本站源代码
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.

2418 lines
57KB

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