parse.go 57 KB

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