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