parse.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  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. p.popUntil(defaultScope, a.Template)
  638. p.clearActiveFormattingElements()
  639. p.templateStack.pop()
  640. p.resetInsertionMode()
  641. return true
  642. default:
  643. // Ignore the token.
  644. return true
  645. }
  646. case CommentToken:
  647. p.addChild(&Node{
  648. Type: CommentNode,
  649. Data: p.tok.Data,
  650. })
  651. return true
  652. case DoctypeToken:
  653. // Ignore the token.
  654. return true
  655. }
  656. p.parseImpliedToken(EndTagToken, a.Head, a.Head.String())
  657. return false
  658. }
  659. // Section 12.2.6.4.6.
  660. func afterHeadIM(p *parser) bool {
  661. switch p.tok.Type {
  662. case TextToken:
  663. s := strings.TrimLeft(p.tok.Data, whitespace)
  664. if len(s) < len(p.tok.Data) {
  665. // Add the initial whitespace to the current node.
  666. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)])
  667. if s == "" {
  668. return true
  669. }
  670. p.tok.Data = s
  671. }
  672. case StartTagToken:
  673. switch p.tok.DataAtom {
  674. case a.Html:
  675. return inBodyIM(p)
  676. case a.Body:
  677. p.addElement()
  678. p.framesetOK = false
  679. p.im = inBodyIM
  680. return true
  681. case a.Frameset:
  682. p.addElement()
  683. p.im = inFramesetIM
  684. return true
  685. case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
  686. p.oe = append(p.oe, p.head)
  687. defer p.oe.remove(p.head)
  688. return inHeadIM(p)
  689. case a.Head:
  690. // Ignore the token.
  691. return true
  692. }
  693. case EndTagToken:
  694. switch p.tok.DataAtom {
  695. case a.Body, a.Html, a.Br:
  696. // Drop down to creating an implied <body> tag.
  697. case a.Template:
  698. return inHeadIM(p)
  699. default:
  700. // Ignore the token.
  701. return true
  702. }
  703. case CommentToken:
  704. p.addChild(&Node{
  705. Type: CommentNode,
  706. Data: p.tok.Data,
  707. })
  708. return true
  709. case DoctypeToken:
  710. // Ignore the token.
  711. return true
  712. }
  713. p.parseImpliedToken(StartTagToken, a.Body, a.Body.String())
  714. p.framesetOK = true
  715. return false
  716. }
  717. // copyAttributes copies attributes of src not found on dst to dst.
  718. func copyAttributes(dst *Node, src Token) {
  719. if len(src.Attr) == 0 {
  720. return
  721. }
  722. attr := map[string]string{}
  723. for _, t := range dst.Attr {
  724. attr[t.Key] = t.Val
  725. }
  726. for _, t := range src.Attr {
  727. if _, ok := attr[t.Key]; !ok {
  728. dst.Attr = append(dst.Attr, t)
  729. attr[t.Key] = t.Val
  730. }
  731. }
  732. }
  733. // Section 12.2.6.4.7.
  734. func inBodyIM(p *parser) bool {
  735. switch p.tok.Type {
  736. case TextToken:
  737. d := p.tok.Data
  738. switch n := p.oe.top(); n.DataAtom {
  739. case a.Pre, a.Listing:
  740. if n.FirstChild == nil {
  741. // Ignore a newline at the start of a <pre> block.
  742. if d != "" && d[0] == '\r' {
  743. d = d[1:]
  744. }
  745. if d != "" && d[0] == '\n' {
  746. d = d[1:]
  747. }
  748. }
  749. }
  750. d = strings.Replace(d, "\x00", "", -1)
  751. if d == "" {
  752. return true
  753. }
  754. p.reconstructActiveFormattingElements()
  755. p.addText(d)
  756. if p.framesetOK && strings.TrimLeft(d, whitespace) != "" {
  757. // There were non-whitespace characters inserted.
  758. p.framesetOK = false
  759. }
  760. case StartTagToken:
  761. switch p.tok.DataAtom {
  762. case a.Html:
  763. if p.oe.contains(a.Template) {
  764. return true
  765. }
  766. copyAttributes(p.oe[0], p.tok)
  767. case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
  768. return inHeadIM(p)
  769. case a.Body:
  770. if p.oe.contains(a.Template) {
  771. return true
  772. }
  773. if len(p.oe) >= 2 {
  774. body := p.oe[1]
  775. if body.Type == ElementNode && body.DataAtom == a.Body {
  776. p.framesetOK = false
  777. copyAttributes(body, p.tok)
  778. }
  779. }
  780. case a.Frameset:
  781. if !p.framesetOK || len(p.oe) < 2 || p.oe[1].DataAtom != a.Body {
  782. // Ignore the token.
  783. return true
  784. }
  785. body := p.oe[1]
  786. if body.Parent != nil {
  787. body.Parent.RemoveChild(body)
  788. }
  789. p.oe = p.oe[:1]
  790. p.addElement()
  791. p.im = inFramesetIM
  792. return true
  793. 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:
  794. p.popUntil(buttonScope, a.P)
  795. p.addElement()
  796. case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
  797. p.popUntil(buttonScope, a.P)
  798. switch n := p.top(); n.DataAtom {
  799. case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
  800. p.oe.pop()
  801. }
  802. p.addElement()
  803. case a.Pre, a.Listing:
  804. p.popUntil(buttonScope, a.P)
  805. p.addElement()
  806. // The newline, if any, will be dealt with by the TextToken case.
  807. p.framesetOK = false
  808. case a.Form:
  809. if p.form != nil && !p.oe.contains(a.Template) {
  810. // Ignore the token
  811. return true
  812. }
  813. p.popUntil(buttonScope, a.P)
  814. p.addElement()
  815. if !p.oe.contains(a.Template) {
  816. p.form = p.top()
  817. }
  818. case a.Li:
  819. p.framesetOK = false
  820. for i := len(p.oe) - 1; i >= 0; i-- {
  821. node := p.oe[i]
  822. switch node.DataAtom {
  823. case a.Li:
  824. p.oe = p.oe[:i]
  825. case a.Address, a.Div, a.P:
  826. continue
  827. default:
  828. if !isSpecialElement(node) {
  829. continue
  830. }
  831. }
  832. break
  833. }
  834. p.popUntil(buttonScope, a.P)
  835. p.addElement()
  836. case a.Dd, a.Dt:
  837. p.framesetOK = false
  838. for i := len(p.oe) - 1; i >= 0; i-- {
  839. node := p.oe[i]
  840. switch node.DataAtom {
  841. case a.Dd, a.Dt:
  842. p.oe = p.oe[:i]
  843. case a.Address, a.Div, a.P:
  844. continue
  845. default:
  846. if !isSpecialElement(node) {
  847. continue
  848. }
  849. }
  850. break
  851. }
  852. p.popUntil(buttonScope, a.P)
  853. p.addElement()
  854. case a.Plaintext:
  855. p.popUntil(buttonScope, a.P)
  856. p.addElement()
  857. case a.Button:
  858. p.popUntil(defaultScope, a.Button)
  859. p.reconstructActiveFormattingElements()
  860. p.addElement()
  861. p.framesetOK = false
  862. case a.A:
  863. for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- {
  864. if n := p.afe[i]; n.Type == ElementNode && n.DataAtom == a.A {
  865. p.inBodyEndTagFormatting(a.A)
  866. p.oe.remove(n)
  867. p.afe.remove(n)
  868. break
  869. }
  870. }
  871. p.reconstructActiveFormattingElements()
  872. p.addFormattingElement()
  873. 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:
  874. p.reconstructActiveFormattingElements()
  875. p.addFormattingElement()
  876. case a.Nobr:
  877. p.reconstructActiveFormattingElements()
  878. if p.elementInScope(defaultScope, a.Nobr) {
  879. p.inBodyEndTagFormatting(a.Nobr)
  880. p.reconstructActiveFormattingElements()
  881. }
  882. p.addFormattingElement()
  883. case a.Applet, a.Marquee, a.Object:
  884. p.reconstructActiveFormattingElements()
  885. p.addElement()
  886. p.afe = append(p.afe, &scopeMarker)
  887. p.framesetOK = false
  888. case a.Table:
  889. if !p.quirks {
  890. p.popUntil(buttonScope, a.P)
  891. }
  892. p.addElement()
  893. p.framesetOK = false
  894. p.im = inTableIM
  895. return true
  896. case a.Area, a.Br, a.Embed, a.Img, a.Input, a.Keygen, a.Wbr:
  897. p.reconstructActiveFormattingElements()
  898. p.addElement()
  899. p.oe.pop()
  900. p.acknowledgeSelfClosingTag()
  901. if p.tok.DataAtom == a.Input {
  902. for _, t := range p.tok.Attr {
  903. if t.Key == "type" {
  904. if strings.ToLower(t.Val) == "hidden" {
  905. // Skip setting framesetOK = false
  906. return true
  907. }
  908. }
  909. }
  910. }
  911. p.framesetOK = false
  912. case a.Param, a.Source, a.Track:
  913. p.addElement()
  914. p.oe.pop()
  915. p.acknowledgeSelfClosingTag()
  916. case a.Hr:
  917. p.popUntil(buttonScope, a.P)
  918. p.addElement()
  919. p.oe.pop()
  920. p.acknowledgeSelfClosingTag()
  921. p.framesetOK = false
  922. case a.Image:
  923. p.tok.DataAtom = a.Img
  924. p.tok.Data = a.Img.String()
  925. return false
  926. case a.Isindex:
  927. if p.form != nil {
  928. // Ignore the token.
  929. return true
  930. }
  931. action := ""
  932. prompt := "This is a searchable index. Enter search keywords: "
  933. attr := []Attribute{{Key: "name", Val: "isindex"}}
  934. for _, t := range p.tok.Attr {
  935. switch t.Key {
  936. case "action":
  937. action = t.Val
  938. case "name":
  939. // Ignore the attribute.
  940. case "prompt":
  941. prompt = t.Val
  942. default:
  943. attr = append(attr, t)
  944. }
  945. }
  946. p.acknowledgeSelfClosingTag()
  947. p.popUntil(buttonScope, a.P)
  948. p.parseImpliedToken(StartTagToken, a.Form, a.Form.String())
  949. if action != "" {
  950. p.form.Attr = []Attribute{{Key: "action", Val: action}}
  951. }
  952. p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
  953. p.parseImpliedToken(StartTagToken, a.Label, a.Label.String())
  954. p.addText(prompt)
  955. p.addChild(&Node{
  956. Type: ElementNode,
  957. DataAtom: a.Input,
  958. Data: a.Input.String(),
  959. Attr: attr,
  960. })
  961. p.oe.pop()
  962. p.parseImpliedToken(EndTagToken, a.Label, a.Label.String())
  963. p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
  964. p.parseImpliedToken(EndTagToken, a.Form, a.Form.String())
  965. case a.Textarea:
  966. p.addElement()
  967. p.setOriginalIM()
  968. p.framesetOK = false
  969. p.im = textIM
  970. case a.Xmp:
  971. p.popUntil(buttonScope, a.P)
  972. p.reconstructActiveFormattingElements()
  973. p.framesetOK = false
  974. p.addElement()
  975. p.setOriginalIM()
  976. p.im = textIM
  977. case a.Iframe:
  978. p.framesetOK = false
  979. p.addElement()
  980. p.setOriginalIM()
  981. p.im = textIM
  982. case a.Noembed, a.Noscript:
  983. p.addElement()
  984. p.setOriginalIM()
  985. p.im = textIM
  986. case a.Select:
  987. p.reconstructActiveFormattingElements()
  988. p.addElement()
  989. p.framesetOK = false
  990. p.im = inSelectIM
  991. return true
  992. case a.Optgroup, a.Option:
  993. if p.top().DataAtom == a.Option {
  994. p.oe.pop()
  995. }
  996. p.reconstructActiveFormattingElements()
  997. p.addElement()
  998. case a.Rb, a.Rtc:
  999. if p.elementInScope(defaultScope, a.Ruby) {
  1000. p.generateImpliedEndTags()
  1001. }
  1002. p.addElement()
  1003. case a.Rp, a.Rt:
  1004. if p.elementInScope(defaultScope, a.Ruby) {
  1005. p.generateImpliedEndTags("rtc")
  1006. }
  1007. p.addElement()
  1008. case a.Math, a.Svg:
  1009. p.reconstructActiveFormattingElements()
  1010. if p.tok.DataAtom == a.Math {
  1011. adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments)
  1012. } else {
  1013. adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments)
  1014. }
  1015. adjustForeignAttributes(p.tok.Attr)
  1016. p.addElement()
  1017. p.top().Namespace = p.tok.Data
  1018. if p.hasSelfClosingToken {
  1019. p.oe.pop()
  1020. p.acknowledgeSelfClosingTag()
  1021. }
  1022. return true
  1023. case a.Caption, a.Col, a.Colgroup, a.Frame, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1024. // Ignore the token.
  1025. default:
  1026. p.reconstructActiveFormattingElements()
  1027. p.addElement()
  1028. }
  1029. case EndTagToken:
  1030. switch p.tok.DataAtom {
  1031. case a.Body:
  1032. if p.elementInScope(defaultScope, a.Body) {
  1033. p.im = afterBodyIM
  1034. }
  1035. case a.Html:
  1036. if p.elementInScope(defaultScope, a.Body) {
  1037. p.parseImpliedToken(EndTagToken, a.Body, a.Body.String())
  1038. return false
  1039. }
  1040. return true
  1041. 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:
  1042. p.popUntil(defaultScope, p.tok.DataAtom)
  1043. case a.Form:
  1044. if p.oe.contains(a.Template) {
  1045. i := p.indexOfElementInScope(defaultScope, a.Form)
  1046. if i == -1 {
  1047. // Ignore the token.
  1048. return true
  1049. }
  1050. p.generateImpliedEndTags()
  1051. if p.oe[i].DataAtom != a.Form {
  1052. // Ignore the token.
  1053. return true
  1054. }
  1055. p.popUntil(defaultScope, a.Form)
  1056. } else {
  1057. node := p.form
  1058. p.form = nil
  1059. i := p.indexOfElementInScope(defaultScope, a.Form)
  1060. if node == nil || i == -1 || p.oe[i] != node {
  1061. // Ignore the token.
  1062. return true
  1063. }
  1064. p.generateImpliedEndTags()
  1065. p.oe.remove(node)
  1066. }
  1067. case a.P:
  1068. if !p.elementInScope(buttonScope, a.P) {
  1069. p.parseImpliedToken(StartTagToken, a.P, a.P.String())
  1070. }
  1071. p.popUntil(buttonScope, a.P)
  1072. case a.Li:
  1073. p.popUntil(listItemScope, a.Li)
  1074. case a.Dd, a.Dt:
  1075. p.popUntil(defaultScope, p.tok.DataAtom)
  1076. case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
  1077. p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6)
  1078. 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:
  1079. p.inBodyEndTagFormatting(p.tok.DataAtom)
  1080. case a.Applet, a.Marquee, a.Object:
  1081. if p.popUntil(defaultScope, p.tok.DataAtom) {
  1082. p.clearActiveFormattingElements()
  1083. }
  1084. case a.Br:
  1085. p.tok.Type = StartTagToken
  1086. return false
  1087. case a.Template:
  1088. return inHeadIM(p)
  1089. default:
  1090. p.inBodyEndTagOther(p.tok.DataAtom)
  1091. }
  1092. case CommentToken:
  1093. p.addChild(&Node{
  1094. Type: CommentNode,
  1095. Data: p.tok.Data,
  1096. })
  1097. case ErrorToken:
  1098. // TODO: remove this divergence from the HTML5 spec.
  1099. if len(p.templateStack) > 0 {
  1100. p.im = inTemplateIM
  1101. return false
  1102. } else {
  1103. for _, e := range p.oe {
  1104. switch e.DataAtom {
  1105. 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,
  1106. a.Thead, a.Tr, a.Body, a.Html:
  1107. default:
  1108. return true
  1109. }
  1110. }
  1111. }
  1112. }
  1113. return true
  1114. }
  1115. func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) {
  1116. // This is the "adoption agency" algorithm, described at
  1117. // https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency
  1118. // TODO: this is a fairly literal line-by-line translation of that algorithm.
  1119. // Once the code successfully parses the comprehensive test suite, we should
  1120. // refactor this code to be more idiomatic.
  1121. // Steps 1-4. The outer loop.
  1122. for i := 0; i < 8; i++ {
  1123. // Step 5. Find the formatting element.
  1124. var formattingElement *Node
  1125. for j := len(p.afe) - 1; j >= 0; j-- {
  1126. if p.afe[j].Type == scopeMarkerNode {
  1127. break
  1128. }
  1129. if p.afe[j].DataAtom == tagAtom {
  1130. formattingElement = p.afe[j]
  1131. break
  1132. }
  1133. }
  1134. if formattingElement == nil {
  1135. p.inBodyEndTagOther(tagAtom)
  1136. return
  1137. }
  1138. feIndex := p.oe.index(formattingElement)
  1139. if feIndex == -1 {
  1140. p.afe.remove(formattingElement)
  1141. return
  1142. }
  1143. if !p.elementInScope(defaultScope, tagAtom) {
  1144. // Ignore the tag.
  1145. return
  1146. }
  1147. // Steps 9-10. Find the furthest block.
  1148. var furthestBlock *Node
  1149. for _, e := range p.oe[feIndex:] {
  1150. if isSpecialElement(e) {
  1151. furthestBlock = e
  1152. break
  1153. }
  1154. }
  1155. if furthestBlock == nil {
  1156. e := p.oe.pop()
  1157. for e != formattingElement {
  1158. e = p.oe.pop()
  1159. }
  1160. p.afe.remove(e)
  1161. return
  1162. }
  1163. // Steps 11-12. Find the common ancestor and bookmark node.
  1164. commonAncestor := p.oe[feIndex-1]
  1165. bookmark := p.afe.index(formattingElement)
  1166. // Step 13. The inner loop. Find the lastNode to reparent.
  1167. lastNode := furthestBlock
  1168. node := furthestBlock
  1169. x := p.oe.index(node)
  1170. // Steps 13.1-13.2
  1171. for j := 0; j < 3; j++ {
  1172. // Step 13.3.
  1173. x--
  1174. node = p.oe[x]
  1175. // Step 13.4 - 13.5.
  1176. if p.afe.index(node) == -1 {
  1177. p.oe.remove(node)
  1178. continue
  1179. }
  1180. // Step 13.6.
  1181. if node == formattingElement {
  1182. break
  1183. }
  1184. // Step 13.7.
  1185. clone := node.clone()
  1186. p.afe[p.afe.index(node)] = clone
  1187. p.oe[p.oe.index(node)] = clone
  1188. node = clone
  1189. // Step 13.8.
  1190. if lastNode == furthestBlock {
  1191. bookmark = p.afe.index(node) + 1
  1192. }
  1193. // Step 13.9.
  1194. if lastNode.Parent != nil {
  1195. lastNode.Parent.RemoveChild(lastNode)
  1196. }
  1197. node.AppendChild(lastNode)
  1198. // Step 13.10.
  1199. lastNode = node
  1200. }
  1201. // Step 14. Reparent lastNode to the common ancestor,
  1202. // or for misnested table nodes, to the foster parent.
  1203. if lastNode.Parent != nil {
  1204. lastNode.Parent.RemoveChild(lastNode)
  1205. }
  1206. switch commonAncestor.DataAtom {
  1207. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1208. p.fosterParent(lastNode)
  1209. case a.Template:
  1210. // TODO: remove namespace checking
  1211. if commonAncestor.Namespace == "html" {
  1212. commonAncestor = commonAncestor.LastChild
  1213. }
  1214. fallthrough
  1215. default:
  1216. commonAncestor.AppendChild(lastNode)
  1217. }
  1218. // Steps 15-17. Reparent nodes from the furthest block's children
  1219. // to a clone of the formatting element.
  1220. clone := formattingElement.clone()
  1221. reparentChildren(clone, furthestBlock)
  1222. furthestBlock.AppendChild(clone)
  1223. // Step 18. Fix up the list of active formatting elements.
  1224. if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark {
  1225. // Move the bookmark with the rest of the list.
  1226. bookmark--
  1227. }
  1228. p.afe.remove(formattingElement)
  1229. p.afe.insert(bookmark, clone)
  1230. // Step 19. Fix up the stack of open elements.
  1231. p.oe.remove(formattingElement)
  1232. p.oe.insert(p.oe.index(furthestBlock)+1, clone)
  1233. }
  1234. }
  1235. // inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM.
  1236. // "Any other end tag" handling from 12.2.6.5 The rules for parsing tokens in foreign content
  1237. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign
  1238. func (p *parser) inBodyEndTagOther(tagAtom a.Atom) {
  1239. for i := len(p.oe) - 1; i >= 0; i-- {
  1240. if p.oe[i].DataAtom == tagAtom {
  1241. p.oe = p.oe[:i]
  1242. break
  1243. }
  1244. if isSpecialElement(p.oe[i]) {
  1245. break
  1246. }
  1247. }
  1248. }
  1249. // Section 12.2.6.4.8.
  1250. func textIM(p *parser) bool {
  1251. switch p.tok.Type {
  1252. case ErrorToken:
  1253. p.oe.pop()
  1254. case TextToken:
  1255. d := p.tok.Data
  1256. if n := p.oe.top(); n.DataAtom == a.Textarea && n.FirstChild == nil {
  1257. // Ignore a newline at the start of a <textarea> block.
  1258. if d != "" && d[0] == '\r' {
  1259. d = d[1:]
  1260. }
  1261. if d != "" && d[0] == '\n' {
  1262. d = d[1:]
  1263. }
  1264. }
  1265. if d == "" {
  1266. return true
  1267. }
  1268. p.addText(d)
  1269. return true
  1270. case EndTagToken:
  1271. p.oe.pop()
  1272. }
  1273. p.im = p.originalIM
  1274. p.originalIM = nil
  1275. return p.tok.Type == EndTagToken
  1276. }
  1277. // Section 12.2.6.4.9.
  1278. func inTableIM(p *parser) bool {
  1279. switch p.tok.Type {
  1280. case ErrorToken:
  1281. // Stop parsing.
  1282. return true
  1283. case TextToken:
  1284. p.tok.Data = strings.Replace(p.tok.Data, "\x00", "", -1)
  1285. switch p.oe.top().DataAtom {
  1286. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1287. if strings.Trim(p.tok.Data, whitespace) == "" {
  1288. p.addText(p.tok.Data)
  1289. return true
  1290. }
  1291. }
  1292. case StartTagToken:
  1293. switch p.tok.DataAtom {
  1294. case a.Caption:
  1295. p.clearStackToContext(tableScope)
  1296. p.afe = append(p.afe, &scopeMarker)
  1297. p.addElement()
  1298. p.im = inCaptionIM
  1299. return true
  1300. case a.Colgroup:
  1301. p.clearStackToContext(tableScope)
  1302. p.addElement()
  1303. p.im = inColumnGroupIM
  1304. return true
  1305. case a.Col:
  1306. p.parseImpliedToken(StartTagToken, a.Colgroup, a.Colgroup.String())
  1307. return false
  1308. case a.Tbody, a.Tfoot, a.Thead:
  1309. p.clearStackToContext(tableScope)
  1310. p.addElement()
  1311. p.im = inTableBodyIM
  1312. return true
  1313. case a.Td, a.Th, a.Tr:
  1314. p.parseImpliedToken(StartTagToken, a.Tbody, a.Tbody.String())
  1315. return false
  1316. case a.Table:
  1317. if p.popUntil(tableScope, a.Table) {
  1318. p.resetInsertionMode()
  1319. return false
  1320. }
  1321. // Ignore the token.
  1322. return true
  1323. case a.Style, a.Script, a.Template:
  1324. return inHeadIM(p)
  1325. case a.Input:
  1326. for _, t := range p.tok.Attr {
  1327. if t.Key == "type" && strings.ToLower(t.Val) == "hidden" {
  1328. p.addElement()
  1329. p.oe.pop()
  1330. return true
  1331. }
  1332. }
  1333. // Otherwise drop down to the default action.
  1334. case a.Form:
  1335. if p.oe.contains(a.Template) || p.form != nil {
  1336. // Ignore the token.
  1337. return true
  1338. }
  1339. p.addElement()
  1340. p.form = p.oe.pop()
  1341. case a.Select:
  1342. p.reconstructActiveFormattingElements()
  1343. switch p.top().DataAtom {
  1344. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1345. p.fosterParenting = true
  1346. }
  1347. p.addElement()
  1348. p.fosterParenting = false
  1349. p.framesetOK = false
  1350. p.im = inSelectInTableIM
  1351. return true
  1352. }
  1353. case EndTagToken:
  1354. switch p.tok.DataAtom {
  1355. case a.Table:
  1356. if p.popUntil(tableScope, a.Table) {
  1357. p.resetInsertionMode()
  1358. return true
  1359. }
  1360. // Ignore the token.
  1361. return true
  1362. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1363. // Ignore the token.
  1364. return true
  1365. case a.Template:
  1366. return inHeadIM(p)
  1367. }
  1368. case CommentToken:
  1369. p.addChild(&Node{
  1370. Type: CommentNode,
  1371. Data: p.tok.Data,
  1372. })
  1373. return true
  1374. case DoctypeToken:
  1375. // Ignore the token.
  1376. return true
  1377. }
  1378. p.fosterParenting = true
  1379. defer func() { p.fosterParenting = false }()
  1380. return inBodyIM(p)
  1381. }
  1382. // Section 12.2.6.4.11.
  1383. func inCaptionIM(p *parser) bool {
  1384. switch p.tok.Type {
  1385. case StartTagToken:
  1386. switch p.tok.DataAtom {
  1387. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Thead, a.Tr:
  1388. if p.popUntil(tableScope, a.Caption) {
  1389. p.clearActiveFormattingElements()
  1390. p.im = inTableIM
  1391. return false
  1392. } else {
  1393. // Ignore the token.
  1394. return true
  1395. }
  1396. case a.Select:
  1397. p.reconstructActiveFormattingElements()
  1398. p.addElement()
  1399. p.framesetOK = false
  1400. p.im = inSelectInTableIM
  1401. return true
  1402. }
  1403. case EndTagToken:
  1404. switch p.tok.DataAtom {
  1405. case a.Caption:
  1406. if p.popUntil(tableScope, a.Caption) {
  1407. p.clearActiveFormattingElements()
  1408. p.im = inTableIM
  1409. }
  1410. return true
  1411. case a.Table:
  1412. if p.popUntil(tableScope, a.Caption) {
  1413. p.clearActiveFormattingElements()
  1414. p.im = inTableIM
  1415. return false
  1416. } else {
  1417. // Ignore the token.
  1418. return true
  1419. }
  1420. case a.Body, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1421. // Ignore the token.
  1422. return true
  1423. }
  1424. }
  1425. return inBodyIM(p)
  1426. }
  1427. // Section 12.2.6.4.12.
  1428. func inColumnGroupIM(p *parser) bool {
  1429. switch p.tok.Type {
  1430. case TextToken:
  1431. s := strings.TrimLeft(p.tok.Data, whitespace)
  1432. if len(s) < len(p.tok.Data) {
  1433. // Add the initial whitespace to the current node.
  1434. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)])
  1435. if s == "" {
  1436. return true
  1437. }
  1438. p.tok.Data = s
  1439. }
  1440. case CommentToken:
  1441. p.addChild(&Node{
  1442. Type: CommentNode,
  1443. Data: p.tok.Data,
  1444. })
  1445. return true
  1446. case DoctypeToken:
  1447. // Ignore the token.
  1448. return true
  1449. case StartTagToken:
  1450. switch p.tok.DataAtom {
  1451. case a.Html:
  1452. return inBodyIM(p)
  1453. case a.Col:
  1454. p.addElement()
  1455. p.oe.pop()
  1456. p.acknowledgeSelfClosingTag()
  1457. return true
  1458. case a.Template:
  1459. return inHeadIM(p)
  1460. }
  1461. case EndTagToken:
  1462. switch p.tok.DataAtom {
  1463. case a.Colgroup:
  1464. if p.oe.top().DataAtom == a.Colgroup {
  1465. p.oe.pop()
  1466. p.im = inTableIM
  1467. }
  1468. return true
  1469. case a.Col:
  1470. // Ignore the token.
  1471. return true
  1472. case a.Template:
  1473. return inHeadIM(p)
  1474. }
  1475. }
  1476. if p.oe.top().DataAtom != a.Colgroup {
  1477. return true
  1478. }
  1479. p.oe.pop()
  1480. p.im = inTableIM
  1481. return false
  1482. }
  1483. // Section 12.2.6.4.13.
  1484. func inTableBodyIM(p *parser) bool {
  1485. switch p.tok.Type {
  1486. case StartTagToken:
  1487. switch p.tok.DataAtom {
  1488. case a.Tr:
  1489. p.clearStackToContext(tableBodyScope)
  1490. p.addElement()
  1491. p.im = inRowIM
  1492. return true
  1493. case a.Td, a.Th:
  1494. p.parseImpliedToken(StartTagToken, a.Tr, a.Tr.String())
  1495. return false
  1496. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Tfoot, a.Thead:
  1497. if p.popUntil(tableScope, a.Tbody, a.Thead, a.Tfoot) {
  1498. p.im = inTableIM
  1499. return false
  1500. }
  1501. // Ignore the token.
  1502. return true
  1503. }
  1504. case EndTagToken:
  1505. switch p.tok.DataAtom {
  1506. case a.Tbody, a.Tfoot, a.Thead:
  1507. if p.elementInScope(tableScope, p.tok.DataAtom) {
  1508. p.clearStackToContext(tableBodyScope)
  1509. p.oe.pop()
  1510. p.im = inTableIM
  1511. }
  1512. return true
  1513. case a.Table:
  1514. if p.popUntil(tableScope, a.Tbody, a.Thead, a.Tfoot) {
  1515. p.im = inTableIM
  1516. return false
  1517. }
  1518. // Ignore the token.
  1519. return true
  1520. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Td, a.Th, a.Tr:
  1521. // Ignore the token.
  1522. return true
  1523. }
  1524. case CommentToken:
  1525. p.addChild(&Node{
  1526. Type: CommentNode,
  1527. Data: p.tok.Data,
  1528. })
  1529. return true
  1530. }
  1531. return inTableIM(p)
  1532. }
  1533. // Section 12.2.6.4.14.
  1534. func inRowIM(p *parser) bool {
  1535. switch p.tok.Type {
  1536. case StartTagToken:
  1537. switch p.tok.DataAtom {
  1538. case a.Td, a.Th:
  1539. p.clearStackToContext(tableRowScope)
  1540. p.addElement()
  1541. p.afe = append(p.afe, &scopeMarker)
  1542. p.im = inCellIM
  1543. return true
  1544. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1545. if p.popUntil(tableScope, a.Tr) {
  1546. p.im = inTableBodyIM
  1547. return false
  1548. }
  1549. // Ignore the token.
  1550. return true
  1551. }
  1552. case EndTagToken:
  1553. switch p.tok.DataAtom {
  1554. case a.Tr:
  1555. if p.popUntil(tableScope, a.Tr) {
  1556. p.im = inTableBodyIM
  1557. return true
  1558. }
  1559. // Ignore the token.
  1560. return true
  1561. case a.Table:
  1562. if p.popUntil(tableScope, a.Tr) {
  1563. p.im = inTableBodyIM
  1564. return false
  1565. }
  1566. // Ignore the token.
  1567. return true
  1568. case a.Tbody, a.Tfoot, a.Thead:
  1569. if p.elementInScope(tableScope, p.tok.DataAtom) {
  1570. p.parseImpliedToken(EndTagToken, a.Tr, a.Tr.String())
  1571. return false
  1572. }
  1573. // Ignore the token.
  1574. return true
  1575. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Td, a.Th:
  1576. // Ignore the token.
  1577. return true
  1578. }
  1579. }
  1580. return inTableIM(p)
  1581. }
  1582. // Section 12.2.6.4.15.
  1583. func inCellIM(p *parser) bool {
  1584. switch p.tok.Type {
  1585. case StartTagToken:
  1586. switch p.tok.DataAtom {
  1587. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1588. if p.popUntil(tableScope, a.Td, a.Th) {
  1589. // Close the cell and reprocess.
  1590. p.clearActiveFormattingElements()
  1591. p.im = inRowIM
  1592. return false
  1593. }
  1594. // Ignore the token.
  1595. return true
  1596. case a.Select:
  1597. p.reconstructActiveFormattingElements()
  1598. p.addElement()
  1599. p.framesetOK = false
  1600. p.im = inSelectInTableIM
  1601. return true
  1602. }
  1603. case EndTagToken:
  1604. switch p.tok.DataAtom {
  1605. case a.Td, a.Th:
  1606. if !p.popUntil(tableScope, p.tok.DataAtom) {
  1607. // Ignore the token.
  1608. return true
  1609. }
  1610. p.clearActiveFormattingElements()
  1611. p.im = inRowIM
  1612. return true
  1613. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html:
  1614. // Ignore the token.
  1615. return true
  1616. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1617. if !p.elementInScope(tableScope, p.tok.DataAtom) {
  1618. // Ignore the token.
  1619. return true
  1620. }
  1621. // Close the cell and reprocess.
  1622. p.popUntil(tableScope, a.Td, a.Th)
  1623. p.clearActiveFormattingElements()
  1624. p.im = inRowIM
  1625. return false
  1626. }
  1627. }
  1628. return inBodyIM(p)
  1629. }
  1630. // Section 12.2.6.4.16.
  1631. func inSelectIM(p *parser) bool {
  1632. switch p.tok.Type {
  1633. case ErrorToken:
  1634. // Stop parsing.
  1635. return true
  1636. case TextToken:
  1637. p.addText(strings.Replace(p.tok.Data, "\x00", "", -1))
  1638. case StartTagToken:
  1639. switch p.tok.DataAtom {
  1640. case a.Html:
  1641. return inBodyIM(p)
  1642. case a.Option:
  1643. if p.top().DataAtom == a.Option {
  1644. p.oe.pop()
  1645. }
  1646. p.addElement()
  1647. case a.Optgroup:
  1648. if p.top().DataAtom == a.Option {
  1649. p.oe.pop()
  1650. }
  1651. if p.top().DataAtom == a.Optgroup {
  1652. p.oe.pop()
  1653. }
  1654. p.addElement()
  1655. case a.Select:
  1656. p.tok.Type = EndTagToken
  1657. return false
  1658. case a.Input, a.Keygen, a.Textarea:
  1659. if p.elementInScope(selectScope, a.Select) {
  1660. p.parseImpliedToken(EndTagToken, a.Select, a.Select.String())
  1661. return false
  1662. }
  1663. // In order to properly ignore <textarea>, we need to change the tokenizer mode.
  1664. p.tokenizer.NextIsNotRawText()
  1665. // Ignore the token.
  1666. return true
  1667. case a.Script, a.Template:
  1668. return inHeadIM(p)
  1669. }
  1670. case EndTagToken:
  1671. switch p.tok.DataAtom {
  1672. case a.Option:
  1673. if p.top().DataAtom == a.Option {
  1674. p.oe.pop()
  1675. }
  1676. case a.Optgroup:
  1677. i := len(p.oe) - 1
  1678. if p.oe[i].DataAtom == a.Option {
  1679. i--
  1680. }
  1681. if p.oe[i].DataAtom == a.Optgroup {
  1682. p.oe = p.oe[:i]
  1683. }
  1684. case a.Select:
  1685. if p.popUntil(selectScope, a.Select) {
  1686. p.resetInsertionMode()
  1687. }
  1688. case a.Template:
  1689. return inHeadIM(p)
  1690. }
  1691. case CommentToken:
  1692. p.addChild(&Node{
  1693. Type: CommentNode,
  1694. Data: p.tok.Data,
  1695. })
  1696. case DoctypeToken:
  1697. // Ignore the token.
  1698. return true
  1699. }
  1700. return true
  1701. }
  1702. // Section 12.2.6.4.17.
  1703. func inSelectInTableIM(p *parser) bool {
  1704. switch p.tok.Type {
  1705. case StartTagToken, EndTagToken:
  1706. switch p.tok.DataAtom {
  1707. case a.Caption, a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr, a.Td, a.Th:
  1708. if p.tok.Type == StartTagToken || p.elementInScope(tableScope, p.tok.DataAtom) {
  1709. p.parseImpliedToken(EndTagToken, a.Select, a.Select.String())
  1710. return false
  1711. } else {
  1712. // Ignore the token.
  1713. return true
  1714. }
  1715. }
  1716. }
  1717. return inSelectIM(p)
  1718. }
  1719. // Section 12.2.6.4.18.
  1720. func inTemplateIM(p *parser) bool {
  1721. switch p.tok.Type {
  1722. case TextToken, CommentToken, DoctypeToken:
  1723. return inBodyIM(p)
  1724. case StartTagToken:
  1725. switch p.tok.DataAtom {
  1726. case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
  1727. return inHeadIM(p)
  1728. case a.Caption, a.Colgroup, a.Tbody, a.Tfoot, a.Thead:
  1729. p.templateStack.pop()
  1730. p.templateStack = append(p.templateStack, inTableIM)
  1731. p.im = inTableIM
  1732. return false
  1733. case a.Col:
  1734. p.templateStack.pop()
  1735. p.templateStack = append(p.templateStack, inColumnGroupIM)
  1736. p.im = inColumnGroupIM
  1737. return false
  1738. case a.Tr:
  1739. p.templateStack.pop()
  1740. p.templateStack = append(p.templateStack, inTableBodyIM)
  1741. p.im = inTableBodyIM
  1742. return false
  1743. case a.Td, a.Th:
  1744. p.templateStack.pop()
  1745. p.templateStack = append(p.templateStack, inRowIM)
  1746. p.im = inRowIM
  1747. return false
  1748. default:
  1749. p.templateStack.pop()
  1750. p.templateStack = append(p.templateStack, inBodyIM)
  1751. p.im = inBodyIM
  1752. return false
  1753. }
  1754. case EndTagToken:
  1755. switch p.tok.DataAtom {
  1756. case a.Template:
  1757. return inHeadIM(p)
  1758. default:
  1759. // Ignore the token.
  1760. return true
  1761. }
  1762. }
  1763. if !p.oe.contains(a.Template) {
  1764. // Ignore the token.
  1765. return true
  1766. }
  1767. p.popUntil(defaultScope, a.Template)
  1768. p.clearActiveFormattingElements()
  1769. p.templateStack.pop()
  1770. p.resetInsertionMode()
  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. // The input is assumed to be UTF-8 encoded.
  2123. func Parse(r io.Reader) (*Node, error) {
  2124. p := &parser{
  2125. tokenizer: NewTokenizer(r),
  2126. doc: &Node{
  2127. Type: DocumentNode,
  2128. },
  2129. scripting: true,
  2130. framesetOK: true,
  2131. im: initialIM,
  2132. }
  2133. err := p.parse()
  2134. if err != nil {
  2135. return nil, err
  2136. }
  2137. return p.doc, nil
  2138. }
  2139. // ParseFragment parses a fragment of HTML and returns the nodes that were
  2140. // found. If the fragment is the InnerHTML for an existing element, pass that
  2141. // element in context.
  2142. func ParseFragment(r io.Reader, context *Node) ([]*Node, error) {
  2143. contextTag := ""
  2144. if context != nil {
  2145. if context.Type != ElementNode {
  2146. return nil, errors.New("html: ParseFragment of non-element Node")
  2147. }
  2148. // The next check isn't just context.DataAtom.String() == context.Data because
  2149. // it is valid to pass an element whose tag isn't a known atom. For example,
  2150. // DataAtom == 0 and Data = "tagfromthefuture" is perfectly consistent.
  2151. if context.DataAtom != a.Lookup([]byte(context.Data)) {
  2152. return nil, fmt.Errorf("html: inconsistent Node: DataAtom=%q, Data=%q", context.DataAtom, context.Data)
  2153. }
  2154. contextTag = context.DataAtom.String()
  2155. }
  2156. p := &parser{
  2157. tokenizer: NewTokenizerFragment(r, contextTag),
  2158. doc: &Node{
  2159. Type: DocumentNode,
  2160. },
  2161. scripting: true,
  2162. fragment: true,
  2163. context: context,
  2164. }
  2165. root := &Node{
  2166. Type: ElementNode,
  2167. DataAtom: a.Html,
  2168. Data: a.Html.String(),
  2169. }
  2170. p.doc.AppendChild(root)
  2171. p.oe = nodeStack{root}
  2172. if context != nil && context.DataAtom == a.Template {
  2173. p.templateStack = append(p.templateStack, inTemplateIM)
  2174. }
  2175. p.resetInsertionMode()
  2176. for n := context; n != nil; n = n.Parent {
  2177. if n.Type == ElementNode && n.DataAtom == a.Form {
  2178. p.form = n
  2179. break
  2180. }
  2181. }
  2182. err := p.parse()
  2183. if err != nil {
  2184. return nil, err
  2185. }
  2186. parent := p.doc
  2187. if context != nil {
  2188. parent = root
  2189. }
  2190. var result []*Node
  2191. for c := parent.FirstChild; c != nil; {
  2192. next := c.NextSibling
  2193. parent.RemoveChild(c)
  2194. result = append(result, c)
  2195. c = next
  2196. }
  2197. return result, nil
  2198. }