parse.go 53 KB

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