parse.go 55 KB

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