parse.go 48 KB

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