token.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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. }
  696. // startTagIn returns whether the start tag in z.buf[z.data.start:z.data.end]
  697. // case-insensitively matches any element of ss.
  698. func (z *Tokenizer) startTagIn(ss ...string) bool {
  699. loop:
  700. for _, s := range ss {
  701. if z.data.end-z.data.start != len(s) {
  702. continue loop
  703. }
  704. for i := 0; i < len(s); i++ {
  705. c := z.buf[z.data.start+i]
  706. if 'A' <= c && c <= 'Z' {
  707. c += 'a' - 'A'
  708. }
  709. if c != s[i] {
  710. continue loop
  711. }
  712. }
  713. return true
  714. }
  715. return false
  716. }
  717. // readStartTag reads the next start tag token. The opening "<a" has already
  718. // been consumed, where 'a' means anything in [A-Za-z].
  719. func (z *Tokenizer) readStartTag() TokenType {
  720. z.readTag(true)
  721. if z.err != nil {
  722. return ErrorToken
  723. }
  724. // Several tags flag the tokenizer's next token as raw.
  725. c, raw := z.buf[z.data.start], false
  726. if 'A' <= c && c <= 'Z' {
  727. c += 'a' - 'A'
  728. }
  729. switch c {
  730. case 'i':
  731. raw = z.startTagIn("iframe")
  732. case 'n':
  733. raw = z.startTagIn("noembed", "noframes", "noscript")
  734. case 'p':
  735. raw = z.startTagIn("plaintext")
  736. case 's':
  737. raw = z.startTagIn("script", "style")
  738. case 't':
  739. raw = z.startTagIn("textarea", "title")
  740. case 'x':
  741. raw = z.startTagIn("xmp")
  742. }
  743. if raw {
  744. z.rawTag = strings.ToLower(string(z.buf[z.data.start:z.data.end]))
  745. }
  746. // Look for a self-closing token like "<br/>".
  747. if z.err == nil && z.buf[z.raw.end-2] == '/' {
  748. return SelfClosingTagToken
  749. }
  750. return StartTagToken
  751. }
  752. // readTag reads the next tag token and its attributes. If saveAttr, those
  753. // attributes are saved in z.attr, otherwise z.attr is set to an empty slice.
  754. // The opening "<a" or "</a" has already been consumed, where 'a' means anything
  755. // in [A-Za-z].
  756. func (z *Tokenizer) readTag(saveAttr bool) {
  757. z.attr = z.attr[:0]
  758. z.nAttrReturned = 0
  759. // Read the tag name and attribute key/value pairs.
  760. z.readTagName()
  761. if z.skipWhiteSpace(); z.err != nil {
  762. return
  763. }
  764. for {
  765. c := z.readByte()
  766. if z.err != nil || c == '>' {
  767. break
  768. }
  769. z.raw.end--
  770. z.readTagAttrKey()
  771. z.readTagAttrVal()
  772. // Save pendingAttr if saveAttr and that attribute has a non-empty key.
  773. if saveAttr && z.pendingAttr[0].start != z.pendingAttr[0].end {
  774. z.attr = append(z.attr, z.pendingAttr)
  775. }
  776. if z.skipWhiteSpace(); z.err != nil {
  777. break
  778. }
  779. }
  780. }
  781. // readTagName sets z.data to the "div" in "<div k=v>". The reader (z.raw.end)
  782. // is positioned such that the first byte of the tag name (the "d" in "<div")
  783. // has already been consumed.
  784. func (z *Tokenizer) readTagName() {
  785. z.data.start = z.raw.end - 1
  786. for {
  787. c := z.readByte()
  788. if z.err != nil {
  789. z.data.end = z.raw.end
  790. return
  791. }
  792. switch c {
  793. case ' ', '\n', '\r', '\t', '\f':
  794. z.data.end = z.raw.end - 1
  795. return
  796. case '/', '>':
  797. z.raw.end--
  798. z.data.end = z.raw.end
  799. return
  800. }
  801. }
  802. }
  803. // readTagAttrKey sets z.pendingAttr[0] to the "k" in "<div k=v>".
  804. // Precondition: z.err == nil.
  805. func (z *Tokenizer) readTagAttrKey() {
  806. z.pendingAttr[0].start = z.raw.end
  807. for {
  808. c := z.readByte()
  809. if z.err != nil {
  810. z.pendingAttr[0].end = z.raw.end
  811. return
  812. }
  813. switch c {
  814. case ' ', '\n', '\r', '\t', '\f', '/':
  815. z.pendingAttr[0].end = z.raw.end - 1
  816. return
  817. case '=', '>':
  818. z.raw.end--
  819. z.pendingAttr[0].end = z.raw.end
  820. return
  821. }
  822. }
  823. }
  824. // readTagAttrVal sets z.pendingAttr[1] to the "v" in "<div k=v>".
  825. func (z *Tokenizer) readTagAttrVal() {
  826. z.pendingAttr[1].start = z.raw.end
  827. z.pendingAttr[1].end = z.raw.end
  828. if z.skipWhiteSpace(); z.err != nil {
  829. return
  830. }
  831. c := z.readByte()
  832. if z.err != nil {
  833. return
  834. }
  835. if c != '=' {
  836. z.raw.end--
  837. return
  838. }
  839. if z.skipWhiteSpace(); z.err != nil {
  840. return
  841. }
  842. quote := z.readByte()
  843. if z.err != nil {
  844. return
  845. }
  846. switch quote {
  847. case '>':
  848. z.raw.end--
  849. return
  850. case '\'', '"':
  851. z.pendingAttr[1].start = z.raw.end
  852. for {
  853. c := z.readByte()
  854. if z.err != nil {
  855. z.pendingAttr[1].end = z.raw.end
  856. return
  857. }
  858. if c == quote {
  859. z.pendingAttr[1].end = z.raw.end - 1
  860. return
  861. }
  862. }
  863. default:
  864. z.pendingAttr[1].start = z.raw.end - 1
  865. for {
  866. c := z.readByte()
  867. if z.err != nil {
  868. z.pendingAttr[1].end = z.raw.end
  869. return
  870. }
  871. switch c {
  872. case ' ', '\n', '\r', '\t', '\f':
  873. z.pendingAttr[1].end = z.raw.end - 1
  874. return
  875. case '>':
  876. z.raw.end--
  877. z.pendingAttr[1].end = z.raw.end
  878. return
  879. }
  880. }
  881. }
  882. }
  883. // Next scans the next token and returns its type.
  884. func (z *Tokenizer) Next() TokenType {
  885. z.raw.start = z.raw.end
  886. z.data.start = z.raw.end
  887. z.data.end = z.raw.end
  888. if z.err != nil {
  889. z.tt = ErrorToken
  890. return z.tt
  891. }
  892. if z.rawTag != "" {
  893. if z.rawTag == "plaintext" {
  894. // Read everything up to EOF.
  895. for z.err == nil {
  896. z.readByte()
  897. }
  898. z.data.end = z.raw.end
  899. z.textIsRaw = true
  900. } else {
  901. z.readRawOrRCDATA()
  902. }
  903. if z.data.end > z.data.start {
  904. z.tt = TextToken
  905. z.convertNUL = true
  906. return z.tt
  907. }
  908. }
  909. z.textIsRaw = false
  910. z.convertNUL = false
  911. loop:
  912. for {
  913. c := z.readByte()
  914. if z.err != nil {
  915. break loop
  916. }
  917. if c != '<' {
  918. continue loop
  919. }
  920. // Check if the '<' we have just read is part of a tag, comment
  921. // or doctype. If not, it's part of the accumulated text token.
  922. c = z.readByte()
  923. if z.err != nil {
  924. break loop
  925. }
  926. var tokenType TokenType
  927. switch {
  928. case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
  929. tokenType = StartTagToken
  930. case c == '/':
  931. tokenType = EndTagToken
  932. case c == '!' || c == '?':
  933. // We use CommentToken to mean any of "<!--actual comments-->",
  934. // "<!DOCTYPE declarations>" and "<?xml processing instructions?>".
  935. tokenType = CommentToken
  936. default:
  937. continue
  938. }
  939. // We have a non-text token, but we might have accumulated some text
  940. // before that. If so, we return the text first, and return the non-
  941. // text token on the subsequent call to Next.
  942. if x := z.raw.end - len("<a"); z.raw.start < x {
  943. z.raw.end = x
  944. z.data.end = x
  945. z.tt = TextToken
  946. return z.tt
  947. }
  948. switch tokenType {
  949. case StartTagToken:
  950. z.tt = z.readStartTag()
  951. return z.tt
  952. case EndTagToken:
  953. c = z.readByte()
  954. if z.err != nil {
  955. break loop
  956. }
  957. if c == '>' {
  958. // "</>" does not generate a token at all. Generate an empty comment
  959. // to allow passthrough clients to pick up the data using Raw.
  960. // Reset the tokenizer state and start again.
  961. z.tt = CommentToken
  962. return z.tt
  963. }
  964. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
  965. z.readTag(false)
  966. if z.err != nil {
  967. z.tt = ErrorToken
  968. } else {
  969. z.tt = EndTagToken
  970. }
  971. return z.tt
  972. }
  973. z.raw.end--
  974. z.readUntilCloseAngle()
  975. z.tt = CommentToken
  976. return z.tt
  977. case CommentToken:
  978. if c == '!' {
  979. z.tt = z.readMarkupDeclaration()
  980. return z.tt
  981. }
  982. z.raw.end--
  983. z.readUntilCloseAngle()
  984. z.tt = CommentToken
  985. return z.tt
  986. }
  987. }
  988. if z.raw.start < z.raw.end {
  989. z.data.end = z.raw.end
  990. z.tt = TextToken
  991. return z.tt
  992. }
  993. z.tt = ErrorToken
  994. return z.tt
  995. }
  996. // Raw returns the unmodified text of the current token. Calling Next, Token,
  997. // Text, TagName or TagAttr may change the contents of the returned slice.
  998. func (z *Tokenizer) Raw() []byte {
  999. return z.buf[z.raw.start:z.raw.end]
  1000. }
  1001. // convertNewlines converts "\r" and "\r\n" in s to "\n".
  1002. // The conversion happens in place, but the resulting slice may be shorter.
  1003. func convertNewlines(s []byte) []byte {
  1004. for i, c := range s {
  1005. if c != '\r' {
  1006. continue
  1007. }
  1008. src := i + 1
  1009. if src >= len(s) || s[src] != '\n' {
  1010. s[i] = '\n'
  1011. continue
  1012. }
  1013. dst := i
  1014. for src < len(s) {
  1015. if s[src] == '\r' {
  1016. if src+1 < len(s) && s[src+1] == '\n' {
  1017. src++
  1018. }
  1019. s[dst] = '\n'
  1020. } else {
  1021. s[dst] = s[src]
  1022. }
  1023. src++
  1024. dst++
  1025. }
  1026. return s[:dst]
  1027. }
  1028. return s
  1029. }
  1030. var (
  1031. nul = []byte("\x00")
  1032. replacement = []byte("\ufffd")
  1033. )
  1034. // Text returns the unescaped text of a text, comment or doctype token. The
  1035. // contents of the returned slice may change on the next call to Next.
  1036. func (z *Tokenizer) Text() []byte {
  1037. switch z.tt {
  1038. case TextToken, CommentToken, DoctypeToken:
  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. s = convertNewlines(s)
  1043. if (z.convertNUL || z.tt == CommentToken) && bytes.Contains(s, nul) {
  1044. s = bytes.Replace(s, nul, replacement, -1)
  1045. }
  1046. if !z.textIsRaw {
  1047. s = unescape(s, false)
  1048. }
  1049. return s
  1050. }
  1051. return nil
  1052. }
  1053. // TagName returns the lower-cased name of a tag token (the `img` out of
  1054. // `<IMG SRC="foo">`) and whether the tag has attributes.
  1055. // The contents of the returned slice may change on the next call to Next.
  1056. func (z *Tokenizer) TagName() (name []byte, hasAttr bool) {
  1057. if z.data.start < z.data.end {
  1058. switch z.tt {
  1059. case StartTagToken, EndTagToken, SelfClosingTagToken:
  1060. s := z.buf[z.data.start:z.data.end]
  1061. z.data.start = z.raw.end
  1062. z.data.end = z.raw.end
  1063. return lower(s), z.nAttrReturned < len(z.attr)
  1064. }
  1065. }
  1066. return nil, false
  1067. }
  1068. // TagAttr returns the lower-cased key and unescaped value of the next unparsed
  1069. // attribute for the current tag token and whether there are more attributes.
  1070. // The contents of the returned slices may change on the next call to Next.
  1071. func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
  1072. if z.nAttrReturned < len(z.attr) {
  1073. switch z.tt {
  1074. case StartTagToken, SelfClosingTagToken:
  1075. x := z.attr[z.nAttrReturned]
  1076. z.nAttrReturned++
  1077. key = z.buf[x[0].start:x[0].end]
  1078. val = z.buf[x[1].start:x[1].end]
  1079. return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
  1080. }
  1081. }
  1082. return nil, nil, false
  1083. }
  1084. // Token returns the next Token. The result's Data and Attr values remain valid
  1085. // after subsequent Next calls.
  1086. func (z *Tokenizer) Token() Token {
  1087. t := Token{Type: z.tt}
  1088. switch z.tt {
  1089. case TextToken, CommentToken, DoctypeToken:
  1090. t.Data = string(z.Text())
  1091. case StartTagToken, SelfClosingTagToken, EndTagToken:
  1092. name, moreAttr := z.TagName()
  1093. for moreAttr {
  1094. var key, val []byte
  1095. key, val, moreAttr = z.TagAttr()
  1096. t.Attr = append(t.Attr, Attribute{"", atom.String(key), string(val)})
  1097. }
  1098. if a := atom.Lookup(name); a != 0 {
  1099. t.DataAtom, t.Data = a, a.String()
  1100. } else {
  1101. t.DataAtom, t.Data = 0, string(name)
  1102. }
  1103. }
  1104. return t
  1105. }
  1106. // NewTokenizer returns a new HTML Tokenizer for the given Reader.
  1107. // The input is assumed to be UTF-8 encoded.
  1108. func NewTokenizer(r io.Reader) *Tokenizer {
  1109. return NewTokenizerFragment(r, "")
  1110. }
  1111. // NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for
  1112. // tokenizing an exisitng element's InnerHTML fragment. contextTag is that
  1113. // element's tag, such as "div" or "iframe".
  1114. //
  1115. // For example, how the InnerHTML "a<b" is tokenized depends on whether it is
  1116. // for a <p> tag or a <script> tag.
  1117. //
  1118. // The input is assumed to be UTF-8 encoded.
  1119. func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer {
  1120. z := &Tokenizer{
  1121. r: r,
  1122. buf: make([]byte, 0, 4096),
  1123. }
  1124. if contextTag != "" {
  1125. switch s := strings.ToLower(contextTag); s {
  1126. case "iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "title", "textarea", "xmp":
  1127. z.rawTag = s
  1128. }
  1129. }
  1130. return z
  1131. }