parse.go 54 KB

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