parse.go 54 KB

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