token.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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. "bytes"
  7. "io"
  8. "strconv"
  9. "strings"
  10. "code.google.com/p/go.net/html/atom"
  11. )
  12. // A TokenType is the type of a Token.
  13. type TokenType uint32
  14. const (
  15. // ErrorToken means that an error occurred during tokenization.
  16. ErrorToken TokenType = iota
  17. // TextToken means a text node.
  18. TextToken
  19. // A StartTagToken looks like <a>.
  20. StartTagToken
  21. // An EndTagToken looks like </a>.
  22. EndTagToken
  23. // A SelfClosingTagToken tag looks like <br/>.
  24. SelfClosingTagToken
  25. // A CommentToken looks like <!--x-->.
  26. CommentToken
  27. // A DoctypeToken looks like <!DOCTYPE x>
  28. DoctypeToken
  29. )
  30. // String returns a string representation of the TokenType.
  31. func (t TokenType) String() string {
  32. switch t {
  33. case ErrorToken:
  34. return "Error"
  35. case TextToken:
  36. return "Text"
  37. case StartTagToken:
  38. return "StartTag"
  39. case EndTagToken:
  40. return "EndTag"
  41. case SelfClosingTagToken:
  42. return "SelfClosingTag"
  43. case CommentToken:
  44. return "Comment"
  45. case DoctypeToken:
  46. return "Doctype"
  47. }
  48. return "Invalid(" + strconv.Itoa(int(t)) + ")"
  49. }
  50. // An Attribute is an attribute namespace-key-value triple. Namespace is
  51. // non-empty for foreign attributes like xlink, Key is alphabetic (and hence
  52. // does not contain escapable characters like '&', '<' or '>'), and Val is
  53. // unescaped (it looks like "a<b" rather than "a&lt;b").
  54. //
  55. // Namespace is only used by the parser, not the tokenizer.
  56. type Attribute struct {
  57. Namespace, Key, Val string
  58. }
  59. // A Token consists of a TokenType and some Data (tag name for start and end
  60. // tags, content for text, comments and doctypes). A tag Token may also contain
  61. // a slice of Attributes. Data is unescaped for all Tokens (it looks like "a<b"
  62. // rather than "a&lt;b"). For tag Tokens, DataAtom is the atom for Data, or
  63. // zero if Data is not a known tag name.
  64. type Token struct {
  65. Type TokenType
  66. DataAtom atom.Atom
  67. Data string
  68. Attr []Attribute
  69. }
  70. // tagString returns a string representation of a tag Token's Data and Attr.
  71. func (t Token) tagString() string {
  72. if len(t.Attr) == 0 {
  73. return t.Data
  74. }
  75. buf := bytes.NewBufferString(t.Data)
  76. for _, a := range t.Attr {
  77. buf.WriteByte(' ')
  78. buf.WriteString(a.Key)
  79. buf.WriteString(`="`)
  80. escape(buf, a.Val)
  81. buf.WriteByte('"')
  82. }
  83. return buf.String()
  84. }
  85. // String returns a string representation of the Token.
  86. func (t Token) String() string {
  87. switch t.Type {
  88. case ErrorToken:
  89. return ""
  90. case TextToken:
  91. return EscapeString(t.Data)
  92. case StartTagToken:
  93. return "<" + t.tagString() + ">"
  94. case EndTagToken:
  95. return "</" + t.tagString() + ">"
  96. case SelfClosingTagToken:
  97. return "<" + t.tagString() + "/>"
  98. case CommentToken:
  99. return "<!--" + t.Data + "-->"
  100. case DoctypeToken:
  101. return "<!DOCTYPE " + t.Data + ">"
  102. }
  103. return "Invalid(" + strconv.Itoa(int(t.Type)) + ")"
  104. }
  105. // span is a range of bytes in a Tokenizer's buffer. The start is inclusive,
  106. // the end is exclusive.
  107. type span struct {
  108. start, end int
  109. }
  110. // A Tokenizer returns a stream of HTML Tokens.
  111. type Tokenizer struct {
  112. // r is the source of the HTML text.
  113. r io.Reader
  114. // tt is the TokenType of the current token.
  115. tt TokenType
  116. // err is the first error encountered during tokenization. It is possible
  117. // for tt != Error && err != nil to hold: this means that Next returned a
  118. // valid token but the subsequent Next call will return an error token.
  119. // For example, if the HTML text input was just "plain", then the first
  120. // Next call would set z.err to io.EOF but return a TextToken, and all
  121. // subsequent Next calls would return an ErrorToken.
  122. // err is never reset. Once it becomes non-nil, it stays non-nil.
  123. err error
  124. // buf[raw.start:raw.end] holds the raw bytes of the current token.
  125. // buf[raw.end:] is buffered input that will yield future tokens.
  126. raw span
  127. buf []byte
  128. // buf[data.start:data.end] holds the raw bytes of the current token's data:
  129. // a text token's text, a tag token's tag name, etc.
  130. data span
  131. // pendingAttr is the attribute key and value currently being tokenized.
  132. // When complete, pendingAttr is pushed onto attr. nAttrReturned is
  133. // incremented on each call to TagAttr.
  134. pendingAttr [2]span
  135. attr [][2]span
  136. nAttrReturned int
  137. // rawTag is the "script" in "</script>" that closes the next token. If
  138. // non-empty, the subsequent call to Next will return a raw or RCDATA text
  139. // token: one that treats "<p>" as text instead of an element.
  140. // rawTag's contents are lower-cased.
  141. rawTag string
  142. // textIsRaw is whether the current text token's data is not escaped.
  143. textIsRaw bool
  144. // convertNUL is whether NUL bytes in the current token's data should
  145. // be converted into \ufffd replacement characters.
  146. convertNUL bool
  147. // allowCDATA is whether CDATA sections are allowed in the current context.
  148. allowCDATA bool
  149. }
  150. // AllowCDATA sets whether or not the tokenizer recognizes <![CDATA[foo]]> as
  151. // the text "foo". The default value is false, which means to recognize it as
  152. // a bogus comment "<!-- [CDATA[foo]] -->" instead.
  153. //
  154. // Strictly speaking, an HTML5 compliant tokenizer should allow CDATA if and
  155. // only if tokenizing foreign content, such as MathML and SVG. However,
  156. // tracking foreign-contentness is difficult to do purely in the tokenizer,
  157. // as opposed to the parser, due to HTML integration points: an <svg> element
  158. // can contain a <foreignObject> that is foreign-to-SVG but not foreign-to-
  159. // HTML. For strict compliance with the HTML5 tokenization algorithm, it is the
  160. // responsibility of the user of a tokenizer to call AllowCDATA as appropriate.
  161. // In practice, if using the tokenizer without caring whether MathML or SVG
  162. // CDATA is text or comments, such as tokenizing HTML to find all the anchor
  163. // text, it is acceptable to ignore this responsibility.
  164. func (z *Tokenizer) AllowCDATA(allowCDATA bool) {
  165. z.allowCDATA = allowCDATA
  166. }
  167. // NextIsNotRawText instructs the tokenizer that the next token should not be
  168. // considered as 'raw text'. Some elements, such as script and title elements,
  169. // normally require the next token after the opening tag to be 'raw text' that
  170. // has no child elements. For example, tokenizing "<title>a<b>c</b>d</title>"
  171. // yields a start tag token for "<title>", a text token for "a<b>c</b>d", and
  172. // an end tag token for "</title>". There are no distinct start tag or end tag
  173. // tokens for the "<b>" and "</b>".
  174. //
  175. // This tokenizer implementation will generally look for raw text at the right
  176. // times. Strictly speaking, an HTML5 compliant tokenizer should not look for
  177. // raw text if in foreign content: <title> generally needs raw text, but a
  178. // <title> inside an <svg> does not. Another example is that a <textarea>
  179. // generally needs raw text, but a <textarea> is not allowed as an immediate
  180. // child of a <select>; in normal parsing, a <textarea> implies </select>, but
  181. // one cannot close the implicit element when parsing a <select>'s InnerHTML.
  182. // Similarly to AllowCDATA, tracking the correct moment to override raw-text-
  183. // ness is difficult to do purely in the tokenizer, as opposed to the parser.
  184. // For strict compliance with the HTML5 tokenization algorithm, it is the
  185. // responsibility of the user of a tokenizer to call NextIsNotRawText as
  186. // appropriate. In practice, like AllowCDATA, it is acceptable to ignore this
  187. // responsibility for basic usage.
  188. //
  189. // Note that this 'raw text' concept is different from the one offered by the
  190. // Tokenizer.Raw method.
  191. func (z *Tokenizer) NextIsNotRawText() {
  192. z.rawTag = ""
  193. }
  194. // Err returns the error associated with the most recent ErrorToken token.
  195. // This is typically io.EOF, meaning the end of tokenization.
  196. func (z *Tokenizer) Err() error {
  197. if z.tt != ErrorToken {
  198. return nil
  199. }
  200. return z.err
  201. }
  202. // readByte returns the next byte from the input stream, doing a buffered read
  203. // from z.r into z.buf if necessary. z.buf[z.raw.start:z.raw.end] remains a contiguous byte
  204. // slice that holds all the bytes read so far for the current token.
  205. // It sets z.err if the underlying reader returns an error.
  206. // Pre-condition: z.err == nil.
  207. func (z *Tokenizer) readByte() byte {
  208. if z.raw.end >= len(z.buf) {
  209. // Our buffer is exhausted and we have to read from z.r.
  210. // We copy z.buf[z.raw.start:z.raw.end] to the beginning of z.buf. If the length
  211. // z.raw.end - z.raw.start is more than half the capacity of z.buf, then we
  212. // allocate a new buffer before the copy.
  213. c := cap(z.buf)
  214. d := z.raw.end - z.raw.start
  215. var buf1 []byte
  216. if 2*d > c {
  217. buf1 = make([]byte, d, 2*c)
  218. } else {
  219. buf1 = z.buf[:d]
  220. }
  221. copy(buf1, z.buf[z.raw.start:z.raw.end])
  222. if x := z.raw.start; x != 0 {
  223. // Adjust the data/attr spans to refer to the same contents after the copy.
  224. z.data.start -= x
  225. z.data.end -= x
  226. z.pendingAttr[0].start -= x
  227. z.pendingAttr[0].end -= x
  228. z.pendingAttr[1].start -= x
  229. z.pendingAttr[1].end -= x
  230. for i := range z.attr {
  231. z.attr[i][0].start -= x
  232. z.attr[i][0].end -= x
  233. z.attr[i][1].start -= x
  234. z.attr[i][1].end -= x
  235. }
  236. }
  237. z.raw.start, z.raw.end, z.buf = 0, d, buf1[:d]
  238. // Now that we have copied the live bytes to the start of the buffer,
  239. // we read from z.r into the remainder.
  240. n, err := z.r.Read(buf1[d:cap(buf1)])
  241. if err != nil {
  242. z.err = err
  243. return 0
  244. }
  245. z.buf = buf1[:d+n]
  246. }
  247. x := z.buf[z.raw.end]
  248. z.raw.end++
  249. return x
  250. }
  251. // skipWhiteSpace skips past any white space.
  252. func (z *Tokenizer) skipWhiteSpace() {
  253. if z.err != nil {
  254. return
  255. }
  256. for {
  257. c := z.readByte()
  258. if z.err != nil {
  259. return
  260. }
  261. switch c {
  262. case ' ', '\n', '\r', '\t', '\f':
  263. // No-op.
  264. default:
  265. z.raw.end--
  266. return
  267. }
  268. }
  269. }
  270. // readRawOrRCDATA reads until the next "</foo>", where "foo" is z.rawTag and
  271. // is typically something like "script" or "textarea".
  272. func (z *Tokenizer) readRawOrRCDATA() {
  273. if z.rawTag == "script" {
  274. z.readScript()
  275. z.textIsRaw = true
  276. z.rawTag = ""
  277. return
  278. }
  279. loop:
  280. for {
  281. c := z.readByte()
  282. if z.err != nil {
  283. break loop
  284. }
  285. if c != '<' {
  286. continue loop
  287. }
  288. c = z.readByte()
  289. if z.err != nil {
  290. break loop
  291. }
  292. if c != '/' {
  293. continue loop
  294. }
  295. if z.readRawEndTag() || z.err != nil {
  296. break loop
  297. }
  298. }
  299. z.data.end = z.raw.end
  300. // A textarea's or title's RCDATA can contain escaped entities.
  301. z.textIsRaw = z.rawTag != "textarea" && z.rawTag != "title"
  302. z.rawTag = ""
  303. }
  304. // readRawEndTag attempts to read a tag like "</foo>", where "foo" is z.rawTag.
  305. // If it succeeds, it backs up the input position to reconsume the tag and
  306. // returns true. Otherwise it returns false. The opening "</" has already been
  307. // consumed.
  308. func (z *Tokenizer) readRawEndTag() bool {
  309. for i := 0; i < len(z.rawTag); i++ {
  310. c := z.readByte()
  311. if z.err != nil {
  312. return false
  313. }
  314. if c != z.rawTag[i] && c != z.rawTag[i]-('a'-'A') {
  315. z.raw.end--
  316. return false
  317. }
  318. }
  319. c := z.readByte()
  320. if z.err != nil {
  321. return false
  322. }
  323. switch c {
  324. case ' ', '\n', '\r', '\t', '\f', '/', '>':
  325. // The 3 is 2 for the leading "</" plus 1 for the trailing character c.
  326. z.raw.end -= 3 + len(z.rawTag)
  327. return true
  328. }
  329. z.raw.end--
  330. return false
  331. }
  332. // readScript reads until the next </script> tag, following the byzantine
  333. // rules for escaping/hiding the closing tag.
  334. func (z *Tokenizer) readScript() {
  335. defer func() {
  336. z.data.end = z.raw.end
  337. }()
  338. var c byte
  339. scriptData:
  340. c = z.readByte()
  341. if z.err != nil {
  342. return
  343. }
  344. if c == '<' {
  345. goto scriptDataLessThanSign
  346. }
  347. goto scriptData
  348. scriptDataLessThanSign:
  349. c = z.readByte()
  350. if z.err != nil {
  351. return
  352. }
  353. switch c {
  354. case '/':
  355. goto scriptDataEndTagOpen
  356. case '!':
  357. goto scriptDataEscapeStart
  358. }
  359. z.raw.end--
  360. goto scriptData
  361. scriptDataEndTagOpen:
  362. if z.readRawEndTag() || z.err != nil {
  363. return
  364. }
  365. goto scriptData
  366. scriptDataEscapeStart:
  367. c = z.readByte()
  368. if z.err != nil {
  369. return
  370. }
  371. if c == '-' {
  372. goto scriptDataEscapeStartDash
  373. }
  374. z.raw.end--
  375. goto scriptData
  376. scriptDataEscapeStartDash:
  377. c = z.readByte()
  378. if z.err != nil {
  379. return
  380. }
  381. if c == '-' {
  382. goto scriptDataEscapedDashDash
  383. }
  384. z.raw.end--
  385. goto scriptData
  386. scriptDataEscaped:
  387. c = z.readByte()
  388. if z.err != nil {
  389. return
  390. }
  391. switch c {
  392. case '-':
  393. goto scriptDataEscapedDash
  394. case '<':
  395. goto scriptDataEscapedLessThanSign
  396. }
  397. goto scriptDataEscaped
  398. scriptDataEscapedDash:
  399. c = z.readByte()
  400. if z.err != nil {
  401. return
  402. }
  403. switch c {
  404. case '-':
  405. goto scriptDataEscapedDashDash
  406. case '<':
  407. goto scriptDataEscapedLessThanSign
  408. }
  409. goto scriptDataEscaped
  410. scriptDataEscapedDashDash:
  411. c = z.readByte()
  412. if z.err != nil {
  413. return
  414. }
  415. switch c {
  416. case '-':
  417. goto scriptDataEscapedDashDash
  418. case '<':
  419. goto scriptDataEscapedLessThanSign
  420. case '>':
  421. goto scriptData
  422. }
  423. goto scriptDataEscaped
  424. scriptDataEscapedLessThanSign:
  425. c = z.readByte()
  426. if z.err != nil {
  427. return
  428. }
  429. if c == '/' {
  430. goto scriptDataEscapedEndTagOpen
  431. }
  432. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  433. goto scriptDataDoubleEscapeStart
  434. }
  435. z.raw.end--
  436. goto scriptData
  437. scriptDataEscapedEndTagOpen:
  438. if z.readRawEndTag() || z.err != nil {
  439. return
  440. }
  441. goto scriptDataEscaped
  442. scriptDataDoubleEscapeStart:
  443. z.raw.end--
  444. for i := 0; i < len("script"); i++ {
  445. c = z.readByte()
  446. if z.err != nil {
  447. return
  448. }
  449. if c != "script"[i] && c != "SCRIPT"[i] {
  450. z.raw.end--
  451. goto scriptDataEscaped
  452. }
  453. }
  454. c = z.readByte()
  455. if z.err != nil {
  456. return
  457. }
  458. switch c {
  459. case ' ', '\n', '\r', '\t', '\f', '/', '>':
  460. goto scriptDataDoubleEscaped
  461. }
  462. z.raw.end--
  463. goto scriptDataEscaped
  464. scriptDataDoubleEscaped:
  465. c = z.readByte()
  466. if z.err != nil {
  467. return
  468. }
  469. switch c {
  470. case '-':
  471. goto scriptDataDoubleEscapedDash
  472. case '<':
  473. goto scriptDataDoubleEscapedLessThanSign
  474. }
  475. goto scriptDataDoubleEscaped
  476. scriptDataDoubleEscapedDash:
  477. c = z.readByte()
  478. if z.err != nil {
  479. return
  480. }
  481. switch c {
  482. case '-':
  483. goto scriptDataDoubleEscapedDashDash
  484. case '<':
  485. goto scriptDataDoubleEscapedLessThanSign
  486. }
  487. goto scriptDataDoubleEscaped
  488. scriptDataDoubleEscapedDashDash:
  489. c = z.readByte()
  490. if z.err != nil {
  491. return
  492. }
  493. switch c {
  494. case '-':
  495. goto scriptDataDoubleEscapedDashDash
  496. case '<':
  497. goto scriptDataDoubleEscapedLessThanSign
  498. case '>':
  499. goto scriptData
  500. }
  501. goto scriptDataDoubleEscaped
  502. scriptDataDoubleEscapedLessThanSign:
  503. c = z.readByte()
  504. if z.err != nil {
  505. return
  506. }
  507. if c == '/' {
  508. goto scriptDataDoubleEscapeEnd
  509. }
  510. z.raw.end--
  511. goto scriptDataDoubleEscaped
  512. scriptDataDoubleEscapeEnd:
  513. if z.readRawEndTag() {
  514. z.raw.end += len("</script>")
  515. goto scriptDataEscaped
  516. }
  517. if z.err != nil {
  518. return
  519. }
  520. goto scriptDataDoubleEscaped
  521. }
  522. // readComment reads the next comment token starting with "<!--". The opening
  523. // "<!--" has already been consumed.
  524. func (z *Tokenizer) readComment() {
  525. z.data.start = z.raw.end
  526. defer func() {
  527. if z.data.end < z.data.start {
  528. // It's a comment with no data, like <!-->.
  529. z.data.end = z.data.start
  530. }
  531. }()
  532. for dashCount := 2; ; {
  533. c := z.readByte()
  534. if z.err != nil {
  535. // Ignore up to two dashes at EOF.
  536. if dashCount > 2 {
  537. dashCount = 2
  538. }
  539. z.data.end = z.raw.end - dashCount
  540. return
  541. }
  542. switch c {
  543. case '-':
  544. dashCount++
  545. continue
  546. case '>':
  547. if dashCount >= 2 {
  548. z.data.end = z.raw.end - len("-->")
  549. return
  550. }
  551. case '!':
  552. if dashCount >= 2 {
  553. c = z.readByte()
  554. if z.err != nil {
  555. z.data.end = z.raw.end
  556. return
  557. }
  558. if c == '>' {
  559. z.data.end = z.raw.end - len("--!>")
  560. return
  561. }
  562. }
  563. }
  564. dashCount = 0
  565. }
  566. }
  567. // readUntilCloseAngle reads until the next ">".
  568. func (z *Tokenizer) readUntilCloseAngle() {
  569. z.data.start = z.raw.end
  570. for {
  571. c := z.readByte()
  572. if z.err != nil {
  573. z.data.end = z.raw.end
  574. return
  575. }
  576. if c == '>' {
  577. z.data.end = z.raw.end - len(">")
  578. return
  579. }
  580. }
  581. }
  582. // readMarkupDeclaration reads the next token starting with "<!". It might be
  583. // a "<!--comment-->", a "<!DOCTYPE foo>", a "<![CDATA[section]]>" or
  584. // "<!a bogus comment". The opening "<!" has already been consumed.
  585. func (z *Tokenizer) readMarkupDeclaration() TokenType {
  586. z.data.start = z.raw.end
  587. var c [2]byte
  588. for i := 0; i < 2; i++ {
  589. c[i] = z.readByte()
  590. if z.err != nil {
  591. z.data.end = z.raw.end
  592. return CommentToken
  593. }
  594. }
  595. if c[0] == '-' && c[1] == '-' {
  596. z.readComment()
  597. return CommentToken
  598. }
  599. z.raw.end -= 2
  600. if z.readDoctype() {
  601. return DoctypeToken
  602. }
  603. if z.allowCDATA && z.readCDATA() {
  604. z.convertNUL = true
  605. return TextToken
  606. }
  607. // It's a bogus comment.
  608. z.readUntilCloseAngle()
  609. return CommentToken
  610. }
  611. // readDoctype attempts to read a doctype declaration and returns true if
  612. // successful. The opening "<!" has already been consumed.
  613. func (z *Tokenizer) readDoctype() bool {
  614. const s = "DOCTYPE"
  615. for i := 0; i < len(s); i++ {
  616. c := z.readByte()
  617. if z.err != nil {
  618. z.data.end = z.raw.end
  619. return false
  620. }
  621. if c != s[i] && c != s[i]+('a'-'A') {
  622. // Back up to read the fragment of "DOCTYPE" again.
  623. z.raw.end = z.data.start
  624. return false
  625. }
  626. }
  627. if z.skipWhiteSpace(); z.err != nil {
  628. z.data.start = z.raw.end
  629. z.data.end = z.raw.end
  630. return true
  631. }
  632. z.readUntilCloseAngle()
  633. return true
  634. }
  635. // readCDATA attempts to read a CDATA section and returns true if
  636. // successful. The opening "<!" has already been consumed.
  637. func (z *Tokenizer) readCDATA() bool {
  638. const s = "[CDATA["
  639. for i := 0; i < len(s); i++ {
  640. c := z.readByte()
  641. if z.err != nil {
  642. z.data.end = z.raw.end
  643. return false
  644. }
  645. if c != s[i] {
  646. // Back up to read the fragment of "[CDATA[" again.
  647. z.raw.end = z.data.start
  648. return false
  649. }
  650. }
  651. z.data.start = z.raw.end
  652. brackets := 0
  653. for {
  654. c := z.readByte()
  655. if z.err != nil {
  656. z.data.end = z.raw.end
  657. return true
  658. }
  659. switch c {
  660. case ']':
  661. brackets++
  662. case '>':
  663. if brackets >= 2 {
  664. z.data.end = z.raw.end - len("]]>")
  665. return true
  666. }
  667. brackets = 0
  668. default:
  669. brackets = 0
  670. }
  671. }
  672. panic("unreachable")
  673. }
  674. // startTagIn returns whether the start tag in z.buf[z.data.start:z.data.end]
  675. // case-insensitively matches any element of ss.
  676. func (z *Tokenizer) startTagIn(ss ...string) bool {
  677. loop:
  678. for _, s := range ss {
  679. if z.data.end-z.data.start != len(s) {
  680. continue loop
  681. }
  682. for i := 0; i < len(s); i++ {
  683. c := z.buf[z.data.start+i]
  684. if 'A' <= c && c <= 'Z' {
  685. c += 'a' - 'A'
  686. }
  687. if c != s[i] {
  688. continue loop
  689. }
  690. }
  691. return true
  692. }
  693. return false
  694. }
  695. // readStartTag reads the next start tag token. The opening "<a" has already
  696. // been consumed, where 'a' means anything in [A-Za-z].
  697. func (z *Tokenizer) readStartTag() TokenType {
  698. z.readTag(true)
  699. if z.err != nil {
  700. return ErrorToken
  701. }
  702. // Several tags flag the tokenizer's next token as raw.
  703. c, raw := z.buf[z.data.start], false
  704. if 'A' <= c && c <= 'Z' {
  705. c += 'a' - 'A'
  706. }
  707. switch c {
  708. case 'i':
  709. raw = z.startTagIn("iframe")
  710. case 'n':
  711. raw = z.startTagIn("noembed", "noframes", "noscript")
  712. case 'p':
  713. raw = z.startTagIn("plaintext")
  714. case 's':
  715. raw = z.startTagIn("script", "style")
  716. case 't':
  717. raw = z.startTagIn("textarea", "title")
  718. case 'x':
  719. raw = z.startTagIn("xmp")
  720. }
  721. if raw {
  722. z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end]))
  723. }
  724. // Look for a self-closing token like "<br/>".
  725. if z.err == nil && z.buf[z.raw.end-2] == '/' {
  726. return SelfClosingTagToken
  727. }
  728. return StartTagToken
  729. }
  730. // readTag reads the next tag token and its attributes. If saveAttr, those
  731. // attributes are saved in z.attr, otherwise z.attr is set to an empty slice.
  732. // The opening "<a" or "</a" has already been consumed, where 'a' means anything
  733. // in [A-Za-z].
  734. func (z *Tokenizer) readTag(saveAttr bool) {
  735. z.attr = z.attr[:0]
  736. z.nAttrReturned = 0
  737. // Read the tag name and attribute key/value pairs.
  738. z.readTagName()
  739. if z.skipWhiteSpace(); z.err != nil {
  740. return
  741. }
  742. for {
  743. c := z.readByte()
  744. if z.err != nil || c == '>' {
  745. break
  746. }
  747. z.raw.end--
  748. z.readTagAttrKey()
  749. z.readTagAttrVal()
  750. // Save pendingAttr if saveAttr and that attribute has a non-empty key.
  751. if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end {
  752. z.attr = append(z.attr, z.pendingAttr)
  753. }
  754. if z.skipWhiteSpace(); z.err != nil {
  755. break
  756. }
  757. }
  758. }
  759. // readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end)
  760. // is positioned such that the first byte of the tag name (the "d" in "<div")
  761. // has already been consumed.
  762. func (z *Tokenizer) readTagName() {
  763. z.data.start = z.raw.end - 1
  764. for {
  765. c := z.readByte()
  766. if z.err != nil {
  767. z.data.end = z.raw.end
  768. return
  769. }
  770. switch c {
  771. case ' ', '\n', '\r', '\t', '\f':
  772. z.data.end = z.raw.end - 1
  773. return
  774. case '/', '>':
  775. z.raw.end--
  776. z.data.end = z.raw.end
  777. return
  778. }
  779. }
  780. }
  781. // readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>".
  782. // Precondition: z.err == nil.
  783. func (z *Tokenizer) readTagAttrKey() {
  784. z.pendingAttr[0].start = z.raw.end
  785. for {
  786. c := z.readByte()
  787. if z.err != nil {
  788. z.pendingAttr[0].end = z.raw.end
  789. return
  790. }
  791. switch c {
  792. case ' ', '\n', '\r', '\t', '\f', '/':
  793. z.pendingAttr[0].end = z.raw.end - 1
  794. return
  795. case '=', '>':
  796. z.raw.end--
  797. z.pendingAttr[0].end = z.raw.end
  798. return
  799. }
  800. }
  801. }
  802. // readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>".
  803. func (z *Tokenizer) readTagAttrVal() {
  804. z.pendingAttr[1].start = z.raw.end
  805. z.pendingAttr[1].end = z.raw.end
  806. if z.skipWhiteSpace(); z.err != nil {
  807. return
  808. }
  809. c := z.readByte()
  810. if z.err != nil {
  811. return
  812. }
  813. if c != '=' {
  814. z.raw.end--
  815. return
  816. }
  817. if z.skipWhiteSpace(); z.err != nil {
  818. return
  819. }
  820. quote := z.readByte()
  821. if z.err != nil {
  822. return
  823. }
  824. switch quote {
  825. case '>':
  826. z.raw.end--
  827. return
  828. case '\'', '"':
  829. z.pendingAttr[1].start = z.raw.end
  830. for {
  831. c := z.readByte()
  832. if z.err != nil {
  833. z.pendingAttr[1].end = z.raw.end
  834. return
  835. }
  836. if c == quote {
  837. z.pendingAttr[1].end = z.raw.end - 1
  838. return
  839. }
  840. }
  841. default:
  842. z.pendingAttr[1].start = z.raw.end - 1
  843. for {
  844. c := z.readByte()
  845. if z.err != nil {
  846. z.pendingAttr[1].end = z.raw.end
  847. return
  848. }
  849. switch c {
  850. case ' ', '\n', '\r', '\t', '\f':
  851. z.pendingAttr[1].end = z.raw.end - 1
  852. return
  853. case '>':
  854. z.raw.end--
  855. z.pendingAttr[1].end = z.raw.end
  856. return
  857. }
  858. }
  859. }
  860. }
  861. // Next scans the next token and returns its type.
  862. func (z *Tokenizer) Next() TokenType {
  863. if z.err != nil {
  864. z.tt = ErrorToken
  865. return z.tt
  866. }
  867. z.raw.start = z.raw.end
  868. z.data.start = z.raw.end
  869. z.data.end = z.raw.end
  870. if z.rawTag != "" {
  871. if z.rawTag == "plaintext" {
  872. // Read everything up to EOF.
  873. for z.err == nil {
  874. z.readByte()
  875. }
  876. z.data.end = z.raw.end
  877. z.textIsRaw = true
  878. } else {
  879. z.readRawOrRCDATA()
  880. }
  881. if z.data.end > z.data.start {
  882. z.tt = TextToken
  883. z.convertNUL = true
  884. return z.tt
  885. }
  886. }
  887. z.textIsRaw = false
  888. z.convertNUL = false
  889. loop:
  890. for {
  891. c := z.readByte()
  892. if z.err != nil {
  893. break loop
  894. }
  895. if c != '<' {
  896. continue loop
  897. }
  898. // Check if the '<' we have just read is part of a tag, comment
  899. // or doctype. If not, it's part of the accumulated text token.
  900. c = z.readByte()
  901. if z.err != nil {
  902. break loop
  903. }
  904. var tokenType TokenType
  905. switch {
  906. case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
  907. tokenType = StartTagToken
  908. case c == '/':
  909. tokenType = EndTagToken
  910. case c == '!' || c == '?':
  911. // We use CommentToken to mean any of "<!--actual comments-->",
  912. // "<!DOCTYPE declarations>" and "<?xml processing instructions?>".
  913. tokenType = CommentToken
  914. default:
  915. continue
  916. }
  917. // We have a non-text token, but we might have accumulated some text
  918. // before that. If so, we return the text first, and return the non-
  919. // text token on the subsequent call to Next.
  920. if x := z.raw.end - len("<a"); z.raw.start < x {
  921. z.raw.end = x
  922. z.data.end = x
  923. z.tt = TextToken
  924. return z.tt
  925. }
  926. switch tokenType {
  927. case StartTagToken:
  928. z.tt = z.readStartTag()
  929. return z.tt
  930. case EndTagToken:
  931. c = z.readByte()
  932. if z.err != nil {
  933. break loop
  934. }
  935. if c == '>' {
  936. // "</>" does not generate a token at all.
  937. // Reset the tokenizer state and start again.
  938. z.raw.start = z.raw.end
  939. z.data.start = z.raw.end
  940. z.data.end = z.raw.end
  941. continue loop
  942. }
  943. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  944. z.readTag(false)
  945. if z.err != nil {
  946. z.tt = ErrorToken
  947. } else {
  948. z.tt = EndTagToken
  949. }
  950. return z.tt
  951. }
  952. z.raw.end--
  953. z.readUntilCloseAngle()
  954. z.tt = CommentToken
  955. return z.tt
  956. case CommentToken:
  957. if c == '!' {
  958. z.tt = z.readMarkupDeclaration()
  959. return z.tt
  960. }
  961. z.raw.end--
  962. z.readUntilCloseAngle()
  963. z.tt = CommentToken
  964. return z.tt
  965. }
  966. }
  967. if z.raw.start < z.raw.end {
  968. z.data.end = z.raw.end
  969. z.tt = TextToken
  970. return z.tt
  971. }
  972. z.tt = ErrorToken
  973. return z.tt
  974. }
  975. // Raw returns the unmodified text of the current token. Calling Next, Token,
  976. // Text, TagName or TagAttr may change the contents of the returned slice.
  977. func (z *Tokenizer) Raw() []byte {
  978. return z.buf[z.raw.start:z.raw.end]
  979. }
  980. // convertNewlines converts "\r" and "\r\n" in s to "\n".
  981. // The conversion happens in place, but the resulting slice may be shorter.
  982. func convertNewlines(s []byte) []byte {
  983. for i, c := range s {
  984. if c != '\r' {
  985. continue
  986. }
  987. src := i + 1
  988. if src >= len(s) || s[src] != '\n' {
  989. s[i] = '\n'
  990. continue
  991. }
  992. dst := i
  993. for src < len(s) {
  994. if s[src] == '\r' {
  995. if src+1 < len(s) && s[src+1] == '\n' {
  996. src++
  997. }
  998. s[dst] = '\n'
  999. } else {
  1000. s[dst] = s[src]
  1001. }
  1002. src++
  1003. dst++
  1004. }
  1005. return s[:dst]
  1006. }
  1007. return s
  1008. }
  1009. var (
  1010. nul = []byte("\x00")
  1011. replacement = []byte("\ufffd")
  1012. )
  1013. // Text returns the unescaped text of a text, comment or doctype token. The
  1014. // contents of the returned slice may change on the next call to Next.
  1015. func (z *Tokenizer) Text() []byte {
  1016. switch z.tt {
  1017. case TextToken, CommentToken, DoctypeToken:
  1018. s := z.buf[z.data.start:z.data.end]
  1019. z.data.start = z.raw.end
  1020. z.data.end = z.raw.end
  1021. s = convertNewlines(s)
  1022. if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) {
  1023. s = bytes.Replace(s, nul, replacement, -1)
  1024. }
  1025. if !z.textIsRaw {
  1026. s = unescape(s, false)
  1027. }
  1028. return s
  1029. }
  1030. return nil
  1031. }
  1032. // TagName returns the lower-cased name of a tag token (the `img` out of
  1033. // `<IMG SRC="foo">`) and whether the tag has attributes.
  1034. // The contents of the returned slice may change on the next call to Next.
  1035. func (z *Tokenizer) TagName() (name []byte, hasAttr bool) {
  1036. if z.data.start < z.data.end {
  1037. switch z.tt {
  1038. case StartTagToken, EndTagToken, SelfClosingTagToken:
  1039. s := z.buf[z.data.start:z.data.end]
  1040. z.data.start = z.raw.end
  1041. z.data.end = z.raw.end
  1042. return lower(s), z.nAttrReturned < len(z.attr)
  1043. }
  1044. }
  1045. return nil, false
  1046. }
  1047. // TagAttr returns the lower-cased key and unescaped value of the next unparsed
  1048. // attribute for the current tag token and whether there are more attributes.
  1049. // The contents of the returned slices may change on the next call to Next.
  1050. func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
  1051. if z.nAttrReturned < len(z.attr) {
  1052. switch z.tt {
  1053. case StartTagToken, SelfClosingTagToken:
  1054. x := z.attr[z.nAttrReturned]
  1055. z.nAttrReturned++
  1056. key = z.buf[x[0].start:x[0].end]
  1057. val = z.buf[x[1].start:x[1].end]
  1058. return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
  1059. }
  1060. }
  1061. return nil, nil, false
  1062. }
  1063. // Token returns the next Token. The result's Data and Attr values remain valid
  1064. // after subsequent Next calls.
  1065. func (z *Tokenizer) Token() Token {
  1066. t := Token{Type: z.tt}
  1067. switch z.tt {
  1068. case TextToken, CommentToken, DoctypeToken:
  1069. t.Data = string(z.Text())
  1070. case StartTagToken, SelfClosingTagToken, EndTagToken:
  1071. name, moreAttr := z.TagName()
  1072. for moreAttr {
  1073. var key, val []byte
  1074. key, val, moreAttr = z.TagAttr()
  1075. t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)})
  1076. }
  1077. if a := atom.Lookup(name); a != 0 {
  1078. t.DataAtom, t.Data = a, a.String()
  1079. } else {
  1080. t.DataAtom, t.Data = 0, string(name)
  1081. }
  1082. }
  1083. return t
  1084. }
  1085. // NewTokenizer returns a new HTML Tokenizer for the given Reader.
  1086. // The input is assumed to be UTF-8 encoded.
  1087. func NewTokenizer(r io.Reader) *Tokenizer {
  1088. return NewTokenizerFragment(r, "")
  1089. }
  1090. // NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for
  1091. // tokenizing an exisitng element's InnerHTML fragment. contextTag is that
  1092. // element's tag, such as "div" or "iframe".
  1093. //
  1094. // For example, how the InnerHTML "a<b" is tokenized depends on whether it is
  1095. // for a <p> tag or a <script> tag.
  1096. //
  1097. // The input is assumed to be UTF-8 encoded.
  1098. func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer {
  1099. z := &Tokenizer{
  1100. r: r,
  1101. buf: make([]byte, 0, 4096),
  1102. }
  1103. if contextTag != "" {
  1104. switch s := strings.ToLower(contextTag); s {
  1105. case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp":
  1106. z.rawTag = s
  1107. }
  1108. }
  1109. return z
  1110. }