parse.go 59 KB

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