You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2438 lines
58 KiB

  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package html
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "strings"
  10. a "golang.org/x/net/html/atom"
  11. )
  12. // A parser implements the HTML5 parsing algorithm:
  13. // https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
  14. type parser struct {
  15. // tokenizer provides the tokens for the parser.
  16. tokenizer *Tokenizer
  17. // tok is the most recently read token.
  18. tok Token
  19. // Self-closing tags like <hr/> are treated as start tags, except that
  20. // hasSelfClosingToken is set while they are being processed.
  21. hasSelfClosingToken bool
  22. // doc is the document root element.
  23. doc *Node
  24. // The stack of open elements (section 12.2.4.2) and active formatting
  25. // elements (section 12.2.4.3).
  26. oe, afe nodeStack
  27. // Element pointers (section 12.2.4.4).
  28. head, form *Node
  29. // Other parsing state flags (section 12.2.4.5).
  30. scripting, framesetOK bool
  31. // The stack of template insertion modes
  32. templateStack insertionModeStack
  33. // im is the current insertion mode.
  34. im insertionMode
  35. // originalIM is the insertion mode to go back to after completing a text
  36. // or inTableText insertion mode.
  37. originalIM insertionMode
  38. // fosterParenting is whether new elements should be inserted according to
  39. // the foster parenting rules (section 12.2.6.1).
  40. fosterParenting bool
  41. // quirks is whether the parser is operating in "quirks mode."
  42. quirks bool
  43. // fragment is whether the parser is parsing an HTML fragment.
  44. fragment bool
  45. // context is the context element when parsing an HTML fragment
  46. // (section 12.4).
  47. context *Node
  48. }
  49. func (p *parser) top() *Node {
  50. if n := p.oe.top(); n != nil {
  51. return n
  52. }
  53. return p.doc
  54. }
  55. // Stop tags for use in popUntil. These come from section 12.2.4.2.
  56. var (
  57. defaultScopeStopTags = map[string][]a.Atom{
  58. "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template},
  59. "math": {a.AnnotationXml, a.Mi, a.Mn, a.Mo, a.Ms, a.Mtext},
  60. "svg": {a.Desc, a.ForeignObject, a.Title},
  61. }
  62. )
  63. type scope int
  64. const (
  65. defaultScope scope = iota
  66. listItemScope
  67. buttonScope
  68. tableScope
  69. tableRowScope
  70. tableBodyScope
  71. selectScope
  72. )
  73. // popUntil pops the stack of open elements at the highest element whose tag
  74. // is in matchTags, provided there is no higher element in the scope's stop
  75. // tags (as defined in section 12.2.4.2). It returns whether or not there was
  76. // such an element. If there was not, popUntil leaves the stack unchanged.
  77. //
  78. // For example, the set of stop tags for table scope is: "html", "table". If
  79. // the stack was:
  80. // ["html", "body", "font", "table", "b", "i", "u"]
  81. // then popUntil(tableScope, "font") would return false, but
  82. // popUntil(tableScope, "i") would return true and the stack would become:
  83. // ["html", "body", "font", "table", "b"]
  84. //
  85. // If an element's tag is in both the stop tags and matchTags, then the stack
  86. // will be popped and the function returns true (provided, of course, there was
  87. // no higher element in the stack that was also in the stop tags). For example,
  88. // popUntil(tableScope, "table") returns true and leaves:
  89. // ["html", "body", "font"]
  90. func (p *parser) popUntil(s scope, matchTags ...a.Atom) bool {
  91. if i := p.indexOfElementInScope(s, matchTags...); i != -1 {
  92. p.oe = p.oe[:i]
  93. return true
  94. }
  95. return false
  96. }
  97. // indexOfElementInScope returns the index in p.oe of the highest element whose
  98. // tag is in matchTags that is in scope. If no matching element is in scope, it
  99. // returns -1.
  100. func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int {
  101. for i := len(p.oe) - 1; i >= 0; i-- {
  102. tagAtom := p.oe[i].DataAtom
  103. if p.oe[i].Namespace == "" {
  104. for _, t := range matchTags {
  105. if t == tagAtom {
  106. return i
  107. }
  108. }
  109. switch s {
  110. case defaultScope:
  111. // No-op.
  112. case listItemScope:
  113. if tagAtom == a.Ol || tagAtom == a.Ul {
  114. return -1
  115. }
  116. case buttonScope:
  117. if tagAtom == a.Button {
  118. return -1
  119. }
  120. case tableScope:
  121. if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template {
  122. return -1
  123. }
  124. case selectScope:
  125. if tagAtom != a.Optgroup && tagAtom != a.Option {
  126. return -1
  127. }
  128. default:
  129. panic("unreachable")
  130. }
  131. }
  132. switch s {
  133. case defaultScope, listItemScope, buttonScope:
  134. for _, t := range defaultScopeStopTags[p.oe[i].Namespace] {
  135. if t == tagAtom {
  136. return -1
  137. }
  138. }
  139. }
  140. }
  141. return -1
  142. }
  143. // elementInScope is like popUntil, except that it doesn't modify the stack of
  144. // open elements.
  145. func (p *parser) elementInScope(s scope, matchTags ...a.Atom) bool {
  146. return p.indexOfElementInScope(s, matchTags...) != -1
  147. }
  148. // clearStackToContext pops elements off the stack of open elements until a
  149. // scope-defined element is found.
  150. func (p *parser) clearStackToContext(s scope) {
  151. for i := len(p.oe) - 1; i >= 0; i-- {
  152. tagAtom := p.oe[i].DataAtom
  153. switch s {
  154. case tableScope:
  155. if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template {
  156. p.oe = p.oe[:i+1]
  157. return
  158. }
  159. case tableRowScope:
  160. if tagAtom == a.Html || tagAtom == a.Tr || tagAtom == a.Template {
  161. p.oe = p.oe[:i+1]
  162. return
  163. }
  164. case tableBodyScope:
  165. if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead || tagAtom == a.Template {
  166. p.oe = p.oe[:i+1]
  167. return
  168. }
  169. default:
  170. panic("unreachable")
  171. }
  172. }
  173. }
  174. // parseGenericRawTextElements implements the generic raw text element parsing
  175. // algorithm defined in 12.2.6.2.
  176. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-elements-that-contain-only-text
  177. // TODO: Since both RAWTEXT and RCDATA states are treated as tokenizer's part
  178. // officially, need to make tokenizer consider both states.
  179. func (p *parser) parseGenericRawTextElement() {
  180. p.addElement()
  181. p.originalIM = p.im
  182. p.im = textIM
  183. }
  184. // generateImpliedEndTags pops nodes off the stack of open elements as long as
  185. // the top node has a tag name of dd, dt, li, optgroup, option, p, rb, rp, rt or rtc.
  186. // If exceptions are specified, nodes with that name will not be popped off.
  187. func (p *parser) generateImpliedEndTags(exceptions ...string) {
  188. var i int
  189. loop:
  190. for i = len(p.oe) - 1; i >= 0; i-- {
  191. n := p.oe[i]
  192. if n.Type != ElementNode {
  193. break
  194. }
  195. switch n.DataAtom {
  196. case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc:
  197. for _, except := range exceptions {
  198. if n.Data == except {
  199. break loop
  200. }
  201. }
  202. continue
  203. }
  204. break
  205. }
  206. p.oe = p.oe[:i+1]
  207. }
  208. // addChild adds a child node n to the top element, and pushes n onto the stack
  209. // of open elements if it is an element node.
  210. func (p *parser) addChild(n *Node) {
  211. if p.shouldFosterParent() {
  212. p.fosterParent(n)
  213. } else {
  214. p.top().AppendChild(n)
  215. }
  216. if n.Type == ElementNode {
  217. p.oe = append(p.oe, n)
  218. }
  219. }
  220. // shouldFosterParent returns whether the next node to be added should be
  221. // foster parented.
  222. func (p *parser) shouldFosterParent() bool {
  223. if p.fosterParenting {
  224. switch p.top().DataAtom {
  225. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  226. return true
  227. }
  228. }
  229. return false
  230. }
  231. // fosterParent adds a child node according to the foster parenting rules.
  232. // Section 12.2.6.1, "foster parenting".
  233. func (p *parser) fosterParent(n *Node) {
  234. var table, parent, prev, template *Node
  235. var i int
  236. for i = len(p.oe) - 1; i >= 0; i-- {
  237. if p.oe[i].DataAtom == a.Table {
  238. table = p.oe[i]
  239. break
  240. }
  241. }
  242. var j int
  243. for j = len(p.oe) - 1; j >= 0; j-- {
  244. if p.oe[j].DataAtom == a.Template {
  245. template = p.oe[j]
  246. break
  247. }
  248. }
  249. if template != nil && (table == nil || j > i) {
  250. template.AppendChild(n)
  251. return
  252. }
  253. if table == nil {
  254. // The foster parent is the html element.
  255. parent = p.oe[0]
  256. } else {
  257. parent = table.Parent
  258. }
  259. if parent == nil {
  260. parent = p.oe[i-1]
  261. }
  262. if table != nil {
  263. prev = table.PrevSibling
  264. } else {
  265. prev = parent.LastChild
  266. }
  267. if prev != nil && prev.Type == TextNode && n.Type == TextNode {
  268. prev.Data += n.Data
  269. return
  270. }
  271. parent.InsertBefore(n, table)
  272. }
  273. // addText adds text to the preceding node if it is a text node, or else it
  274. // calls addChild with a new text node.
  275. func (p *parser) addText(text string) {
  276. if text == "" {
  277. return
  278. }
  279. if p.shouldFosterParent() {
  280. p.fosterParent(&Node{
  281. Type: TextNode,
  282. Data: text,
  283. })
  284. return
  285. }
  286. t := p.top()
  287. if n := t.LastChild; n != nil && n.Type == TextNode {
  288. n.Data += text
  289. return
  290. }
  291. p.addChild(&Node{
  292. Type: TextNode,
  293. Data: text,
  294. })
  295. }
  296. // addElement adds a child element based on the current token.
  297. func (p *parser) addElement() {
  298. p.addChild(&Node{
  299. Type: ElementNode,
  300. DataAtom: p.tok.DataAtom,
  301. Data: p.tok.Data,
  302. Attr: p.tok.Attr,
  303. })
  304. }
  305. // Section 12.2.4.3.
  306. func (p *parser) addFormattingElement() {
  307. tagAtom, attr := p.tok.DataAtom, p.tok.Attr
  308. p.addElement()
  309. // Implement the Noah's Ark clause, but with three per family instead of two.
  310. identicalElements := 0
  311. findIdenticalElements:
  312. for i := len(p.afe) - 1; i >= 0; i-- {
  313. n := p.afe[i]
  314. if n.Type == scopeMarkerNode {
  315. break
  316. }
  317. if n.Type != ElementNode {
  318. continue
  319. }
  320. if n.Namespace != "" {
  321. continue
  322. }
  323. if n.DataAtom != tagAtom {
  324. continue
  325. }
  326. if len(n.Attr) != len(attr) {
  327. continue
  328. }
  329. compareAttributes:
  330. for _, t0 := range n.Attr {
  331. for _, t1 := range attr {
  332. if t0.Key == t1.Key && t0.Namespace == t1.Namespace && t0.Val == t1.Val {
  333. // Found a match for this attribute, continue with the next attribute.
  334. continue compareAttributes
  335. }
  336. }
  337. // If we get here, there is no attribute that matches a.
  338. // Therefore the element is not identical to the new one.
  339. continue findIdenticalElements
  340. }
  341. identicalElements++
  342. if identicalElements >= 3 {
  343. p.afe.remove(n)
  344. }
  345. }
  346. p.afe = append(p.afe, p.top())
  347. }
  348. // Section 12.2.4.3.
  349. func (p *parser) clearActiveFormattingElements() {
  350. for {
  351. if n := p.afe.pop(); len(p.afe) == 0 || n.Type == scopeMarkerNode {
  352. return
  353. }
  354. }
  355. }
  356. // Section 12.2.4.3.
  357. func (p *parser) reconstructActiveFormattingElements() {
  358. n := p.afe.top()
  359. if n == nil {
  360. return
  361. }
  362. if n.Type == scopeMarkerNode || p.oe.index(n) != -1 {
  363. return
  364. }
  365. i := len(p.afe) - 1
  366. for n.Type != scopeMarkerNode && p.oe.index(n) == -1 {
  367. if i == 0 {
  368. i = -1
  369. break
  370. }
  371. i--
  372. n = p.afe[i]
  373. }
  374. for {
  375. i++
  376. clone := p.afe[i].clone()
  377. p.addChild(clone)
  378. p.afe[i] = clone
  379. if i == len(p.afe)-1 {
  380. break
  381. }
  382. }
  383. }
  384. // Section 12.2.5.
  385. func (p *parser) acknowledgeSelfClosingTag() {
  386. p.hasSelfClosingToken = false
  387. }
  388. // An insertion mode (section 12.2.4.1) is the state transition function from
  389. // a particular state in the HTML5 parser's state machine. It updates the
  390. // parser's fields depending on parser.tok (where ErrorToken means EOF).
  391. // It returns whether the token was consumed.
  392. type insertionMode func(*parser) bool
  393. // setOriginalIM sets the insertion mode to return to after completing a text or
  394. // inTableText insertion mode.
  395. // Section 12.2.4.1, "using the rules for".
  396. func (p *parser) setOriginalIM() {
  397. if p.originalIM != nil {
  398. panic("html: bad parser state: originalIM was set twice")
  399. }
  400. p.originalIM = p.im
  401. }
  402. // Section 12.2.4.1, "reset the insertion mode".
  403. func (p *parser) resetInsertionMode() {
  404. for i := len(p.oe) - 1; i >= 0; i-- {
  405. n := p.oe[i]
  406. last := i == 0
  407. if last && p.context != nil {
  408. n = p.context
  409. }
  410. switch n.DataAtom {
  411. case a.Select:
  412. if !last {
  413. for ancestor, first := n, p.oe[0]; ancestor != first; {
  414. ancestor = p.oe[p.oe.index(ancestor)-1]
  415. switch ancestor.DataAtom {
  416. case a.Template:
  417. p.im = inSelectIM
  418. return
  419. case a.Table:
  420. p.im = inSelectInTableIM
  421. return
  422. }
  423. }
  424. }
  425. p.im = inSelectIM
  426. case a.Td, a.Th:
  427. // TODO: remove this divergence from the HTML5 spec.
  428. //
  429. // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668
  430. p.im = inCellIM
  431. case a.Tr:
  432. p.im = inRowIM
  433. case a.Tbody, a.Thead, a.Tfoot:
  434. p.im = inTableBodyIM
  435. case a.Caption:
  436. p.im = inCaptionIM
  437. case a.Colgroup:
  438. p.im = inColumnGroupIM
  439. case a.Table:
  440. p.im = inTableIM
  441. case a.Template:
  442. // TODO: remove this divergence from the HTML5 spec.
  443. if n.Namespace != "" {
  444. continue
  445. }
  446. p.im = p.templateStack.top()
  447. case a.Head:
  448. // TODO: remove this divergence from the HTML5 spec.
  449. //
  450. // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668
  451. p.im = inHeadIM
  452. case a.Body:
  453. p.im = inBodyIM
  454. case a.Frameset:
  455. p.im = inFramesetIM
  456. case a.Html:
  457. if p.head == nil {
  458. p.im = beforeHeadIM
  459. } else {
  460. p.im = afterHeadIM
  461. }
  462. default:
  463. if last {
  464. p.im = inBodyIM
  465. return
  466. }
  467. continue
  468. }
  469. return
  470. }
  471. }
  472. const whitespace = " \t\r\n\f"
  473. // Section 12.2.6.4.1.
  474. func initialIM(p *parser) bool {
  475. switch p.tok.Type {
  476. case TextToken:
  477. p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace)
  478. if len(p.tok.Data) == 0 {
  479. // It was all whitespace, so ignore it.
  480. return true
  481. }
  482. case CommentToken:
  483. p.doc.AppendChild(&Node{
  484. Type: CommentNode,
  485. Data: p.tok.Data,
  486. })
  487. return true
  488. case DoctypeToken:
  489. n, quirks := parseDoctype(p.tok.Data)
  490. p.doc.AppendChild(n)
  491. p.quirks = quirks
  492. p.im = beforeHTMLIM
  493. return true
  494. }
  495. p.quirks = true
  496. p.im = beforeHTMLIM
  497. return false
  498. }
  499. // Section 12.2.6.4.2.
  500. func beforeHTMLIM(p *parser) bool {
  501. switch p.tok.Type {
  502. case DoctypeToken:
  503. // Ignore the token.
  504. return true
  505. case TextToken:
  506. p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace)
  507. if len(p.tok.Data) == 0 {
  508. // It was all whitespace, so ignore it.
  509. return true
  510. }
  511. case StartTagToken:
  512. if p.tok.DataAtom == a.Html {
  513. p.addElement()
  514. p.im = beforeHeadIM
  515. return true
  516. }
  517. case EndTagToken:
  518. switch p.tok.DataAtom {
  519. case a.Head, a.Body, a.Html, a.Br:
  520. p.parseImpliedToken(StartTagToken, a.Html, a.Html.String())
  521. return false
  522. default:
  523. // Ignore the token.
  524. return true
  525. }
  526. case CommentToken:
  527. p.doc.AppendChild(&Node{
  528. Type: CommentNode,
  529. Data: p.tok.Data,
  530. })
  531. return true
  532. }
  533. p.parseImpliedToken(StartTagToken, a.Html, a.Html.String())
  534. return false
  535. }
  536. // Section 12.2.6.4.3.
  537. func beforeHeadIM(p *parser) bool {
  538. switch p.tok.Type {
  539. case TextToken:
  540. p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace)
  541. if len(p.tok.Data) == 0 {
  542. // It was all whitespace, so ignore it.
  543. return true
  544. }
  545. case StartTagToken:
  546. switch p.tok.DataAtom {
  547. case a.Head:
  548. p.addElement()
  549. p.head = p.top()
  550. p.im = inHeadIM
  551. return true
  552. case a.Html:
  553. return inBodyIM(p)
  554. }
  555. case EndTagToken:
  556. switch p.tok.DataAtom {
  557. case a.Head, a.Body, a.Html, a.Br:
  558. p.parseImpliedToken(StartTagToken, a.Head, a.Head.String())
  559. return false
  560. default:
  561. // Ignore the token.
  562. return true
  563. }
  564. case CommentToken:
  565. p.addChild(&Node{
  566. Type: CommentNode,
  567. Data: p.tok.Data,
  568. })
  569. return true
  570. case DoctypeToken:
  571. // Ignore the token.
  572. return true
  573. }
  574. p.parseImpliedToken(StartTagToken, a.Head, a.Head.String())
  575. return false
  576. }
  577. // Section 12.2.6.4.4.
  578. func inHeadIM(p *parser) bool {
  579. switch p.tok.Type {
  580. case TextToken:
  581. s := strings.TrimLeft(p.tok.Data, whitespace)
  582. if len(s) < len(p.tok.Data) {
  583. // Add the initial whitespace to the current node.
  584. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)])
  585. if s == "" {
  586. return true
  587. }
  588. p.tok.Data = s
  589. }
  590. case StartTagToken:
  591. switch p.tok.DataAtom {
  592. case a.Html:
  593. return inBodyIM(p)
  594. case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta:
  595. p.addElement()
  596. p.oe.pop()
  597. p.acknowledgeSelfClosingTag()
  598. return true
  599. case a.Noscript:
  600. if p.scripting {
  601. p.parseGenericRawTextElement()
  602. return true
  603. }
  604. p.addElement()
  605. p.im = inHeadNoscriptIM
  606. // Don't let the tokenizer go into raw text mode when scripting is disabled.
  607. p.tokenizer.NextIsNotRawText()
  608. return true
  609. case a.Script, a.Title:
  610. p.addElement()
  611. p.setOriginalIM()
  612. p.im = textIM
  613. return true
  614. case a.Noframes, a.Style:
  615. p.parseGenericRawTextElement()
  616. return true
  617. case a.Head:
  618. // Ignore the token.
  619. return true
  620. case a.Template:
  621. p.addElement()
  622. p.afe = append(p.afe, &scopeMarker)
  623. p.framesetOK = false
  624. p.im = inTemplateIM
  625. p.templateStack = append(p.templateStack, inTemplateIM)
  626. return true
  627. }
  628. case EndTagToken:
  629. switch p.tok.DataAtom {
  630. case a.Head:
  631. p.oe.pop()
  632. p.im = afterHeadIM
  633. return true
  634. case a.Body, a.Html, a.Br:
  635. p.parseImpliedToken(EndTagToken, a.Head, a.Head.String())
  636. return false
  637. case a.Template:
  638. if !p.oe.contains(a.Template) {
  639. return true
  640. }
  641. // TODO: remove this divergence from the HTML5 spec.
  642. //
  643. // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668
  644. p.generateImpliedEndTags()
  645. for i := len(p.oe) - 1; i >= 0; i-- {
  646. if n := p.oe[i]; n.Namespace == "" && n.DataAtom == a.Template {
  647. p.oe = p.oe[:i]
  648. break
  649. }
  650. }
  651. p.clearActiveFormattingElements()
  652. p.templateStack.pop()
  653. p.resetInsertionMode()
  654. return true
  655. default:
  656. // Ignore the token.
  657. return true
  658. }
  659. case CommentToken:
  660. p.addChild(&Node{
  661. Type: CommentNode,
  662. Data: p.tok.Data,
  663. })
  664. return true
  665. case DoctypeToken:
  666. // Ignore the token.
  667. return true
  668. }
  669. p.parseImpliedToken(EndTagToken, a.Head, a.Head.String())
  670. return false
  671. }
  672. // 12.2.6.4.5.
  673. func inHeadNoscriptIM(p *parser) bool {
  674. switch p.tok.Type {
  675. case DoctypeToken:
  676. // Ignore the token.
  677. return true
  678. case StartTagToken:
  679. switch p.tok.DataAtom {
  680. case a.Html:
  681. return inBodyIM(p)
  682. case a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Style:
  683. return inHeadIM(p)
  684. case a.Head:
  685. // Ignore the token.
  686. return true
  687. case a.Noscript:
  688. // Don't let the tokenizer go into raw text mode even when a <noscript>
  689. // tag is in "in head noscript" insertion mode.
  690. p.tokenizer.NextIsNotRawText()
  691. // Ignore the token.
  692. return true
  693. }
  694. case EndTagToken:
  695. switch p.tok.DataAtom {
  696. case a.Noscript, a.Br:
  697. default:
  698. // Ignore the token.
  699. return true
  700. }
  701. case TextToken:
  702. s := strings.TrimLeft(p.tok.Data, whitespace)
  703. if len(s) == 0 {
  704. // It was all whitespace.
  705. return inHeadIM(p)
  706. }
  707. case CommentToken:
  708. return inHeadIM(p)
  709. }
  710. p.oe.pop()
  711. if p.top().DataAtom != a.Head {
  712. panic("html: the new current node will be a head element.")
  713. }
  714. p.im = inHeadIM
  715. if p.tok.DataAtom == a.Noscript {
  716. return true
  717. }
  718. return false
  719. }
  720. // Section 12.2.6.4.6.
  721. func afterHeadIM(p *parser) bool {
  722. switch p.tok.Type {
  723. case TextToken:
  724. s := strings.TrimLeft(p.tok.Data, whitespace)
  725. if len(s) < len(p.tok.Data) {
  726. // Add the initial whitespace to the current node.
  727. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)])
  728. if s == "" {
  729. return true
  730. }
  731. p.tok.Data = s
  732. }
  733. case StartTagToken:
  734. switch p.tok.DataAtom {
  735. case a.Html:
  736. return inBodyIM(p)
  737. case a.Body:
  738. p.addElement()
  739. p.framesetOK = false
  740. p.im = inBodyIM
  741. return true
  742. case a.Frameset:
  743. p.addElement()
  744. p.im = inFramesetIM
  745. return true
  746. case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
  747. p.oe = append(p.oe, p.head)
  748. defer p.oe.remove(p.head)
  749. return inHeadIM(p)
  750. case a.Head:
  751. // Ignore the token.
  752. return true
  753. }
  754. case EndTagToken:
  755. switch p.tok.DataAtom {
  756. case a.Body, a.Html, a.Br:
  757. // Drop down to creating an implied <body> tag.
  758. case a.Template:
  759. return inHeadIM(p)
  760. default:
  761. // Ignore the token.
  762. return true
  763. }
  764. case CommentToken:
  765. p.addChild(&Node{
  766. Type: CommentNode,
  767. Data: p.tok.Data,
  768. })
  769. return true
  770. case DoctypeToken:
  771. // Ignore the token.
  772. return true
  773. }
  774. p.parseImpliedToken(StartTagToken, a.Body, a.Body.String())
  775. p.framesetOK = true
  776. return false
  777. }
  778. // copyAttributes copies attributes of src not found on dst to dst.
  779. func copyAttributes(dst *Node, src Token) {
  780. if len(src.Attr) == 0 {
  781. return
  782. }
  783. attr := map[string]string{}
  784. for _, t := range dst.Attr {
  785. attr[t.Key] = t.Val
  786. }
  787. for _, t := range src.Attr {
  788. if _, ok := attr[t.Key]; !ok {
  789. dst.Attr = append(dst.Attr, t)
  790. attr[t.Key] = t.Val
  791. }
  792. }
  793. }
  794. // Section 12.2.6.4.7.
  795. func inBodyIM(p *parser) bool {
  796. switch p.tok.Type {
  797. case TextToken:
  798. d := p.tok.Data
  799. switch n := p.oe.top(); n.DataAtom {
  800. case a.Pre, a.Listing:
  801. if n.FirstChild == nil {
  802. // Ignore a newline at the start of a <pre> block.
  803. if d != "" && d[0] == '\r' {
  804. d = d[1:]
  805. }
  806. if d != "" && d[0] == '\n' {
  807. d = d[1:]
  808. }
  809. }
  810. }
  811. d = strings.Replace(d, "\x00", "", -1)
  812. if d == "" {
  813. return true
  814. }
  815. p.reconstructActiveFormattingElements()
  816. p.addText(d)
  817. if p.framesetOK && strings.TrimLeft(d, whitespace) != "" {
  818. // There were non-whitespace characters inserted.
  819. p.framesetOK = false
  820. }
  821. case StartTagToken:
  822. switch p.tok.DataAtom {
  823. case a.Html:
  824. if p.oe.contains(a.Template) {
  825. return true
  826. }
  827. copyAttributes(p.oe[0], p.tok)
  828. case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
  829. return inHeadIM(p)
  830. case a.Body:
  831. if p.oe.contains(a.Template) {
  832. return true
  833. }
  834. if len(p.oe) >= 2 {
  835. body := p.oe[1]
  836. if body.Type == ElementNode && body.DataAtom == a.Body {
  837. p.framesetOK = false
  838. copyAttributes(body, p.tok)
  839. }
  840. }
  841. case a.Frameset:
  842. if !p.framesetOK || len(p.oe) < 2 || p.oe[1].DataAtom != a.Body {
  843. // Ignore the token.
  844. return true
  845. }
  846. body := p.oe[1]
  847. if body.Parent != nil {
  848. body.Parent.RemoveChild(body)
  849. }
  850. p.oe = p.oe[:1]
  851. p.addElement()
  852. p.im = inFramesetIM
  853. return true
  854. case a.Address, a.Article, a.Aside, a.Blockquote, a.Center, a.Details, a.Dialog, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Main, a.Menu, a.Nav, a.Ol, a.P, a.Section, a.Summary, a.Ul:
  855. p.popUntil(buttonScope, a.P)
  856. p.addElement()
  857. case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
  858. p.popUntil(buttonScope, a.P)
  859. switch n := p.top(); n.DataAtom {
  860. case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
  861. p.oe.pop()
  862. }
  863. p.addElement()
  864. case a.Pre, a.Listing:
  865. p.popUntil(buttonScope, a.P)
  866. p.addElement()
  867. // The newline, if any, will be dealt with by the TextToken case.
  868. p.framesetOK = false
  869. case a.Form:
  870. if p.form != nil && !p.oe.contains(a.Template) {
  871. // Ignore the token
  872. return true
  873. }
  874. p.popUntil(buttonScope, a.P)
  875. p.addElement()
  876. if !p.oe.contains(a.Template) {
  877. p.form = p.top()
  878. }
  879. case a.Li:
  880. p.framesetOK = false
  881. for i := len(p.oe) - 1; i >= 0; i-- {
  882. node := p.oe[i]
  883. switch node.DataAtom {
  884. case a.Li:
  885. p.oe = p.oe[:i]
  886. case a.Address, a.Div, a.P:
  887. continue
  888. default:
  889. if !isSpecialElement(node) {
  890. continue
  891. }
  892. }
  893. break
  894. }
  895. p.popUntil(buttonScope, a.P)
  896. p.addElement()
  897. case a.Dd, a.Dt:
  898. p.framesetOK = false
  899. for i := len(p.oe) - 1; i >= 0; i-- {
  900. node := p.oe[i]
  901. switch node.DataAtom {
  902. case a.Dd, a.Dt:
  903. p.oe = p.oe[:i]
  904. case a.Address, a.Div, a.P:
  905. continue
  906. default:
  907. if !isSpecialElement(node) {
  908. continue
  909. }
  910. }
  911. break
  912. }
  913. p.popUntil(buttonScope, a.P)
  914. p.addElement()
  915. case a.Plaintext:
  916. p.popUntil(buttonScope, a.P)
  917. p.addElement()
  918. case a.Button:
  919. p.popUntil(defaultScope, a.Button)
  920. p.reconstructActiveFormattingElements()
  921. p.addElement()
  922. p.framesetOK = false
  923. case a.A:
  924. for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- {
  925. if n := p.afe[i]; n.Type == ElementNode && n.DataAtom == a.A {
  926. p.inBodyEndTagFormatting(a.A, "a")
  927. p.oe.remove(n)
  928. p.afe.remove(n)
  929. break
  930. }
  931. }
  932. p.reconstructActiveFormattingElements()
  933. p.addFormattingElement()
  934. case a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
  935. p.reconstructActiveFormattingElements()
  936. p.addFormattingElement()
  937. case a.Nobr:
  938. p.reconstructActiveFormattingElements()
  939. if p.elementInScope(defaultScope, a.Nobr) {
  940. p.inBodyEndTagFormatting(a.Nobr, "nobr")
  941. p.reconstructActiveFormattingElements()
  942. }
  943. p.addFormattingElement()
  944. case a.Applet, a.Marquee, a.Object:
  945. p.reconstructActiveFormattingElements()
  946. p.addElement()
  947. p.afe = append(p.afe, &scopeMarker)
  948. p.framesetOK = false
  949. case a.Table:
  950. if !p.quirks {
  951. p.popUntil(buttonScope, a.P)
  952. }
  953. p.addElement()
  954. p.framesetOK = false
  955. p.im = inTableIM
  956. return true
  957. case a.Area, a.Br, a.Embed, a.Img, a.Input, a.Keygen, a.Wbr:
  958. p.reconstructActiveFormattingElements()
  959. p.addElement()
  960. p.oe.pop()
  961. p.acknowledgeSelfClosingTag()
  962. if p.tok.DataAtom == a.Input {
  963. for _, t := range p.tok.Attr {
  964. if t.Key == "type" {
  965. if strings.ToLower(t.Val) == "hidden" {
  966. // Skip setting framesetOK = false
  967. return true
  968. }
  969. }
  970. }
  971. }
  972. p.framesetOK = false
  973. case a.Param, a.Source, a.Track:
  974. p.addElement()
  975. p.oe.pop()
  976. p.acknowledgeSelfClosingTag()
  977. case a.Hr:
  978. p.popUntil(buttonScope, a.P)
  979. p.addElement()
  980. p.oe.pop()
  981. p.acknowledgeSelfClosingTag()
  982. p.framesetOK = false
  983. case a.Image:
  984. p.tok.DataAtom = a.Img
  985. p.tok.Data = a.Img.String()
  986. return false
  987. case a.Textarea:
  988. p.addElement()
  989. p.setOriginalIM()
  990. p.framesetOK = false
  991. p.im = textIM
  992. case a.Xmp:
  993. p.popUntil(buttonScope, a.P)
  994. p.reconstructActiveFormattingElements()
  995. p.framesetOK = false
  996. p.parseGenericRawTextElement()
  997. case a.Iframe:
  998. p.framesetOK = false
  999. p.parseGenericRawTextElement()
  1000. case a.Noembed:
  1001. p.parseGenericRawTextElement()
  1002. case a.Noscript:
  1003. if p.scripting {
  1004. p.parseGenericRawTextElement()
  1005. return true
  1006. }
  1007. p.reconstructActiveFormattingElements()
  1008. p.addElement()
  1009. // Don't let the tokenizer go into raw text mode when scripting is disabled.
  1010. p.tokenizer.NextIsNotRawText()
  1011. case a.Select:
  1012. p.reconstructActiveFormattingElements()
  1013. p.addElement()
  1014. p.framesetOK = false
  1015. p.im = inSelectIM
  1016. return true
  1017. case a.Optgroup, a.Option:
  1018. if p.top().DataAtom == a.Option {
  1019. p.oe.pop()
  1020. }
  1021. p.reconstructActiveFormattingElements()
  1022. p.addElement()
  1023. case a.Rb, a.Rtc:
  1024. if p.elementInScope(defaultScope, a.Ruby) {
  1025. p.generateImpliedEndTags()
  1026. }
  1027. p.addElement()
  1028. case a.Rp, a.Rt:
  1029. if p.elementInScope(defaultScope, a.Ruby) {
  1030. p.generateImpliedEndTags("rtc")
  1031. }
  1032. p.addElement()
  1033. case a.Math, a.Svg:
  1034. p.reconstructActiveFormattingElements()
  1035. if p.tok.DataAtom == a.Math {
  1036. adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments)
  1037. } else {
  1038. adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments)
  1039. }
  1040. adjustForeignAttributes(p.tok.Attr)
  1041. p.addElement()
  1042. p.top().Namespace = p.tok.Data
  1043. if p.hasSelfClosingToken {
  1044. p.oe.pop()
  1045. p.acknowledgeSelfClosingTag()
  1046. }
  1047. return true
  1048. case a.Caption, a.Col, a.Colgroup, a.Frame, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1049. // Ignore the token.
  1050. default:
  1051. p.reconstructActiveFormattingElements()
  1052. p.addElement()
  1053. }
  1054. case EndTagToken:
  1055. switch p.tok.DataAtom {
  1056. case a.Body:
  1057. if p.elementInScope(defaultScope, a.Body) {
  1058. p.im = afterBodyIM
  1059. }
  1060. case a.Html:
  1061. if p.elementInScope(defaultScope, a.Body) {
  1062. p.parseImpliedToken(EndTagToken, a.Body, a.Body.String())
  1063. return false
  1064. }
  1065. return true
  1066. case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dialog, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Main, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul:
  1067. p.popUntil(defaultScope, p.tok.DataAtom)
  1068. case a.Form:
  1069. if p.oe.contains(a.Template) {
  1070. i := p.indexOfElementInScope(defaultScope, a.Form)
  1071. if i == -1 {
  1072. // Ignore the token.
  1073. return true
  1074. }
  1075. p.generateImpliedEndTags()
  1076. if p.oe[i].DataAtom != a.Form {
  1077. // Ignore the token.
  1078. return true
  1079. }
  1080. p.popUntil(defaultScope, a.Form)
  1081. } else {
  1082. node := p.form
  1083. p.form = nil
  1084. i := p.indexOfElementInScope(defaultScope, a.Form)
  1085. if node == nil || i == -1 || p.oe[i] != node {
  1086. // Ignore the token.
  1087. return true
  1088. }
  1089. p.generateImpliedEndTags()
  1090. p.oe.remove(node)
  1091. }
  1092. case a.P:
  1093. if !p.elementInScope(buttonScope, a.P) {
  1094. p.parseImpliedToken(StartTagToken, a.P, a.P.String())
  1095. }
  1096. p.popUntil(buttonScope, a.P)
  1097. case a.Li:
  1098. p.popUntil(listItemScope, a.Li)
  1099. case a.Dd, a.Dt:
  1100. p.popUntil(defaultScope, p.tok.DataAtom)
  1101. case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
  1102. p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6)
  1103. case a.A, a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.Nobr, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
  1104. p.inBodyEndTagFormatting(p.tok.DataAtom, p.tok.Data)
  1105. case a.Applet, a.Marquee, a.Object:
  1106. if p.popUntil(defaultScope, p.tok.DataAtom) {
  1107. p.clearActiveFormattingElements()
  1108. }
  1109. case a.Br:
  1110. p.tok.Type = StartTagToken
  1111. return false
  1112. case a.Template:
  1113. return inHeadIM(p)
  1114. default:
  1115. p.inBodyEndTagOther(p.tok.DataAtom, p.tok.Data)
  1116. }
  1117. case CommentToken:
  1118. p.addChild(&Node{
  1119. Type: CommentNode,
  1120. Data: p.tok.Data,
  1121. })
  1122. case ErrorToken:
  1123. // TODO: remove this divergence from the HTML5 spec.
  1124. if len(p.templateStack) > 0 {
  1125. p.im = inTemplateIM
  1126. return false
  1127. }
  1128. for _, e := range p.oe {
  1129. switch e.DataAtom {
  1130. case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc, a.Tbody, a.Td, a.Tfoot, a.Th,
  1131. a.Thead, a.Tr, a.Body, a.Html:
  1132. default:
  1133. return true
  1134. }
  1135. }
  1136. }
  1137. return true
  1138. }
  1139. func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom, tagName string) {
  1140. // This is the "adoption agency" algorithm, described at
  1141. // https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency
  1142. // TODO: this is a fairly literal line-by-line translation of that algorithm.
  1143. // Once the code successfully parses the comprehensive test suite, we should
  1144. // refactor this code to be more idiomatic.
  1145. // Steps 1-2
  1146. if current := p.oe.top(); current.Data == tagName && p.afe.index(current) == -1 {
  1147. p.oe.pop()
  1148. return
  1149. }
  1150. // Steps 3-5. The outer loop.
  1151. for i := 0; i < 8; i++ {
  1152. // Step 6. Find the formatting element.
  1153. var formattingElement *Node
  1154. for j := len(p.afe) - 1; j >= 0; j-- {
  1155. if p.afe[j].Type == scopeMarkerNode {
  1156. break
  1157. }
  1158. if p.afe[j].DataAtom == tagAtom {
  1159. formattingElement = p.afe[j]
  1160. break
  1161. }
  1162. }
  1163. if formattingElement == nil {
  1164. p.inBodyEndTagOther(tagAtom, tagName)
  1165. return
  1166. }
  1167. // Step 7. Ignore the tag if formatting element is not in the stack of open elements.
  1168. feIndex := p.oe.index(formattingElement)
  1169. if feIndex == -1 {
  1170. p.afe.remove(formattingElement)
  1171. return
  1172. }
  1173. // Step 8. Ignore the tag if formatting element is not in the scope.
  1174. if !p.elementInScope(defaultScope, tagAtom) {
  1175. // Ignore the tag.
  1176. return
  1177. }
  1178. // Step 9. This step is omitted because it's just a parse error but no need to return.
  1179. // Steps 10-11. Find the furthest block.
  1180. var furthestBlock *Node
  1181. for _, e := range p.oe[feIndex:] {
  1182. if isSpecialElement(e) {
  1183. furthestBlock = e
  1184. break
  1185. }
  1186. }
  1187. if furthestBlock == nil {
  1188. e := p.oe.pop()
  1189. for e != formattingElement {
  1190. e = p.oe.pop()
  1191. }
  1192. p.afe.remove(e)
  1193. return
  1194. }
  1195. // Steps 12-13. Find the common ancestor and bookmark node.
  1196. commonAncestor := p.oe[feIndex-1]
  1197. bookmark := p.afe.index(formattingElement)
  1198. // Step 14. The inner loop. Find the lastNode to reparent.
  1199. lastNode := furthestBlock
  1200. node := furthestBlock
  1201. x := p.oe.index(node)
  1202. // Step 14.1.
  1203. j := 0
  1204. for {
  1205. // Step 14.2.
  1206. j++
  1207. // Step. 14.3.
  1208. x--
  1209. node = p.oe[x]
  1210. // Step 14.4. Go to the next step if node is formatting element.
  1211. if node == formattingElement {
  1212. break
  1213. }
  1214. // Step 14.5. Remove node from the list of active formatting elements if
  1215. // inner loop counter is greater than three and node is in the list of
  1216. // active formatting elements.
  1217. if ni := p.afe.index(node); j > 3 && ni > -1 {
  1218. p.afe.remove(node)
  1219. // If any element of the list of active formatting elements is removed,
  1220. // we need to take care whether bookmark should be decremented or not.
  1221. // This is because the value of bookmark may exceed the size of the
  1222. // list by removing elements from the list.
  1223. if ni <= bookmark {
  1224. bookmark--
  1225. }
  1226. continue
  1227. }
  1228. // Step 14.6. Continue the next inner loop if node is not in the list of
  1229. // active formatting elements.
  1230. if p.afe.index(node) == -1 {
  1231. p.oe.remove(node)
  1232. continue
  1233. }
  1234. // Step 14.7.
  1235. clone := node.clone()
  1236. p.afe[p.afe.index(node)] = clone
  1237. p.oe[p.oe.index(node)] = clone
  1238. node = clone
  1239. // Step 14.8.
  1240. if lastNode == furthestBlock {
  1241. bookmark = p.afe.index(node) + 1
  1242. }
  1243. // Step 14.9.
  1244. if lastNode.Parent != nil {
  1245. lastNode.Parent.RemoveChild(lastNode)
  1246. }
  1247. node.AppendChild(lastNode)
  1248. // Step 14.10.
  1249. lastNode = node
  1250. }
  1251. // Step 15. Reparent lastNode to the common ancestor,
  1252. // or for misnested table nodes, to the foster parent.
  1253. if lastNode.Parent != nil {
  1254. lastNode.Parent.RemoveChild(lastNode)
  1255. }
  1256. switch commonAncestor.DataAtom {
  1257. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1258. p.fosterParent(lastNode)
  1259. default:
  1260. commonAncestor.AppendChild(lastNode)
  1261. }
  1262. // Steps 16-18. Reparent nodes from the furthest block's children
  1263. // to a clone of the formatting element.
  1264. clone := formattingElement.clone()
  1265. reparentChildren(clone, furthestBlock)
  1266. furthestBlock.AppendChild(clone)
  1267. // Step 19. Fix up the list of active formatting elements.
  1268. if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark {
  1269. // Move the bookmark with the rest of the list.
  1270. bookmark--
  1271. }
  1272. p.afe.remove(formattingElement)
  1273. p.afe.insert(bookmark, clone)
  1274. // Step 20. Fix up the stack of open elements.
  1275. p.oe.remove(formattingElement)
  1276. p.oe.insert(p.oe.index(furthestBlock)+1, clone)
  1277. }
  1278. }
  1279. // inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM.
  1280. // "Any other end tag" handling from 12.2.6.5 The rules for parsing tokens in foreign content
  1281. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign
  1282. func (p *parser) inBodyEndTagOther(tagAtom a.Atom, tagName string) {
  1283. for i := len(p.oe) - 1; i >= 0; i-- {
  1284. // Two element nodes have the same tag if they have the same Data (a
  1285. // string-typed field). As an optimization, for common HTML tags, each
  1286. // Data string is assigned a unique, non-zero DataAtom (a uint32-typed
  1287. // field), since integer comparison is faster than string comparison.
  1288. // Uncommon (custom) tags get a zero DataAtom.
  1289. //
  1290. // The if condition here is equivalent to (p.oe[i].Data == tagName).
  1291. if (p.oe[i].DataAtom == tagAtom) &&
  1292. ((tagAtom != 0) || (p.oe[i].Data == tagName)) {
  1293. p.oe = p.oe[:i]
  1294. break
  1295. }
  1296. if isSpecialElement(p.oe[i]) {
  1297. break
  1298. }
  1299. }
  1300. }
  1301. // Section 12.2.6.4.8.
  1302. func textIM(p *parser) bool {
  1303. switch p.tok.Type {
  1304. case ErrorToken:
  1305. p.oe.pop()
  1306. case TextToken:
  1307. d := p.tok.Data
  1308. if n := p.oe.top(); n.DataAtom == a.Textarea && n.FirstChild == nil {
  1309. // Ignore a newline at the start of a <textarea> block.
  1310. if d != "" && d[0] == '\r' {
  1311. d = d[1:]
  1312. }
  1313. if d != "" && d[0] == '\n' {
  1314. d = d[1:]
  1315. }
  1316. }
  1317. if d == "" {
  1318. return true
  1319. }
  1320. p.addText(d)
  1321. return true
  1322. case EndTagToken:
  1323. p.oe.pop()
  1324. }
  1325. p.im = p.originalIM
  1326. p.originalIM = nil
  1327. return p.tok.Type == EndTagToken
  1328. }
  1329. // Section 12.2.6.4.9.
  1330. func inTableIM(p *parser) bool {
  1331. switch p.tok.Type {
  1332. case TextToken:
  1333. p.tok.Data = strings.Replace(p.tok.Data, "\x00", "", -1)
  1334. switch p.oe.top().DataAtom {
  1335. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1336. if strings.Trim(p.tok.Data, whitespace) == "" {
  1337. p.addText(p.tok.Data)
  1338. return true
  1339. }
  1340. }
  1341. case StartTagToken:
  1342. switch p.tok.DataAtom {
  1343. case a.Caption:
  1344. p.clearStackToContext(tableScope)
  1345. p.afe = append(p.afe, &scopeMarker)
  1346. p.addElement()
  1347. p.im = inCaptionIM
  1348. return true
  1349. case a.Colgroup:
  1350. p.clearStackToContext(tableScope)
  1351. p.addElement()
  1352. p.im = inColumnGroupIM
  1353. return true
  1354. case a.Col:
  1355. p.parseImpliedToken(StartTagToken, a.Colgroup, a.Colgroup.String())
  1356. return false
  1357. case a.Tbody, a.Tfoot, a.Thead:
  1358. p.clearStackToContext(tableScope)
  1359. p.addElement()
  1360. p.im = inTableBodyIM
  1361. return true
  1362. case a.Td, a.Th, a.Tr:
  1363. p.parseImpliedToken(StartTagToken, a.Tbody, a.Tbody.String())
  1364. return false
  1365. case a.Table:
  1366. if p.popUntil(tableScope, a.Table) {
  1367. p.resetInsertionMode()
  1368. return false
  1369. }
  1370. // Ignore the token.
  1371. return true
  1372. case a.Style, a.Script, a.Template:
  1373. return inHeadIM(p)
  1374. case a.Input:
  1375. for _, t := range p.tok.Attr {
  1376. if t.Key == "type" && strings.ToLower(t.Val) == "hidden" {
  1377. p.addElement()
  1378. p.oe.pop()
  1379. return true
  1380. }
  1381. }
  1382. // Otherwise drop down to the default action.
  1383. case a.Form:
  1384. if p.oe.contains(a.Template) || p.form != nil {
  1385. // Ignore the token.
  1386. return true
  1387. }
  1388. p.addElement()
  1389. p.form = p.oe.pop()
  1390. case a.Select:
  1391. p.reconstructActiveFormattingElements()
  1392. switch p.top().DataAtom {
  1393. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1394. p.fosterParenting = true
  1395. }
  1396. p.addElement()
  1397. p.fosterParenting = false
  1398. p.framesetOK = false
  1399. p.im = inSelectInTableIM
  1400. return true
  1401. }
  1402. case EndTagToken:
  1403. switch p.tok.DataAtom {
  1404. case a.Table:
  1405. if p.popUntil(tableScope, a.Table) {
  1406. p.resetInsertionMode()
  1407. return true
  1408. }
  1409. // Ignore the token.
  1410. return true
  1411. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1412. // Ignore the token.
  1413. return true
  1414. case a.Template:
  1415. return inHeadIM(p)
  1416. }
  1417. case CommentToken:
  1418. p.addChild(&Node{
  1419. Type: CommentNode,
  1420. Data: p.tok.Data,
  1421. })
  1422. return true
  1423. case DoctypeToken:
  1424. // Ignore the token.
  1425. return true
  1426. case ErrorToken:
  1427. return inBodyIM(p)
  1428. }
  1429. p.fosterParenting = true
  1430. defer func() { p.fosterParenting = false }()
  1431. return inBodyIM(p)
  1432. }
  1433. // Section 12.2.6.4.11.
  1434. func inCaptionIM(p *parser) bool {
  1435. switch p.tok.Type {
  1436. case StartTagToken:
  1437. switch p.tok.DataAtom {
  1438. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Thead, a.Tr:
  1439. if !p.popUntil(tableScope, a.Caption) {
  1440. // Ignore the token.
  1441. return true
  1442. }
  1443. p.clearActiveFormattingElements()
  1444. p.im = inTableIM
  1445. return false
  1446. case a.Select:
  1447. p.reconstructActiveFormattingElements()
  1448. p.addElement()
  1449. p.framesetOK = false
  1450. p.im = inSelectInTableIM
  1451. return true
  1452. }
  1453. case EndTagToken:
  1454. switch p.tok.DataAtom {
  1455. case a.Caption:
  1456. if p.popUntil(tableScope, a.Caption) {
  1457. p.clearActiveFormattingElements()
  1458. p.im = inTableIM
  1459. }
  1460. return true
  1461. case a.Table:
  1462. if !p.popUntil(tableScope, a.Caption) {
  1463. // Ignore the token.
  1464. return true
  1465. }
  1466. p.clearActiveFormattingElements()
  1467. p.im = inTableIM
  1468. return false
  1469. case a.Body, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1470. // Ignore the token.
  1471. return true
  1472. }
  1473. }
  1474. return inBodyIM(p)
  1475. }
  1476. // Section 12.2.6.4.12.
  1477. func inColumnGroupIM(p *parser) bool {
  1478. switch p.tok.Type {
  1479. case TextToken:
  1480. s := strings.TrimLeft(p.tok.Data, whitespace)
  1481. if len(s) < len(p.tok.Data) {
  1482. // Add the initial whitespace to the current node.
  1483. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)])
  1484. if s == "" {
  1485. return true
  1486. }
  1487. p.tok.Data = s
  1488. }
  1489. case CommentToken:
  1490. p.addChild(&Node{
  1491. Type: CommentNode,
  1492. Data: p.tok.Data,
  1493. })
  1494. return true
  1495. case DoctypeToken:
  1496. // Ignore the token.
  1497. return true
  1498. case StartTagToken:
  1499. switch p.tok.DataAtom {
  1500. case a.Html:
  1501. return inBodyIM(p)
  1502. case a.Col:
  1503. p.addElement()
  1504. p.oe.pop()
  1505. p.acknowledgeSelfClosingTag()
  1506. return true
  1507. case a.Template:
  1508. return inHeadIM(p)
  1509. }
  1510. case EndTagToken:
  1511. switch p.tok.DataAtom {
  1512. case a.Colgroup:
  1513. if p.oe.top().DataAtom == a.Colgroup {
  1514. p.oe.pop()
  1515. p.im = inTableIM
  1516. }
  1517. return true
  1518. case a.Col:
  1519. // Ignore the token.
  1520. return true
  1521. case a.Template:
  1522. return inHeadIM(p)
  1523. }
  1524. case ErrorToken:
  1525. return inBodyIM(p)
  1526. }
  1527. if p.oe.top().DataAtom != a.Colgroup {
  1528. return true
  1529. }
  1530. p.oe.pop()
  1531. p.im = inTableIM
  1532. return false
  1533. }
  1534. // Section 12.2.6.4.13.
  1535. func inTableBodyIM(p *parser) bool {
  1536. switch p.tok.Type {
  1537. case StartTagToken:
  1538. switch p.tok.DataAtom {
  1539. case a.Tr:
  1540. p.clearStackToContext(tableBodyScope)
  1541. p.addElement()
  1542. p.im = inRowIM
  1543. return true
  1544. case a.Td, a.Th:
  1545. p.parseImpliedToken(StartTagToken, a.Tr, a.Tr.String())
  1546. return false
  1547. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Tfoot, a.Thead:
  1548. if p.popUntil(tableScope, a.Tbody, a.Thead, a.Tfoot) {
  1549. p.im = inTableIM
  1550. return false
  1551. }
  1552. // Ignore the token.
  1553. return true
  1554. }
  1555. case EndTagToken:
  1556. switch p.tok.DataAtom {
  1557. case a.Tbody, a.Tfoot, a.Thead:
  1558. if p.elementInScope(tableScope, p.tok.DataAtom) {
  1559. p.clearStackToContext(tableBodyScope)
  1560. p.oe.pop()
  1561. p.im = inTableIM
  1562. }
  1563. return true
  1564. case a.Table:
  1565. if p.popUntil(tableScope, a.Tbody, a.Thead, a.Tfoot) {
  1566. p.im = inTableIM
  1567. return false
  1568. }
  1569. // Ignore the token.
  1570. return true
  1571. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Td, a.Th, a.Tr:
  1572. // Ignore the token.
  1573. return true
  1574. }
  1575. case CommentToken:
  1576. p.addChild(&Node{
  1577. Type: CommentNode,
  1578. Data: p.tok.Data,
  1579. })
  1580. return true
  1581. }
  1582. return inTableIM(p)
  1583. }
  1584. // Section 12.2.6.4.14.
  1585. func inRowIM(p *parser) bool {
  1586. switch p.tok.Type {
  1587. case StartTagToken:
  1588. switch p.tok.DataAtom {
  1589. case a.Td, a.Th:
  1590. p.clearStackToContext(tableRowScope)
  1591. p.addElement()
  1592. p.afe = append(p.afe, &scopeMarker)
  1593. p.im = inCellIM
  1594. return true
  1595. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1596. if p.popUntil(tableScope, a.Tr) {
  1597. p.im = inTableBodyIM
  1598. return false
  1599. }
  1600. // Ignore the token.
  1601. return true
  1602. }
  1603. case EndTagToken:
  1604. switch p.tok.DataAtom {
  1605. case a.Tr:
  1606. if p.popUntil(tableScope, a.Tr) {
  1607. p.im = inTableBodyIM
  1608. return true
  1609. }
  1610. // Ignore the token.
  1611. return true
  1612. case a.Table:
  1613. if p.popUntil(tableScope, a.Tr) {
  1614. p.im = inTableBodyIM
  1615. return false
  1616. }
  1617. // Ignore the token.
  1618. return true
  1619. case a.Tbody, a.Tfoot, a.Thead:
  1620. if p.elementInScope(tableScope, p.tok.DataAtom) {
  1621. p.parseImpliedToken(EndTagToken, a.Tr, a.Tr.String())
  1622. return false
  1623. }
  1624. // Ignore the token.
  1625. return true
  1626. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Td, a.Th:
  1627. // Ignore the token.
  1628. return true
  1629. }
  1630. }
  1631. return inTableIM(p)
  1632. }
  1633. // Section 12.2.6.4.15.
  1634. func inCellIM(p *parser) bool {
  1635. switch p.tok.Type {
  1636. case StartTagToken:
  1637. switch p.tok.DataAtom {
  1638. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1639. if p.popUntil(tableScope, a.Td, a.Th) {
  1640. // Close the cell and reprocess.
  1641. p.clearActiveFormattingElements()
  1642. p.im = inRowIM
  1643. return false
  1644. }
  1645. // Ignore the token.
  1646. return true
  1647. case a.Select:
  1648. p.reconstructActiveFormattingElements()
  1649. p.addElement()
  1650. p.framesetOK = false
  1651. p.im = inSelectInTableIM
  1652. return true
  1653. }
  1654. case EndTagToken:
  1655. switch p.tok.DataAtom {
  1656. case a.Td, a.Th:
  1657. if !p.popUntil(tableScope, p.tok.DataAtom) {
  1658. // Ignore the token.
  1659. return true
  1660. }
  1661. p.clearActiveFormattingElements()
  1662. p.im = inRowIM
  1663. return true
  1664. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html:
  1665. // Ignore the token.
  1666. return true
  1667. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1668. if !p.elementInScope(tableScope, p.tok.DataAtom) {
  1669. // Ignore the token.
  1670. return true
  1671. }
  1672. // Close the cell and reprocess.
  1673. if p.popUntil(tableScope, a.Td, a.Th) {
  1674. p.clearActiveFormattingElements()
  1675. }
  1676. p.im = inRowIM
  1677. return false
  1678. }
  1679. }
  1680. return inBodyIM(p)
  1681. }
  1682. // Section 12.2.6.4.16.
  1683. func inSelectIM(p *parser) bool {
  1684. switch p.tok.Type {
  1685. case TextToken:
  1686. p.addText(strings.Replace(p.tok.Data, "\x00", "", -1))
  1687. case StartTagToken:
  1688. switch p.tok.DataAtom {
  1689. case a.Html:
  1690. return inBodyIM(p)
  1691. case a.Option:
  1692. if p.top().DataAtom == a.Option {
  1693. p.oe.pop()
  1694. }
  1695. p.addElement()
  1696. case a.Optgroup:
  1697. if p.top().DataAtom == a.Option {
  1698. p.oe.pop()
  1699. }
  1700. if p.top().DataAtom == a.Optgroup {
  1701. p.oe.pop()
  1702. }
  1703. p.addElement()
  1704. case a.Select:
  1705. if !p.popUntil(selectScope, a.Select) {
  1706. // Ignore the token.
  1707. return true
  1708. }
  1709. p.resetInsertionMode()
  1710. case a.Input, a.Keygen, a.Textarea:
  1711. if p.elementInScope(selectScope, a.Select) {
  1712. p.parseImpliedToken(EndTagToken, a.Select, a.Select.String())
  1713. return false
  1714. }
  1715. // In order to properly ignore <textarea>, we need to change the tokenizer mode.
  1716. p.tokenizer.NextIsNotRawText()
  1717. // Ignore the token.
  1718. return true
  1719. case a.Script, a.Template:
  1720. return inHeadIM(p)
  1721. case a.Iframe, a.Noembed, a.Noframes, a.Noscript, a.Plaintext, a.Style, a.Title, a.Xmp:
  1722. // Don't let the tokenizer go into raw text mode when there are raw tags
  1723. // to be ignored. These tags should be ignored from the tokenizer
  1724. // properly.
  1725. p.tokenizer.NextIsNotRawText()
  1726. // Ignore the token.
  1727. return true
  1728. }
  1729. case EndTagToken:
  1730. switch p.tok.DataAtom {
  1731. case a.Option:
  1732. if p.top().DataAtom == a.Option {
  1733. p.oe.pop()
  1734. }
  1735. case a.Optgroup:
  1736. i := len(p.oe) - 1
  1737. if p.oe[i].DataAtom == a.Option {
  1738. i--
  1739. }
  1740. if p.oe[i].DataAtom == a.Optgroup {
  1741. p.oe = p.oe[:i]
  1742. }
  1743. case a.Select:
  1744. if !p.popUntil(selectScope, a.Select) {
  1745. // Ignore the token.
  1746. return true
  1747. }
  1748. p.resetInsertionMode()
  1749. case a.Template:
  1750. return inHeadIM(p)
  1751. }
  1752. case CommentToken:
  1753. p.addChild(&Node{
  1754. Type: CommentNode,
  1755. Data: p.tok.Data,
  1756. })
  1757. case DoctypeToken:
  1758. // Ignore the token.
  1759. return true
  1760. case ErrorToken:
  1761. return inBodyIM(p)
  1762. }
  1763. return true
  1764. }
  1765. // Section 12.2.6.4.17.
  1766. func inSelectInTableIM(p *parser) bool {
  1767. switch p.tok.Type {
  1768. case StartTagToken, EndTagToken:
  1769. switch p.tok.DataAtom {
  1770. case a.Caption, a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr, a.Td, a.Th:
  1771. if p.tok.Type == EndTagToken && !p.elementInScope(tableScope, p.tok.DataAtom) {
  1772. // Ignore the token.
  1773. return true
  1774. }
  1775. // This is like p.popUntil(selectScope, a.Select), but it also
  1776. // matches <math select>, not just <select>. Matching the MathML
  1777. // tag is arguably incorrect (conceptually), but it mimics what
  1778. // Chromium does.
  1779. for i := len(p.oe) - 1; i >= 0; i-- {
  1780. if n := p.oe[i]; n.DataAtom == a.Select {
  1781. p.oe = p.oe[:i]
  1782. break
  1783. }
  1784. }
  1785. p.resetInsertionMode()
  1786. return false
  1787. }
  1788. }
  1789. return inSelectIM(p)
  1790. }
  1791. // Section 12.2.6.4.18.
  1792. func inTemplateIM(p *parser) bool {
  1793. switch p.tok.Type {
  1794. case TextToken, CommentToken, DoctypeToken:
  1795. return inBodyIM(p)
  1796. case StartTagToken:
  1797. switch p.tok.DataAtom {
  1798. case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
  1799. return inHeadIM(p)
  1800. case a.Caption, a.Colgroup, a.Tbody, a.Tfoot, a.Thead:
  1801. p.templateStack.pop()
  1802. p.templateStack = append(p.templateStack, inTableIM)
  1803. p.im = inTableIM
  1804. return false
  1805. case a.Col:
  1806. p.templateStack.pop()
  1807. p.templateStack = append(p.templateStack, inColumnGroupIM)
  1808. p.im = inColumnGroupIM
  1809. return false
  1810. case a.Tr:
  1811. p.templateStack.pop()
  1812. p.templateStack = append(p.templateStack, inTableBodyIM)
  1813. p.im = inTableBodyIM
  1814. return false
  1815. case a.Td, a.Th:
  1816. p.templateStack.pop()
  1817. p.templateStack = append(p.templateStack, inRowIM)
  1818. p.im = inRowIM
  1819. return false
  1820. default:
  1821. p.templateStack.pop()
  1822. p.templateStack = append(p.templateStack, inBodyIM)
  1823. p.im = inBodyIM
  1824. return false
  1825. }
  1826. case EndTagToken:
  1827. switch p.tok.DataAtom {
  1828. case a.Template:
  1829. return inHeadIM(p)
  1830. default:
  1831. // Ignore the token.
  1832. return true
  1833. }
  1834. case ErrorToken:
  1835. if !p.oe.contains(a.Template) {
  1836. // Ignore the token.
  1837. return true
  1838. }
  1839. // TODO: remove this divergence from the HTML5 spec.
  1840. //
  1841. // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668
  1842. p.generateImpliedEndTags()
  1843. for i := len(p.oe) - 1; i >= 0; i-- {
  1844. if n := p.oe[i]; n.Namespace == "" && n.DataAtom == a.Template {
  1845. p.oe = p.oe[:i]
  1846. break
  1847. }
  1848. }
  1849. p.clearActiveFormattingElements()
  1850. p.templateStack.pop()
  1851. p.resetInsertionMode()
  1852. return false
  1853. }
  1854. return false
  1855. }
  1856. // Section 12.2.6.4.19.
  1857. func afterBodyIM(p *parser) bool {
  1858. switch p.tok.Type {
  1859. case ErrorToken:
  1860. // Stop parsing.
  1861. return true
  1862. case TextToken:
  1863. s := strings.TrimLeft(p.tok.Data, whitespace)
  1864. if len(s) == 0 {
  1865. // It was all whitespace.
  1866. return inBodyIM(p)
  1867. }
  1868. case StartTagToken:
  1869. if p.tok.DataAtom == a.Html {
  1870. return inBodyIM(p)
  1871. }
  1872. case EndTagToken:
  1873. if p.tok.DataAtom == a.Html {
  1874. if !p.fragment {
  1875. p.im = afterAfterBodyIM
  1876. }
  1877. return true
  1878. }
  1879. case CommentToken:
  1880. // The comment is attached to the <html> element.
  1881. if len(p.oe) < 1 || p.oe[0].DataAtom != a.Html {
  1882. panic("html: bad parser state: <html> element not found, in the after-body insertion mode")
  1883. }
  1884. p.oe[0].AppendChild(&Node{
  1885. Type: CommentNode,
  1886. Data: p.tok.Data,
  1887. })
  1888. return true
  1889. }
  1890. p.im = inBodyIM
  1891. return false
  1892. }
  1893. // Section 12.2.6.4.20.
  1894. func inFramesetIM(p *parser) bool {
  1895. switch p.tok.Type {
  1896. case CommentToken:
  1897. p.addChild(&Node{
  1898. Type: CommentNode,
  1899. Data: p.tok.Data,
  1900. })
  1901. case TextToken:
  1902. // Ignore all text but whitespace.
  1903. s := strings.Map(func(c rune) rune {
  1904. switch c {
  1905. case ' ', '\t', '\n', '\f', '\r':
  1906. return c
  1907. }
  1908. return -1
  1909. }, p.tok.Data)
  1910. if s != "" {
  1911. p.addText(s)
  1912. }
  1913. case StartTagToken:
  1914. switch p.tok.DataAtom {
  1915. case a.Html:
  1916. return inBodyIM(p)
  1917. case a.Frameset:
  1918. p.addElement()
  1919. case a.Frame:
  1920. p.addElement()
  1921. p.oe.pop()
  1922. p.acknowledgeSelfClosingTag()
  1923. case a.Noframes:
  1924. return inHeadIM(p)
  1925. }
  1926. case EndTagToken:
  1927. switch p.tok.DataAtom {
  1928. case a.Frameset:
  1929. if p.oe.top().DataAtom != a.Html {
  1930. p.oe.pop()
  1931. if p.oe.top().DataAtom != a.Frameset {
  1932. p.im = afterFramesetIM
  1933. return true
  1934. }
  1935. }
  1936. }
  1937. default:
  1938. // Ignore the token.
  1939. }
  1940. return true
  1941. }
  1942. // Section 12.2.6.4.21.
  1943. func afterFramesetIM(p *parser) bool {
  1944. switch p.tok.Type {
  1945. case CommentToken:
  1946. p.addChild(&Node{
  1947. Type: CommentNode,
  1948. Data: p.tok.Data,
  1949. })
  1950. case TextToken:
  1951. // Ignore all text but whitespace.
  1952. s := strings.Map(func(c rune) rune {
  1953. switch c {
  1954. case ' ', '\t', '\n', '\f', '\r':
  1955. return c
  1956. }
  1957. return -1
  1958. }, p.tok.Data)
  1959. if s != "" {
  1960. p.addText(s)
  1961. }
  1962. case StartTagToken:
  1963. switch p.tok.DataAtom {
  1964. case a.Html:
  1965. return inBodyIM(p)
  1966. case a.Noframes:
  1967. return inHeadIM(p)
  1968. }
  1969. case EndTagToken:
  1970. switch p.tok.DataAtom {
  1971. case a.Html:
  1972. p.im = afterAfterFramesetIM
  1973. return true
  1974. }
  1975. default:
  1976. // Ignore the token.
  1977. }
  1978. return true
  1979. }
  1980. // Section 12.2.6.4.22.
  1981. func afterAfterBodyIM(p *parser) bool {
  1982. switch p.tok.Type {
  1983. case ErrorToken:
  1984. // Stop parsing.
  1985. return true
  1986. case TextToken:
  1987. s := strings.TrimLeft(p.tok.Data, whitespace)
  1988. if len(s) == 0 {
  1989. // It was all whitespace.
  1990. return inBodyIM(p)
  1991. }
  1992. case StartTagToken:
  1993. if p.tok.DataAtom == a.Html {
  1994. return inBodyIM(p)
  1995. }
  1996. case CommentToken:
  1997. p.doc.AppendChild(&Node{
  1998. Type: CommentNode,
  1999. Data: p.tok.Data,
  2000. })
  2001. return true
  2002. case DoctypeToken:
  2003. return inBodyIM(p)
  2004. }
  2005. p.im = inBodyIM
  2006. return false
  2007. }
  2008. // Section 12.2.6.4.23.
  2009. func afterAfterFramesetIM(p *parser) bool {
  2010. switch p.tok.Type {
  2011. case CommentToken:
  2012. p.doc.AppendChild(&Node{
  2013. Type: CommentNode,
  2014. Data: p.tok.Data,
  2015. })
  2016. case TextToken:
  2017. // Ignore all text but whitespace.
  2018. s := strings.Map(func(c rune) rune {
  2019. switch c {
  2020. case ' ', '\t', '\n', '\f', '\r':
  2021. return c
  2022. }
  2023. return -1
  2024. }, p.tok.Data)
  2025. if s != "" {
  2026. p.tok.Data = s
  2027. return inBodyIM(p)
  2028. }
  2029. case StartTagToken:
  2030. switch p.tok.DataAtom {
  2031. case a.Html:
  2032. return inBodyIM(p)
  2033. case a.Noframes:
  2034. return inHeadIM(p)
  2035. }
  2036. case DoctypeToken:
  2037. return inBodyIM(p)
  2038. default:
  2039. // Ignore the token.
  2040. }
  2041. return true
  2042. }
  2043. const whitespaceOrNUL = whitespace + "\x00"
  2044. // Section 12.2.6.5
  2045. func parseForeignContent(p *parser) bool {
  2046. switch p.tok.Type {
  2047. case TextToken:
  2048. if p.framesetOK {
  2049. p.framesetOK = strings.TrimLeft(p.tok.Data, whitespaceOrNUL) == ""
  2050. }
  2051. p.tok.Data = strings.Replace(p.tok.Data, "\x00", "\ufffd", -1)
  2052. p.addText(p.tok.Data)
  2053. case CommentToken:
  2054. p.addChild(&Node{
  2055. Type: CommentNode,
  2056. Data: p.tok.Data,
  2057. })
  2058. case StartTagToken:
  2059. if !p.fragment {
  2060. b := breakout[p.tok.Data]
  2061. if p.tok.DataAtom == a.Font {
  2062. loop:
  2063. for _, attr := range p.tok.Attr {
  2064. switch attr.Key {
  2065. case "color", "face", "size":
  2066. b = true
  2067. break loop
  2068. }
  2069. }
  2070. }
  2071. if b {
  2072. for i := len(p.oe) - 1; i >= 0; i-- {
  2073. n := p.oe[i]
  2074. if n.Namespace == "" || htmlIntegrationPoint(n) || mathMLTextIntegrationPoint(n) {
  2075. p.oe = p.oe[:i+1]
  2076. break
  2077. }
  2078. }
  2079. return false
  2080. }
  2081. }
  2082. current := p.adjustedCurrentNode()
  2083. switch current.Namespace {
  2084. case "math":
  2085. adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments)
  2086. case "svg":
  2087. // Adjust SVG tag names. The tokenizer lower-cases tag names, but
  2088. // SVG wants e.g. "foreignObject" with a capital second "O".
  2089. if x := svgTagNameAdjustments[p.tok.Data]; x != "" {
  2090. p.tok.DataAtom = a.Lookup([]byte(x))
  2091. p.tok.Data = x
  2092. }
  2093. adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments)
  2094. default:
  2095. panic("html: bad parser state: unexpected namespace")
  2096. }
  2097. adjustForeignAttributes(p.tok.Attr)
  2098. namespace := current.Namespace
  2099. p.addElement()
  2100. p.top().Namespace = namespace
  2101. if namespace != "" {
  2102. // Don't let the tokenizer go into raw text mode in foreign content
  2103. // (e.g. in an SVG <title> tag).
  2104. p.tokenizer.NextIsNotRawText()
  2105. }
  2106. if p.hasSelfClosingToken {
  2107. p.oe.pop()
  2108. p.acknowledgeSelfClosingTag()
  2109. }
  2110. case EndTagToken:
  2111. for i := len(p.oe) - 1; i >= 0; i-- {
  2112. if p.oe[i].Namespace == "" {
  2113. return p.im(p)
  2114. }
  2115. if strings.EqualFold(p.oe[i].Data, p.tok.Data) {
  2116. p.oe = p.oe[:i]
  2117. break
  2118. }
  2119. }
  2120. return true
  2121. default:
  2122. // Ignore the token.
  2123. }
  2124. return true
  2125. }
  2126. // Section 12.2.4.2.
  2127. func (p *parser) adjustedCurrentNode() *Node {
  2128. if len(p.oe) == 1 && p.fragment && p.context != nil {
  2129. return p.context
  2130. }
  2131. return p.oe.top()
  2132. }
  2133. // Section 12.2.6.
  2134. func (p *parser) inForeignContent() bool {
  2135. if len(p.oe) == 0 {
  2136. return false
  2137. }
  2138. n := p.adjustedCurrentNode()
  2139. if n.Namespace == "" {
  2140. return false
  2141. }
  2142. if mathMLTextIntegrationPoint(n) {
  2143. if p.tok.Type == StartTagToken && p.tok.DataAtom != a.Mglyph && p.tok.DataAtom != a.Malignmark {
  2144. return false
  2145. }
  2146. if p.tok.Type == TextToken {
  2147. return false
  2148. }
  2149. }
  2150. if n.Namespace == "math" && n.DataAtom == a.AnnotationXml && p.tok.Type == StartTagToken && p.tok.DataAtom == a.Svg {
  2151. return false
  2152. }
  2153. if htmlIntegrationPoint(n) && (p.tok.Type == StartTagToken || p.tok.Type == TextToken) {
  2154. return false
  2155. }
  2156. if p.tok.Type == ErrorToken {
  2157. return false
  2158. }
  2159. return true
  2160. }
  2161. // parseImpliedToken parses a token as though it had appeared in the parser's
  2162. // input.
  2163. func (p *parser) parseImpliedToken(t TokenType, dataAtom a.Atom, data string) {
  2164. realToken, selfClosing := p.tok, p.hasSelfClosingToken
  2165. p.tok = Token{
  2166. Type: t,
  2167. DataAtom: dataAtom,
  2168. Data: data,
  2169. }
  2170. p.hasSelfClosingToken = false
  2171. p.parseCurrentToken()
  2172. p.tok, p.hasSelfClosingToken = realToken, selfClosing
  2173. }
  2174. // parseCurrentToken runs the current token through the parsing routines
  2175. // until it is consumed.
  2176. func (p *parser) parseCurrentToken() {
  2177. if p.tok.Type == SelfClosingTagToken {
  2178. p.hasSelfClosingToken = true
  2179. p.tok.Type = StartTagToken
  2180. }
  2181. consumed := false
  2182. for !consumed {
  2183. if p.inForeignContent() {
  2184. consumed = parseForeignContent(p)
  2185. } else {
  2186. consumed = p.im(p)
  2187. }
  2188. }
  2189. if p.hasSelfClosingToken {
  2190. // This is a parse error, but ignore it.
  2191. p.hasSelfClosingToken = false
  2192. }
  2193. }
  2194. func (p *parser) parse() error {
  2195. // Iterate until EOF. Any other error will cause an early return.
  2196. var err error
  2197. for err != io.EOF {
  2198. // CDATA sections are allowed only in foreign content.
  2199. n := p.oe.top()
  2200. p.tokenizer.AllowCDATA(n != nil && n.Namespace != "")
  2201. // Read and parse the next token.
  2202. p.tokenizer.Next()
  2203. p.tok = p.tokenizer.Token()
  2204. if p.tok.Type == ErrorToken {
  2205. err = p.tokenizer.Err()
  2206. if err != nil && err != io.EOF {
  2207. return err
  2208. }
  2209. }
  2210. p.parseCurrentToken()
  2211. }
  2212. return nil
  2213. }
  2214. // Parse returns the parse tree for the HTML from the given Reader.
  2215. //
  2216. // It implements the HTML5 parsing algorithm
  2217. // (https://html.spec.whatwg.org/multipage/syntax.html#tree-construction),
  2218. // which is very complicated. The resultant tree can contain implicitly created
  2219. // nodes that have no explicit <tag> listed in r's data, and nodes' parents can
  2220. // differ from the nesting implied by a naive processing of start and end
  2221. // <tag>s. Conversely, explicit <tag>s in r's data can be silently dropped,
  2222. // with no corresponding node in the resulting tree.
  2223. //
  2224. // The input is assumed to be UTF-8 encoded.
  2225. func Parse(r io.Reader) (*Node, error) {
  2226. return ParseWithOptions(r)
  2227. }
  2228. // ParseFragment parses a fragment of HTML and returns the nodes that were
  2229. // found. If the fragment is the InnerHTML for an existing element, pass that
  2230. // element in context.
  2231. //
  2232. // It has the same intricacies as Parse.
  2233. func ParseFragment(r io.Reader, context *Node) ([]*Node, error) {
  2234. return ParseFragmentWithOptions(r, context)
  2235. }
  2236. // ParseOption configures a parser.
  2237. type ParseOption func(p *parser)
  2238. // ParseOptionEnableScripting configures the scripting flag.
  2239. // https://html.spec.whatwg.org/multipage/webappapis.html#enabling-and-disabling-scripting
  2240. //
  2241. // By default, scripting is enabled.
  2242. func ParseOptionEnableScripting(enable bool) ParseOption {
  2243. return func(p *parser) {
  2244. p.scripting = enable
  2245. }
  2246. }
  2247. // ParseWithOptions is like Parse, with options.
  2248. func ParseWithOptions(r io.Reader, opts ...ParseOption) (*Node, error) {
  2249. p := &parser{
  2250. tokenizer: NewTokenizer(r),
  2251. doc: &Node{
  2252. Type: DocumentNode,
  2253. },
  2254. scripting: true,
  2255. framesetOK: true,
  2256. im: initialIM,
  2257. }
  2258. for _, f := range opts {
  2259. f(p)
  2260. }
  2261. if err := p.parse(); err != nil {
  2262. return nil, err
  2263. }
  2264. return p.doc, nil
  2265. }
  2266. // ParseFragmentWithOptions is like ParseFragment, with options.
  2267. func ParseFragmentWithOptions(r io.Reader, context *Node, opts ...ParseOption) ([]*Node, error) {
  2268. contextTag := ""
  2269. if context != nil {
  2270. if context.Type != ElementNode {
  2271. return nil, errors.New("html: ParseFragment of non-element Node")
  2272. }
  2273. // The next check isn't just context.DataAtom.String() == context.Data because
  2274. // it is valid to pass an element whose tag isn't a known atom. For example,
  2275. // DataAtom == 0 and Data = "tagfromthefuture" is perfectly consistent.
  2276. if context.DataAtom != a.Lookup([]byte(context.Data)) {
  2277. return nil, fmt.Errorf("html: inconsistent Node: DataAtom=%q, Data=%q", context.DataAtom, context.Data)
  2278. }
  2279. contextTag = context.DataAtom.String()
  2280. }
  2281. p := &parser{
  2282. doc: &Node{
  2283. Type: DocumentNode,
  2284. },
  2285. scripting: true,
  2286. fragment: true,
  2287. context: context,
  2288. }
  2289. if context != nil && context.Namespace != "" {
  2290. p.tokenizer = NewTokenizer(r)
  2291. } else {
  2292. p.tokenizer = NewTokenizerFragment(r, contextTag)
  2293. }
  2294. for _, f := range opts {
  2295. f(p)
  2296. }
  2297. root := &Node{
  2298. Type: ElementNode,
  2299. DataAtom: a.Html,
  2300. Data: a.Html.String(),
  2301. }
  2302. p.doc.AppendChild(root)
  2303. p.oe = nodeStack{root}
  2304. if context != nil && context.DataAtom == a.Template {
  2305. p.templateStack = append(p.templateStack, inTemplateIM)
  2306. }
  2307. p.resetInsertionMode()
  2308. for n := context; n != nil; n = n.Parent {
  2309. if n.Type == ElementNode && n.DataAtom == a.Form {
  2310. p.form = n
  2311. break
  2312. }
  2313. }
  2314. if err := p.parse(); err != nil {
  2315. return nil, err
  2316. }
  2317. parent := p.doc
  2318. if context != nil {
  2319. parent = root
  2320. }
  2321. var result []*Node
  2322. for c := parent.FirstChild; c != nil; {
  2323. next := c.NextSibling
  2324. parent.RemoveChild(c)
  2325. result = append(result, c)
  2326. c = next
  2327. }
  2328. return result, nil
  2329. }