parse.go 57 KB

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