parse.go 54 KB

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