parse.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307
  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.Frame:
  1024. // TODO: remove this divergence from the HTML5 spec.
  1025. if p.oe.contains(a.Template) {
  1026. p.addElement()
  1027. return true
  1028. }
  1029. case a.Caption, a.Col, a.Colgroup, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1030. // Ignore the token.
  1031. default:
  1032. p.reconstructActiveFormattingElements()
  1033. p.addElement()
  1034. }
  1035. case EndTagToken:
  1036. switch p.tok.DataAtom {
  1037. case a.Body:
  1038. if p.elementInScope(defaultScope, a.Body) {
  1039. p.im = afterBodyIM
  1040. }
  1041. case a.Html:
  1042. if p.elementInScope(defaultScope, a.Body) {
  1043. p.parseImpliedToken(EndTagToken, a.Body, a.Body.String())
  1044. return false
  1045. }
  1046. return true
  1047. 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:
  1048. p.popUntil(defaultScope, p.tok.DataAtom)
  1049. case a.Form:
  1050. if p.oe.contains(a.Template) {
  1051. i := p.indexOfElementInScope(defaultScope, a.Form)
  1052. if i == -1 {
  1053. // Ignore the token.
  1054. return true
  1055. }
  1056. p.generateImpliedEndTags()
  1057. if p.oe[i].DataAtom != a.Form {
  1058. // Ignore the token.
  1059. return true
  1060. }
  1061. p.popUntil(defaultScope, a.Form)
  1062. } else {
  1063. node := p.form
  1064. p.form = nil
  1065. i := p.indexOfElementInScope(defaultScope, a.Form)
  1066. if node == nil || i == -1 || p.oe[i] != node {
  1067. // Ignore the token.
  1068. return true
  1069. }
  1070. p.generateImpliedEndTags()
  1071. p.oe.remove(node)
  1072. }
  1073. case a.P:
  1074. if !p.elementInScope(buttonScope, a.P) {
  1075. p.parseImpliedToken(StartTagToken, a.P, a.P.String())
  1076. }
  1077. p.popUntil(buttonScope, a.P)
  1078. case a.Li:
  1079. p.popUntil(listItemScope, a.Li)
  1080. case a.Dd, a.Dt:
  1081. p.popUntil(defaultScope, p.tok.DataAtom)
  1082. case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
  1083. p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6)
  1084. 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:
  1085. p.inBodyEndTagFormatting(p.tok.DataAtom)
  1086. case a.Applet, a.Marquee, a.Object:
  1087. if p.popUntil(defaultScope, p.tok.DataAtom) {
  1088. p.clearActiveFormattingElements()
  1089. }
  1090. case a.Br:
  1091. p.tok.Type = StartTagToken
  1092. return false
  1093. case a.Template:
  1094. return inHeadIM(p)
  1095. default:
  1096. p.inBodyEndTagOther(p.tok.DataAtom)
  1097. }
  1098. case CommentToken:
  1099. p.addChild(&Node{
  1100. Type: CommentNode,
  1101. Data: p.tok.Data,
  1102. })
  1103. case ErrorToken:
  1104. // TODO: remove this divergence from the HTML5 spec.
  1105. if len(p.templateStack) > 0 {
  1106. p.im = inTemplateIM
  1107. return false
  1108. } else {
  1109. for _, e := range p.oe {
  1110. switch e.DataAtom {
  1111. 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,
  1112. a.Thead, a.Tr, a.Body, a.Html:
  1113. default:
  1114. return true
  1115. }
  1116. }
  1117. }
  1118. }
  1119. return true
  1120. }
  1121. func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) {
  1122. // This is the "adoption agency" algorithm, described at
  1123. // https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency
  1124. // TODO: this is a fairly literal line-by-line translation of that algorithm.
  1125. // Once the code successfully parses the comprehensive test suite, we should
  1126. // refactor this code to be more idiomatic.
  1127. // Steps 1-4. The outer loop.
  1128. for i := 0; i < 8; i++ {
  1129. // Step 5. Find the formatting element.
  1130. var formattingElement *Node
  1131. for j := len(p.afe) - 1; j >= 0; j-- {
  1132. if p.afe[j].Type == scopeMarkerNode {
  1133. break
  1134. }
  1135. if p.afe[j].DataAtom == tagAtom {
  1136. formattingElement = p.afe[j]
  1137. break
  1138. }
  1139. }
  1140. if formattingElement == nil {
  1141. p.inBodyEndTagOther(tagAtom)
  1142. return
  1143. }
  1144. feIndex := p.oe.index(formattingElement)
  1145. if feIndex == -1 {
  1146. p.afe.remove(formattingElement)
  1147. return
  1148. }
  1149. if !p.elementInScope(defaultScope, tagAtom) {
  1150. // Ignore the tag.
  1151. return
  1152. }
  1153. // Steps 9-10. Find the furthest block.
  1154. var furthestBlock *Node
  1155. for _, e := range p.oe[feIndex:] {
  1156. if isSpecialElement(e) {
  1157. furthestBlock = e
  1158. break
  1159. }
  1160. }
  1161. if furthestBlock == nil {
  1162. e := p.oe.pop()
  1163. for e != formattingElement {
  1164. e = p.oe.pop()
  1165. }
  1166. p.afe.remove(e)
  1167. return
  1168. }
  1169. // Steps 11-12. Find the common ancestor and bookmark node.
  1170. commonAncestor := p.oe[feIndex-1]
  1171. bookmark := p.afe.index(formattingElement)
  1172. // Step 13. The inner loop. Find the lastNode to reparent.
  1173. lastNode := furthestBlock
  1174. node := furthestBlock
  1175. x := p.oe.index(node)
  1176. // Steps 13.1-13.2
  1177. for j := 0; j < 3; j++ {
  1178. // Step 13.3.
  1179. x--
  1180. node = p.oe[x]
  1181. // Step 13.4 - 13.5.
  1182. if p.afe.index(node) == -1 {
  1183. p.oe.remove(node)
  1184. continue
  1185. }
  1186. // Step 13.6.
  1187. if node == formattingElement {
  1188. break
  1189. }
  1190. // Step 13.7.
  1191. clone := node.clone()
  1192. p.afe[p.afe.index(node)] = clone
  1193. p.oe[p.oe.index(node)] = clone
  1194. node = clone
  1195. // Step 13.8.
  1196. if lastNode == furthestBlock {
  1197. bookmark = p.afe.index(node) + 1
  1198. }
  1199. // Step 13.9.
  1200. if lastNode.Parent != nil {
  1201. lastNode.Parent.RemoveChild(lastNode)
  1202. }
  1203. node.AppendChild(lastNode)
  1204. // Step 13.10.
  1205. lastNode = node
  1206. }
  1207. // Step 14. Reparent lastNode to the common ancestor,
  1208. // or for misnested table nodes, to the foster parent.
  1209. if lastNode.Parent != nil {
  1210. lastNode.Parent.RemoveChild(lastNode)
  1211. }
  1212. switch commonAncestor.DataAtom {
  1213. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1214. p.fosterParent(lastNode)
  1215. case a.Template:
  1216. // TODO: remove namespace checking
  1217. if commonAncestor.Namespace == "html" {
  1218. commonAncestor = commonAncestor.LastChild
  1219. }
  1220. fallthrough
  1221. default:
  1222. commonAncestor.AppendChild(lastNode)
  1223. }
  1224. // Steps 15-17. Reparent nodes from the furthest block's children
  1225. // to a clone of the formatting element.
  1226. clone := formattingElement.clone()
  1227. reparentChildren(clone, furthestBlock)
  1228. furthestBlock.AppendChild(clone)
  1229. // Step 18. Fix up the list of active formatting elements.
  1230. if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark {
  1231. // Move the bookmark with the rest of the list.
  1232. bookmark--
  1233. }
  1234. p.afe.remove(formattingElement)
  1235. p.afe.insert(bookmark, clone)
  1236. // Step 19. Fix up the stack of open elements.
  1237. p.oe.remove(formattingElement)
  1238. p.oe.insert(p.oe.index(furthestBlock)+1, clone)
  1239. }
  1240. }
  1241. // inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM.
  1242. // "Any other end tag" handling from 12.2.6.5 The rules for parsing tokens in foreign content
  1243. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign
  1244. func (p *parser) inBodyEndTagOther(tagAtom a.Atom) {
  1245. for i := len(p.oe) - 1; i >= 0; i-- {
  1246. if p.oe[i].DataAtom == tagAtom {
  1247. p.oe = p.oe[:i]
  1248. break
  1249. }
  1250. if isSpecialElement(p.oe[i]) {
  1251. break
  1252. }
  1253. }
  1254. }
  1255. // Section 12.2.6.4.8.
  1256. func textIM(p *parser) bool {
  1257. switch p.tok.Type {
  1258. case ErrorToken:
  1259. p.oe.pop()
  1260. case TextToken:
  1261. d := p.tok.Data
  1262. if n := p.oe.top(); n.DataAtom == a.Textarea && n.FirstChild == nil {
  1263. // Ignore a newline at the start of a <textarea> block.
  1264. if d != "" && d[0] == '\r' {
  1265. d = d[1:]
  1266. }
  1267. if d != "" && d[0] == '\n' {
  1268. d = d[1:]
  1269. }
  1270. }
  1271. if d == "" {
  1272. return true
  1273. }
  1274. p.addText(d)
  1275. return true
  1276. case EndTagToken:
  1277. p.oe.pop()
  1278. }
  1279. p.im = p.originalIM
  1280. p.originalIM = nil
  1281. return p.tok.Type == EndTagToken
  1282. }
  1283. // Section 12.2.6.4.9.
  1284. func inTableIM(p *parser) bool {
  1285. switch p.tok.Type {
  1286. case ErrorToken:
  1287. // Stop parsing.
  1288. return true
  1289. case TextToken:
  1290. p.tok.Data = strings.Replace(p.tok.Data, "\x00", "", -1)
  1291. switch p.oe.top().DataAtom {
  1292. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1293. if strings.Trim(p.tok.Data, whitespace) == "" {
  1294. p.addText(p.tok.Data)
  1295. return true
  1296. }
  1297. }
  1298. case StartTagToken:
  1299. switch p.tok.DataAtom {
  1300. case a.Caption:
  1301. p.clearStackToContext(tableScope)
  1302. p.afe = append(p.afe, &scopeMarker)
  1303. p.addElement()
  1304. p.im = inCaptionIM
  1305. return true
  1306. case a.Colgroup:
  1307. p.clearStackToContext(tableScope)
  1308. p.addElement()
  1309. p.im = inColumnGroupIM
  1310. return true
  1311. case a.Col:
  1312. p.parseImpliedToken(StartTagToken, a.Colgroup, a.Colgroup.String())
  1313. return false
  1314. case a.Tbody, a.Tfoot, a.Thead:
  1315. p.clearStackToContext(tableScope)
  1316. p.addElement()
  1317. p.im = inTableBodyIM
  1318. return true
  1319. case a.Td, a.Th, a.Tr:
  1320. p.parseImpliedToken(StartTagToken, a.Tbody, a.Tbody.String())
  1321. return false
  1322. case a.Table:
  1323. if p.popUntil(tableScope, a.Table) {
  1324. p.resetInsertionMode()
  1325. return false
  1326. }
  1327. // Ignore the token.
  1328. return true
  1329. case a.Style, a.Script, a.Template:
  1330. return inHeadIM(p)
  1331. case a.Input:
  1332. for _, t := range p.tok.Attr {
  1333. if t.Key == "type" && strings.ToLower(t.Val) == "hidden" {
  1334. p.addElement()
  1335. p.oe.pop()
  1336. return true
  1337. }
  1338. }
  1339. // Otherwise drop down to the default action.
  1340. case a.Form:
  1341. if p.oe.contains(a.Template) || p.form != nil {
  1342. // Ignore the token.
  1343. return true
  1344. }
  1345. p.addElement()
  1346. p.form = p.oe.pop()
  1347. case a.Select:
  1348. p.reconstructActiveFormattingElements()
  1349. switch p.top().DataAtom {
  1350. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1351. p.fosterParenting = true
  1352. }
  1353. p.addElement()
  1354. p.fosterParenting = false
  1355. p.framesetOK = false
  1356. p.im = inSelectInTableIM
  1357. return true
  1358. }
  1359. case EndTagToken:
  1360. switch p.tok.DataAtom {
  1361. case a.Table:
  1362. if p.popUntil(tableScope, a.Table) {
  1363. p.resetInsertionMode()
  1364. return true
  1365. }
  1366. // Ignore the token.
  1367. return true
  1368. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1369. // Ignore the token.
  1370. return true
  1371. case a.Template:
  1372. return inHeadIM(p)
  1373. }
  1374. case CommentToken:
  1375. p.addChild(&Node{
  1376. Type: CommentNode,
  1377. Data: p.tok.Data,
  1378. })
  1379. return true
  1380. case DoctypeToken:
  1381. // Ignore the token.
  1382. return true
  1383. }
  1384. p.fosterParenting = true
  1385. defer func() { p.fosterParenting = false }()
  1386. return inBodyIM(p)
  1387. }
  1388. // Section 12.2.6.4.11.
  1389. func inCaptionIM(p *parser) bool {
  1390. switch p.tok.Type {
  1391. case StartTagToken:
  1392. switch p.tok.DataAtom {
  1393. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Thead, a.Tr:
  1394. if p.popUntil(tableScope, a.Caption) {
  1395. p.clearActiveFormattingElements()
  1396. p.im = inTableIM
  1397. return false
  1398. } else {
  1399. // Ignore the token.
  1400. return true
  1401. }
  1402. case a.Select:
  1403. p.reconstructActiveFormattingElements()
  1404. p.addElement()
  1405. p.framesetOK = false
  1406. p.im = inSelectInTableIM
  1407. return true
  1408. }
  1409. case EndTagToken:
  1410. switch p.tok.DataAtom {
  1411. case a.Caption:
  1412. if p.popUntil(tableScope, a.Caption) {
  1413. p.clearActiveFormattingElements()
  1414. p.im = inTableIM
  1415. }
  1416. return true
  1417. case a.Table:
  1418. if p.popUntil(tableScope, a.Caption) {
  1419. p.clearActiveFormattingElements()
  1420. p.im = inTableIM
  1421. return false
  1422. } else {
  1423. // Ignore the token.
  1424. return true
  1425. }
  1426. case a.Body, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1427. // Ignore the token.
  1428. return true
  1429. }
  1430. }
  1431. return inBodyIM(p)
  1432. }
  1433. // Section 12.2.6.4.12.
  1434. func inColumnGroupIM(p *parser) bool {
  1435. switch p.tok.Type {
  1436. case TextToken:
  1437. s := strings.TrimLeft(p.tok.Data, whitespace)
  1438. if len(s) < len(p.tok.Data) {
  1439. // Add the initial whitespace to the current node.
  1440. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)])
  1441. if s == "" {
  1442. return true
  1443. }
  1444. p.tok.Data = s
  1445. }
  1446. case CommentToken:
  1447. p.addChild(&Node{
  1448. Type: CommentNode,
  1449. Data: p.tok.Data,
  1450. })
  1451. return true
  1452. case DoctypeToken:
  1453. // Ignore the token.
  1454. return true
  1455. case StartTagToken:
  1456. switch p.tok.DataAtom {
  1457. case a.Html:
  1458. return inBodyIM(p)
  1459. case a.Col:
  1460. p.addElement()
  1461. p.oe.pop()
  1462. p.acknowledgeSelfClosingTag()
  1463. return true
  1464. case a.Template:
  1465. return inHeadIM(p)
  1466. }
  1467. case EndTagToken:
  1468. switch p.tok.DataAtom {
  1469. case a.Colgroup:
  1470. if p.oe.top().DataAtom == a.Colgroup {
  1471. p.oe.pop()
  1472. p.im = inTableIM
  1473. }
  1474. return true
  1475. case a.Col:
  1476. // Ignore the token.
  1477. return true
  1478. case a.Template:
  1479. return inHeadIM(p)
  1480. }
  1481. }
  1482. if p.oe.top().DataAtom != a.Colgroup {
  1483. return true
  1484. }
  1485. p.oe.pop()
  1486. p.im = inTableIM
  1487. return false
  1488. }
  1489. // Section 12.2.6.4.13.
  1490. func inTableBodyIM(p *parser) bool {
  1491. switch p.tok.Type {
  1492. case StartTagToken:
  1493. switch p.tok.DataAtom {
  1494. case a.Tr:
  1495. p.clearStackToContext(tableBodyScope)
  1496. p.addElement()
  1497. p.im = inRowIM
  1498. return true
  1499. case a.Td, a.Th:
  1500. p.parseImpliedToken(StartTagToken, a.Tr, a.Tr.String())
  1501. return false
  1502. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Tfoot, a.Thead:
  1503. if p.popUntil(tableScope, a.Tbody, a.Thead, a.Tfoot) {
  1504. p.im = inTableIM
  1505. return false
  1506. }
  1507. // Ignore the token.
  1508. return true
  1509. }
  1510. case EndTagToken:
  1511. switch p.tok.DataAtom {
  1512. case a.Tbody, a.Tfoot, a.Thead:
  1513. if p.elementInScope(tableScope, p.tok.DataAtom) {
  1514. p.clearStackToContext(tableBodyScope)
  1515. p.oe.pop()
  1516. p.im = inTableIM
  1517. }
  1518. return true
  1519. case a.Table:
  1520. if p.popUntil(tableScope, a.Tbody, a.Thead, a.Tfoot) {
  1521. p.im = inTableIM
  1522. return false
  1523. }
  1524. // Ignore the token.
  1525. return true
  1526. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Td, a.Th, a.Tr:
  1527. // Ignore the token.
  1528. return true
  1529. }
  1530. case CommentToken:
  1531. p.addChild(&Node{
  1532. Type: CommentNode,
  1533. Data: p.tok.Data,
  1534. })
  1535. return true
  1536. }
  1537. return inTableIM(p)
  1538. }
  1539. // Section 12.2.6.4.14.
  1540. func inRowIM(p *parser) bool {
  1541. switch p.tok.Type {
  1542. case StartTagToken:
  1543. switch p.tok.DataAtom {
  1544. case a.Td, a.Th:
  1545. p.clearStackToContext(tableRowScope)
  1546. p.addElement()
  1547. p.afe = append(p.afe, &scopeMarker)
  1548. p.im = inCellIM
  1549. return true
  1550. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1551. if p.popUntil(tableScope, a.Tr) {
  1552. p.im = inTableBodyIM
  1553. return false
  1554. }
  1555. // Ignore the token.
  1556. return true
  1557. }
  1558. case EndTagToken:
  1559. switch p.tok.DataAtom {
  1560. case a.Tr:
  1561. if p.popUntil(tableScope, a.Tr) {
  1562. p.im = inTableBodyIM
  1563. return true
  1564. }
  1565. // Ignore the token.
  1566. return true
  1567. case a.Table:
  1568. if p.popUntil(tableScope, a.Tr) {
  1569. p.im = inTableBodyIM
  1570. return false
  1571. }
  1572. // Ignore the token.
  1573. return true
  1574. case a.Tbody, a.Tfoot, a.Thead:
  1575. if p.elementInScope(tableScope, p.tok.DataAtom) {
  1576. p.parseImpliedToken(EndTagToken, a.Tr, a.Tr.String())
  1577. return false
  1578. }
  1579. // Ignore the token.
  1580. return true
  1581. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Td, a.Th:
  1582. // Ignore the token.
  1583. return true
  1584. }
  1585. }
  1586. return inTableIM(p)
  1587. }
  1588. // Section 12.2.6.4.15.
  1589. func inCellIM(p *parser) bool {
  1590. switch p.tok.Type {
  1591. case StartTagToken:
  1592. switch p.tok.DataAtom {
  1593. case a.Caption, a.Col, a.Colgroup, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
  1594. if p.popUntil(tableScope, a.Td, a.Th) {
  1595. // Close the cell and reprocess.
  1596. p.clearActiveFormattingElements()
  1597. p.im = inRowIM
  1598. return false
  1599. }
  1600. // Ignore the token.
  1601. return true
  1602. case a.Select:
  1603. p.reconstructActiveFormattingElements()
  1604. p.addElement()
  1605. p.framesetOK = false
  1606. p.im = inSelectInTableIM
  1607. return true
  1608. }
  1609. case EndTagToken:
  1610. switch p.tok.DataAtom {
  1611. case a.Td, a.Th:
  1612. if !p.popUntil(tableScope, p.tok.DataAtom) {
  1613. // Ignore the token.
  1614. return true
  1615. }
  1616. p.clearActiveFormattingElements()
  1617. p.im = inRowIM
  1618. return true
  1619. case a.Body, a.Caption, a.Col, a.Colgroup, a.Html:
  1620. // Ignore the token.
  1621. return true
  1622. case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
  1623. if !p.elementInScope(tableScope, p.tok.DataAtom) {
  1624. // Ignore the token.
  1625. return true
  1626. }
  1627. // Close the cell and reprocess.
  1628. p.popUntil(tableScope, a.Td, a.Th)
  1629. p.clearActiveFormattingElements()
  1630. p.im = inRowIM
  1631. return false
  1632. }
  1633. }
  1634. return inBodyIM(p)
  1635. }
  1636. // Section 12.2.6.4.16.
  1637. func inSelectIM(p *parser) bool {
  1638. switch p.tok.Type {
  1639. case ErrorToken:
  1640. // Stop parsing.
  1641. return true
  1642. case TextToken:
  1643. p.addText(strings.Replace(p.tok.Data, "\x00", "", -1))
  1644. case StartTagToken:
  1645. switch p.tok.DataAtom {
  1646. case a.Html:
  1647. return inBodyIM(p)
  1648. case a.Option:
  1649. if p.top().DataAtom == a.Option {
  1650. p.oe.pop()
  1651. }
  1652. p.addElement()
  1653. case a.Optgroup:
  1654. if p.top().DataAtom == a.Option {
  1655. p.oe.pop()
  1656. }
  1657. if p.top().DataAtom == a.Optgroup {
  1658. p.oe.pop()
  1659. }
  1660. p.addElement()
  1661. case a.Select:
  1662. p.tok.Type = EndTagToken
  1663. return false
  1664. case a.Input, a.Keygen, a.Textarea:
  1665. if p.elementInScope(selectScope, a.Select) {
  1666. p.parseImpliedToken(EndTagToken, a.Select, a.Select.String())
  1667. return false
  1668. }
  1669. // In order to properly ignore <textarea>, we need to change the tokenizer mode.
  1670. p.tokenizer.NextIsNotRawText()
  1671. // Ignore the token.
  1672. return true
  1673. case a.Script, a.Template:
  1674. return inHeadIM(p)
  1675. }
  1676. case EndTagToken:
  1677. switch p.tok.DataAtom {
  1678. case a.Option:
  1679. if p.top().DataAtom == a.Option {
  1680. p.oe.pop()
  1681. }
  1682. case a.Optgroup:
  1683. i := len(p.oe) - 1
  1684. if p.oe[i].DataAtom == a.Option {
  1685. i--
  1686. }
  1687. if p.oe[i].DataAtom == a.Optgroup {
  1688. p.oe = p.oe[:i]
  1689. }
  1690. case a.Select:
  1691. if p.popUntil(selectScope, a.Select) {
  1692. p.resetInsertionMode()
  1693. }
  1694. case a.Template:
  1695. return inHeadIM(p)
  1696. }
  1697. case CommentToken:
  1698. p.addChild(&Node{
  1699. Type: CommentNode,
  1700. Data: p.tok.Data,
  1701. })
  1702. case DoctypeToken:
  1703. // Ignore the token.
  1704. return true
  1705. }
  1706. return true
  1707. }
  1708. // Section 12.2.6.4.17.
  1709. func inSelectInTableIM(p *parser) bool {
  1710. switch p.tok.Type {
  1711. case StartTagToken, EndTagToken:
  1712. switch p.tok.DataAtom {
  1713. case a.Caption, a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr, a.Td, a.Th:
  1714. if p.tok.Type == StartTagToken || p.elementInScope(tableScope, p.tok.DataAtom) {
  1715. p.parseImpliedToken(EndTagToken, a.Select, a.Select.String())
  1716. return false
  1717. } else {
  1718. // Ignore the token.
  1719. return true
  1720. }
  1721. }
  1722. }
  1723. return inSelectIM(p)
  1724. }
  1725. // Section 12.2.6.4.18.
  1726. func inTemplateIM(p *parser) bool {
  1727. switch p.tok.Type {
  1728. case TextToken, CommentToken, DoctypeToken:
  1729. return inBodyIM(p)
  1730. case StartTagToken:
  1731. switch p.tok.DataAtom {
  1732. case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title:
  1733. return inHeadIM(p)
  1734. case a.Caption, a.Colgroup, a.Tbody, a.Tfoot, a.Thead:
  1735. p.templateStack.pop()
  1736. p.templateStack = append(p.templateStack, inTableIM)
  1737. p.im = inTableIM
  1738. return false
  1739. case a.Col:
  1740. p.templateStack.pop()
  1741. p.templateStack = append(p.templateStack, inColumnGroupIM)
  1742. p.im = inColumnGroupIM
  1743. return false
  1744. case a.Tr:
  1745. p.templateStack.pop()
  1746. p.templateStack = append(p.templateStack, inTableBodyIM)
  1747. p.im = inTableBodyIM
  1748. return false
  1749. case a.Td, a.Th:
  1750. p.templateStack.pop()
  1751. p.templateStack = append(p.templateStack, inRowIM)
  1752. p.im = inRowIM
  1753. return false
  1754. default:
  1755. p.templateStack.pop()
  1756. p.templateStack = append(p.templateStack, inBodyIM)
  1757. p.im = inBodyIM
  1758. return false
  1759. }
  1760. case EndTagToken:
  1761. switch p.tok.DataAtom {
  1762. case a.Template:
  1763. return inHeadIM(p)
  1764. default:
  1765. // Ignore the token.
  1766. return true
  1767. }
  1768. }
  1769. if !p.oe.contains(a.Template) {
  1770. // Ignore the token.
  1771. return true
  1772. }
  1773. p.popUntil(defaultScope, a.Template)
  1774. p.clearActiveFormattingElements()
  1775. p.templateStack.pop()
  1776. p.resetInsertionMode()
  1777. return false
  1778. }
  1779. // Section 12.2.6.4.19.
  1780. func afterBodyIM(p *parser) bool {
  1781. switch p.tok.Type {
  1782. case ErrorToken:
  1783. // Stop parsing.
  1784. return true
  1785. case TextToken:
  1786. s := strings.TrimLeft(p.tok.Data, whitespace)
  1787. if len(s) == 0 {
  1788. // It was all whitespace.
  1789. return inBodyIM(p)
  1790. }
  1791. case StartTagToken:
  1792. if p.tok.DataAtom == a.Html {
  1793. return inBodyIM(p)
  1794. }
  1795. case EndTagToken:
  1796. if p.tok.DataAtom == a.Html {
  1797. if !p.fragment {
  1798. p.im = afterAfterBodyIM
  1799. }
  1800. return true
  1801. }
  1802. case CommentToken:
  1803. // The comment is attached to the <html> element.
  1804. if len(p.oe) < 1 || p.oe[0].DataAtom != a.Html {
  1805. panic("html: bad parser state: <html> element not found, in the after-body insertion mode")
  1806. }
  1807. p.oe[0].AppendChild(&Node{
  1808. Type: CommentNode,
  1809. Data: p.tok.Data,
  1810. })
  1811. return true
  1812. }
  1813. p.im = inBodyIM
  1814. return false
  1815. }
  1816. // Section 12.2.6.4.20.
  1817. func inFramesetIM(p *parser) bool {
  1818. switch p.tok.Type {
  1819. case CommentToken:
  1820. p.addChild(&Node{
  1821. Type: CommentNode,
  1822. Data: p.tok.Data,
  1823. })
  1824. case TextToken:
  1825. // Ignore all text but whitespace.
  1826. s := strings.Map(func(c rune) rune {
  1827. switch c {
  1828. case ' ', '\t', '\n', '\f', '\r':
  1829. return c
  1830. }
  1831. return -1
  1832. }, p.tok.Data)
  1833. if s != "" {
  1834. p.addText(s)
  1835. }
  1836. case StartTagToken:
  1837. switch p.tok.DataAtom {
  1838. case a.Html:
  1839. return inBodyIM(p)
  1840. case a.Frameset:
  1841. p.addElement()
  1842. case a.Frame:
  1843. p.addElement()
  1844. p.oe.pop()
  1845. p.acknowledgeSelfClosingTag()
  1846. case a.Noframes:
  1847. return inHeadIM(p)
  1848. case a.Template:
  1849. // TODO: remove this divergence from the HTML5 spec.
  1850. //
  1851. // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668
  1852. return inTemplateIM(p)
  1853. }
  1854. case EndTagToken:
  1855. switch p.tok.DataAtom {
  1856. case a.Frameset:
  1857. if p.oe.top().DataAtom != a.Html {
  1858. p.oe.pop()
  1859. if p.oe.top().DataAtom != a.Frameset {
  1860. p.im = afterFramesetIM
  1861. return true
  1862. }
  1863. }
  1864. }
  1865. default:
  1866. // Ignore the token.
  1867. }
  1868. return true
  1869. }
  1870. // Section 12.2.6.4.21.
  1871. func afterFramesetIM(p *parser) bool {
  1872. switch p.tok.Type {
  1873. case CommentToken:
  1874. p.addChild(&Node{
  1875. Type: CommentNode,
  1876. Data: p.tok.Data,
  1877. })
  1878. case TextToken:
  1879. // Ignore all text but whitespace.
  1880. s := strings.Map(func(c rune) rune {
  1881. switch c {
  1882. case ' ', '\t', '\n', '\f', '\r':
  1883. return c
  1884. }
  1885. return -1
  1886. }, p.tok.Data)
  1887. if s != "" {
  1888. p.addText(s)
  1889. }
  1890. case StartTagToken:
  1891. switch p.tok.DataAtom {
  1892. case a.Html:
  1893. return inBodyIM(p)
  1894. case a.Noframes:
  1895. return inHeadIM(p)
  1896. }
  1897. case EndTagToken:
  1898. switch p.tok.DataAtom {
  1899. case a.Html:
  1900. p.im = afterAfterFramesetIM
  1901. return true
  1902. }
  1903. default:
  1904. // Ignore the token.
  1905. }
  1906. return true
  1907. }
  1908. // Section 12.2.6.4.22.
  1909. func afterAfterBodyIM(p *parser) bool {
  1910. switch p.tok.Type {
  1911. case ErrorToken:
  1912. // Stop parsing.
  1913. return true
  1914. case TextToken:
  1915. s := strings.TrimLeft(p.tok.Data, whitespace)
  1916. if len(s) == 0 {
  1917. // It was all whitespace.
  1918. return inBodyIM(p)
  1919. }
  1920. case StartTagToken:
  1921. if p.tok.DataAtom == a.Html {
  1922. return inBodyIM(p)
  1923. }
  1924. case CommentToken:
  1925. p.doc.AppendChild(&Node{
  1926. Type: CommentNode,
  1927. Data: p.tok.Data,
  1928. })
  1929. return true
  1930. case DoctypeToken:
  1931. return inBodyIM(p)
  1932. }
  1933. p.im = inBodyIM
  1934. return false
  1935. }
  1936. // Section 12.2.6.4.23.
  1937. func afterAfterFramesetIM(p *parser) bool {
  1938. switch p.tok.Type {
  1939. case CommentToken:
  1940. p.doc.AppendChild(&Node{
  1941. Type: CommentNode,
  1942. Data: p.tok.Data,
  1943. })
  1944. case TextToken:
  1945. // Ignore all text but whitespace.
  1946. s := strings.Map(func(c rune) rune {
  1947. switch c {
  1948. case ' ', '\t', '\n', '\f', '\r':
  1949. return c
  1950. }
  1951. return -1
  1952. }, p.tok.Data)
  1953. if s != "" {
  1954. p.tok.Data = s
  1955. return inBodyIM(p)
  1956. }
  1957. case StartTagToken:
  1958. switch p.tok.DataAtom {
  1959. case a.Html:
  1960. return inBodyIM(p)
  1961. case a.Noframes:
  1962. return inHeadIM(p)
  1963. }
  1964. case DoctypeToken:
  1965. return inBodyIM(p)
  1966. default:
  1967. // Ignore the token.
  1968. }
  1969. return true
  1970. }
  1971. const whitespaceOrNUL = whitespace + "\x00"
  1972. // Section 12.2.6.5
  1973. func parseForeignContent(p *parser) bool {
  1974. switch p.tok.Type {
  1975. case TextToken:
  1976. if p.framesetOK {
  1977. p.framesetOK = strings.TrimLeft(p.tok.Data, whitespaceOrNUL) == ""
  1978. }
  1979. p.tok.Data = strings.Replace(p.tok.Data, "\x00", "\ufffd", -1)
  1980. p.addText(p.tok.Data)
  1981. case CommentToken:
  1982. p.addChild(&Node{
  1983. Type: CommentNode,
  1984. Data: p.tok.Data,
  1985. })
  1986. case StartTagToken:
  1987. b := breakout[p.tok.Data]
  1988. if p.tok.DataAtom == a.Font {
  1989. loop:
  1990. for _, attr := range p.tok.Attr {
  1991. switch attr.Key {
  1992. case "color", "face", "size":
  1993. b = true
  1994. break loop
  1995. }
  1996. }
  1997. }
  1998. if b {
  1999. for i := len(p.oe) - 1; i >= 0; i-- {
  2000. n := p.oe[i]
  2001. if n.Namespace == "" || htmlIntegrationPoint(n) || mathMLTextIntegrationPoint(n) {
  2002. p.oe = p.oe[:i+1]
  2003. break
  2004. }
  2005. }
  2006. return false
  2007. }
  2008. switch p.top().Namespace {
  2009. case "math":
  2010. adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments)
  2011. case "svg":
  2012. // Adjust SVG tag names. The tokenizer lower-cases tag names, but
  2013. // SVG wants e.g. "foreignObject" with a capital second "O".
  2014. if x := svgTagNameAdjustments[p.tok.Data]; x != "" {
  2015. p.tok.DataAtom = a.Lookup([]byte(x))
  2016. p.tok.Data = x
  2017. }
  2018. adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments)
  2019. default:
  2020. panic("html: bad parser state: unexpected namespace")
  2021. }
  2022. adjustForeignAttributes(p.tok.Attr)
  2023. namespace := p.top().Namespace
  2024. p.addElement()
  2025. p.top().Namespace = namespace
  2026. if namespace != "" {
  2027. // Don't let the tokenizer go into raw text mode in foreign content
  2028. // (e.g. in an SVG <title> tag).
  2029. p.tokenizer.NextIsNotRawText()
  2030. }
  2031. if p.hasSelfClosingToken {
  2032. p.oe.pop()
  2033. p.acknowledgeSelfClosingTag()
  2034. }
  2035. case EndTagToken:
  2036. for i := len(p.oe) - 1; i >= 0; i-- {
  2037. if p.oe[i].Namespace == "" {
  2038. return p.im(p)
  2039. }
  2040. if strings.EqualFold(p.oe[i].Data, p.tok.Data) {
  2041. p.oe = p.oe[:i]
  2042. break
  2043. }
  2044. }
  2045. return true
  2046. default:
  2047. // Ignore the token.
  2048. }
  2049. return true
  2050. }
  2051. // Section 12.2.6.
  2052. func (p *parser) inForeignContent() bool {
  2053. if len(p.oe) == 0 {
  2054. return false
  2055. }
  2056. n := p.oe[len(p.oe)-1]
  2057. if n.Namespace == "" {
  2058. return false
  2059. }
  2060. if mathMLTextIntegrationPoint(n) {
  2061. if p.tok.Type == StartTagToken && p.tok.DataAtom != a.Mglyph && p.tok.DataAtom != a.Malignmark {
  2062. return false
  2063. }
  2064. if p.tok.Type == TextToken {
  2065. return false
  2066. }
  2067. }
  2068. if n.Namespace == "math" && n.DataAtom == a.AnnotationXml && p.tok.Type == StartTagToken && p.tok.DataAtom == a.Svg {
  2069. return false
  2070. }
  2071. if htmlIntegrationPoint(n) && (p.tok.Type == StartTagToken || p.tok.Type == TextToken) {
  2072. return false
  2073. }
  2074. if p.tok.Type == ErrorToken {
  2075. return false
  2076. }
  2077. return true
  2078. }
  2079. // parseImpliedToken parses a token as though it had appeared in the parser's
  2080. // input.
  2081. func (p *parser) parseImpliedToken(t TokenType, dataAtom a.Atom, data string) {
  2082. realToken, selfClosing := p.tok, p.hasSelfClosingToken
  2083. p.tok = Token{
  2084. Type: t,
  2085. DataAtom: dataAtom,
  2086. Data: data,
  2087. }
  2088. p.hasSelfClosingToken = false
  2089. p.parseCurrentToken()
  2090. p.tok, p.hasSelfClosingToken = realToken, selfClosing
  2091. }
  2092. // parseCurrentToken runs the current token through the parsing routines
  2093. // until it is consumed.
  2094. func (p *parser) parseCurrentToken() {
  2095. if p.tok.Type == SelfClosingTagToken {
  2096. p.hasSelfClosingToken = true
  2097. p.tok.Type = StartTagToken
  2098. }
  2099. consumed := false
  2100. for !consumed {
  2101. if p.inForeignContent() {
  2102. consumed = parseForeignContent(p)
  2103. } else {
  2104. consumed = p.im(p)
  2105. }
  2106. }
  2107. if p.hasSelfClosingToken {
  2108. // This is a parse error, but ignore it.
  2109. p.hasSelfClosingToken = false
  2110. }
  2111. }
  2112. func (p *parser) parse() error {
  2113. // Iterate until EOF. Any other error will cause an early return.
  2114. var err error
  2115. for err != io.EOF {
  2116. // CDATA sections are allowed only in foreign content.
  2117. n := p.oe.top()
  2118. p.tokenizer.AllowCDATA(n != nil && n.Namespace != "")
  2119. // Read and parse the next token.
  2120. p.tokenizer.Next()
  2121. p.tok = p.tokenizer.Token()
  2122. if p.tok.Type == ErrorToken {
  2123. err = p.tokenizer.Err()
  2124. if err != nil && err != io.EOF {
  2125. return err
  2126. }
  2127. }
  2128. p.parseCurrentToken()
  2129. }
  2130. return nil
  2131. }
  2132. // Parse returns the parse tree for the HTML from the given Reader.
  2133. // The input is assumed to be UTF-8 encoded.
  2134. func Parse(r io.Reader) (*Node, error) {
  2135. p := &parser{
  2136. tokenizer: NewTokenizer(r),
  2137. doc: &Node{
  2138. Type: DocumentNode,
  2139. },
  2140. scripting: true,
  2141. framesetOK: true,
  2142. im: initialIM,
  2143. }
  2144. err := p.parse()
  2145. if err != nil {
  2146. return nil, err
  2147. }
  2148. return p.doc, nil
  2149. }
  2150. // ParseFragment parses a fragment of HTML and returns the nodes that were
  2151. // found. If the fragment is the InnerHTML for an existing element, pass that
  2152. // element in context.
  2153. func ParseFragment(r io.Reader, context *Node) ([]*Node, error) {
  2154. contextTag := ""
  2155. if context != nil {
  2156. if context.Type != ElementNode {
  2157. return nil, errors.New("html: ParseFragment of non-element Node")
  2158. }
  2159. // The next check isn't just context.DataAtom.String() == context.Data because
  2160. // it is valid to pass an element whose tag isn't a known atom. For example,
  2161. // DataAtom == 0 and Data = "tagfromthefuture" is perfectly consistent.
  2162. if context.DataAtom != a.Lookup([]byte(context.Data)) {
  2163. return nil, fmt.Errorf("html: inconsistent Node: DataAtom=%q, Data=%q", context.DataAtom, context.Data)
  2164. }
  2165. contextTag = context.DataAtom.String()
  2166. }
  2167. p := &parser{
  2168. tokenizer: NewTokenizerFragment(r, contextTag),
  2169. doc: &Node{
  2170. Type: DocumentNode,
  2171. },
  2172. scripting: true,
  2173. fragment: true,
  2174. context: context,
  2175. }
  2176. root := &Node{
  2177. Type: ElementNode,
  2178. DataAtom: a.Html,
  2179. Data: a.Html.String(),
  2180. }
  2181. p.doc.AppendChild(root)
  2182. p.oe = nodeStack{root}
  2183. if context != nil && context.DataAtom == a.Template {
  2184. p.templateStack = append(p.templateStack, inTemplateIM)
  2185. }
  2186. p.resetInsertionMode()
  2187. for n := context; n != nil; n = n.Parent {
  2188. if n.Type == ElementNode && n.DataAtom == a.Form {
  2189. p.form = n
  2190. break
  2191. }
  2192. }
  2193. err := p.parse()
  2194. if err != nil {
  2195. return nil, err
  2196. }
  2197. parent := p.doc
  2198. if context != nil {
  2199. parent = root
  2200. }
  2201. var result []*Node
  2202. for c := parent.FirstChild; c != nil; {
  2203. next := c.NextSibling
  2204. parent.RemoveChild(c)
  2205. result = append(result, c)
  2206. c = next
  2207. }
  2208. return result, nil
  2209. }