token.go 29 KB

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