parse.go 56 KB

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