parse.go 54 KB

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