parse.go 56 KB

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