tokenizer.ts 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. /**
  2. * This Tokenizer is adapted from htmlparser2 under the MIT License listed at
  3. * https://github.com/fb55/htmlparser2/blob/master/LICENSE
  4. Copyright 2010, 2011, Chris Winberry <chris@winberry.net>. All rights reserved.
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to
  7. deal in the Software without restriction, including without limitation the
  8. rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  9. sell copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  18. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  19. IN THE SOFTWARE.
  20. */
  21. import { ErrorCodes } from './errors'
  22. import { ElementNode, Position } from './ast'
  23. /**
  24. * Note: entities is a non-browser-build-only dependency.
  25. * In the browser, we use an HTML element to do the decoding.
  26. * Make sure all imports from entities are only used in non-browser branches
  27. * so that it can be properly treeshaken.
  28. */
  29. import {
  30. EntityDecoder,
  31. DecodingMode,
  32. htmlDecodeTree,
  33. fromCodePoint
  34. } from 'entities/lib/decode.js'
  35. export enum ParseMode {
  36. BASE,
  37. HTML,
  38. SFC
  39. }
  40. export enum CharCodes {
  41. Tab = 0x9, // "\t"
  42. NewLine = 0xa, // "\n"
  43. FormFeed = 0xc, // "\f"
  44. CarriageReturn = 0xd, // "\r"
  45. Space = 0x20, // " "
  46. ExclamationMark = 0x21, // "!"
  47. Number = 0x23, // "#"
  48. Amp = 0x26, // "&"
  49. SingleQuote = 0x27, // "'"
  50. DoubleQuote = 0x22, // '"'
  51. GraveAccent = 96, // "`"
  52. Dash = 0x2d, // "-"
  53. Slash = 0x2f, // "/"
  54. Zero = 0x30, // "0"
  55. Nine = 0x39, // "9"
  56. Semi = 0x3b, // ";"
  57. Lt = 0x3c, // "<"
  58. Eq = 0x3d, // "="
  59. Gt = 0x3e, // ">"
  60. Questionmark = 0x3f, // "?"
  61. UpperA = 0x41, // "A"
  62. LowerA = 0x61, // "a"
  63. UpperF = 0x46, // "F"
  64. LowerF = 0x66, // "f"
  65. UpperZ = 0x5a, // "Z"
  66. LowerZ = 0x7a, // "z"
  67. LowerX = 0x78, // "x"
  68. LowerV = 0x76, // "v"
  69. Dot = 0x2e, // "."
  70. Colon = 0x3a, // ":"
  71. At = 0x40, // "@"
  72. LeftSquare = 91, // "["
  73. RightSquare = 93 // "]"
  74. }
  75. const defaultDelimitersOpen = new Uint8Array([123, 123]) // "{{"
  76. const defaultDelimitersClose = new Uint8Array([125, 125]) // "}}"
  77. /** All the states the tokenizer can be in. */
  78. export enum State {
  79. Text = 1,
  80. // interpolation
  81. InterpolationOpen,
  82. Interpolation,
  83. InterpolationClose,
  84. // Tags
  85. BeforeTagName, // After <
  86. InTagName,
  87. InSelfClosingTag,
  88. BeforeClosingTagName,
  89. InClosingTagName,
  90. AfterClosingTagName,
  91. // Attrs
  92. BeforeAttrName,
  93. InAttrName,
  94. InDirName,
  95. InDirArg,
  96. InDirDynamicArg,
  97. InDirModifier,
  98. AfterAttrName,
  99. BeforeAttrValue,
  100. InAttrValueDq, // "
  101. InAttrValueSq, // '
  102. InAttrValueNq,
  103. // Declarations
  104. BeforeDeclaration, // !
  105. InDeclaration,
  106. // Processing instructions
  107. InProcessingInstruction, // ?
  108. // Comments & CDATA
  109. BeforeComment,
  110. CDATASequence,
  111. InSpecialComment,
  112. InCommentLike,
  113. // Special tags
  114. BeforeSpecialS, // Decide if we deal with `<script` or `<style`
  115. BeforeSpecialT, // Decide if we deal with `<title` or `<textarea`
  116. SpecialStartSequence,
  117. InRCDATA,
  118. InEntity,
  119. InSFCRootTagName
  120. }
  121. /**
  122. * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a
  123. * tag name.
  124. */
  125. function isTagStartChar(c: number): boolean {
  126. return (
  127. (c >= CharCodes.LowerA && c <= CharCodes.LowerZ) ||
  128. (c >= CharCodes.UpperA && c <= CharCodes.UpperZ)
  129. )
  130. }
  131. export function isWhitespace(c: number): boolean {
  132. return (
  133. c === CharCodes.Space ||
  134. c === CharCodes.NewLine ||
  135. c === CharCodes.Tab ||
  136. c === CharCodes.FormFeed ||
  137. c === CharCodes.CarriageReturn
  138. )
  139. }
  140. function isEndOfTagSection(c: number): boolean {
  141. return c === CharCodes.Slash || c === CharCodes.Gt || isWhitespace(c)
  142. }
  143. export function toCharCodes(str: string): Uint8Array {
  144. const ret = new Uint8Array(str.length)
  145. for (let i = 0; i < str.length; i++) {
  146. ret[i] = str.charCodeAt(i)
  147. }
  148. return ret
  149. }
  150. export enum QuoteType {
  151. NoValue = 0,
  152. Unquoted = 1,
  153. Single = 2,
  154. Double = 3
  155. }
  156. export interface Callbacks {
  157. ontext(start: number, endIndex: number): void
  158. ontextentity(char: string, start: number, endIndex: number): void
  159. oninterpolation(start: number, endIndex: number): void
  160. onopentagname(start: number, endIndex: number): void
  161. onopentagend(endIndex: number): void
  162. onselfclosingtag(endIndex: number): void
  163. onclosetag(start: number, endIndex: number): void
  164. onattribdata(start: number, endIndex: number): void
  165. onattribentity(char: string, start: number, end: number): void
  166. onattribend(quote: QuoteType, endIndex: number): void
  167. onattribname(start: number, endIndex: number): void
  168. onattribnameend(endIndex: number): void
  169. ondirname(start: number, endIndex: number): void
  170. ondirarg(start: number, endIndex: number): void
  171. ondirmodifier(start: number, endIndex: number): void
  172. oncomment(start: number, endIndex: number): void
  173. oncdata(start: number, endIndex: number): void
  174. onprocessinginstruction(start: number, endIndex: number): void
  175. // ondeclaration(start: number, endIndex: number): void
  176. onend(): void
  177. onerr(code: ErrorCodes, index: number): void
  178. }
  179. /**
  180. * Sequences used to match longer strings.
  181. *
  182. * We don't have `Script`, `Style`, or `Title` here. Instead, we re-use the *End
  183. * sequences with an increased offset.
  184. */
  185. export const Sequences = {
  186. Cdata: new Uint8Array([0x43, 0x44, 0x41, 0x54, 0x41, 0x5b]), // CDATA[
  187. CdataEnd: new Uint8Array([0x5d, 0x5d, 0x3e]), // ]]>
  188. CommentEnd: new Uint8Array([0x2d, 0x2d, 0x3e]), // `-->`
  189. ScriptEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74]), // `</script`
  190. StyleEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x74, 0x79, 0x6c, 0x65]), // `</style`
  191. TitleEnd: new Uint8Array([0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65]), // `</title`
  192. TextareaEnd: new Uint8Array([
  193. 0x3c, 0x2f, 116, 101, 120, 116, 97, 114, 101, 97
  194. ]) // `</textarea
  195. }
  196. export default class Tokenizer {
  197. /** The current state the tokenizer is in. */
  198. public state = State.Text
  199. /** The read buffer. */
  200. private buffer = ''
  201. /** The beginning of the section that is currently being read. */
  202. public sectionStart = 0
  203. /** The index within the buffer that we are currently looking at. */
  204. private index = 0
  205. /** The start of the last entity. */
  206. private entityStart = 0
  207. /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */
  208. private baseState = State.Text
  209. /** For special parsing behavior inside of script and style tags. */
  210. public inRCDATA = false
  211. /** For disabling RCDATA tags handling */
  212. public inXML = false
  213. /** Record newline positions for fast line / column calculation */
  214. private newlines: number[] = []
  215. private readonly entityDecoder?: EntityDecoder
  216. public mode = ParseMode.BASE
  217. public get inSFCRoot() {
  218. return this.mode === ParseMode.SFC && this.stack.length === 0
  219. }
  220. constructor(
  221. private readonly stack: ElementNode[],
  222. private readonly cbs: Callbacks
  223. ) {
  224. if (!__BROWSER__) {
  225. this.entityDecoder = new EntityDecoder(htmlDecodeTree, (cp, consumed) =>
  226. this.emitCodePoint(cp, consumed)
  227. )
  228. }
  229. }
  230. public reset(): void {
  231. this.state = State.Text
  232. this.mode = ParseMode.BASE
  233. this.buffer = ''
  234. this.sectionStart = 0
  235. this.index = 0
  236. this.baseState = State.Text
  237. this.inRCDATA = false
  238. this.currentSequence = undefined!
  239. this.newlines.length = 0
  240. this.delimiterOpen = defaultDelimitersOpen
  241. this.delimiterClose = defaultDelimitersClose
  242. }
  243. /**
  244. * Generate Position object with line / column information using recorded
  245. * newline positions. We know the index is always going to be an already
  246. * processed index, so all the newlines up to this index should have been
  247. * recorded.
  248. */
  249. public getPos(index: number): Position {
  250. let line = 1
  251. let column = index + 1
  252. for (let i = this.newlines.length - 1; i >= 0; i--) {
  253. const newlineIndex = this.newlines[i]
  254. if (index > newlineIndex) {
  255. line = i + 2
  256. column = index - newlineIndex
  257. break
  258. }
  259. }
  260. return {
  261. column,
  262. line,
  263. offset: index
  264. }
  265. }
  266. private peek() {
  267. return this.buffer.charCodeAt(this.index + 1)
  268. }
  269. private stateText(c: number): void {
  270. if (c === CharCodes.Lt) {
  271. if (this.index > this.sectionStart) {
  272. this.cbs.ontext(this.sectionStart, this.index)
  273. }
  274. this.state = State.BeforeTagName
  275. this.sectionStart = this.index
  276. } else if (!__BROWSER__ && c === CharCodes.Amp) {
  277. this.startEntity()
  278. } else if (c === this.delimiterOpen[0]) {
  279. this.state = State.InterpolationOpen
  280. this.delimiterIndex = 0
  281. this.stateInterpolationOpen(c)
  282. }
  283. }
  284. public delimiterOpen: Uint8Array = defaultDelimitersOpen
  285. public delimiterClose: Uint8Array = defaultDelimitersClose
  286. private delimiterIndex = -1
  287. private stateInterpolationOpen(c: number): void {
  288. if (c === this.delimiterOpen[this.delimiterIndex]) {
  289. if (this.delimiterIndex === this.delimiterOpen.length - 1) {
  290. const start = this.index + 1 - this.delimiterOpen.length
  291. if (start > this.sectionStart) {
  292. this.cbs.ontext(this.sectionStart, start)
  293. }
  294. this.state = State.Interpolation
  295. this.sectionStart = start
  296. } else {
  297. this.delimiterIndex++
  298. }
  299. } else if (this.inRCDATA) {
  300. this.state = State.InRCDATA
  301. this.stateInRCDATA(c)
  302. } else {
  303. this.state = State.Text
  304. this.stateText(c)
  305. }
  306. }
  307. private stateInterpolation(c: number): void {
  308. if (c === this.delimiterClose[0]) {
  309. this.state = State.InterpolationClose
  310. this.delimiterIndex = 0
  311. this.stateInterpolationClose(c)
  312. }
  313. }
  314. private stateInterpolationClose(c: number) {
  315. if (c === this.delimiterClose[this.delimiterIndex]) {
  316. if (this.delimiterIndex === this.delimiterClose.length - 1) {
  317. this.cbs.oninterpolation(this.sectionStart, this.index + 1)
  318. if (this.inRCDATA) {
  319. this.state = State.InRCDATA
  320. } else {
  321. this.state = State.Text
  322. }
  323. this.sectionStart = this.index + 1
  324. } else {
  325. this.delimiterIndex++
  326. }
  327. } else {
  328. this.state = State.Interpolation
  329. this.stateInterpolation(c)
  330. }
  331. }
  332. public currentSequence: Uint8Array = undefined!
  333. private sequenceIndex = 0
  334. private stateSpecialStartSequence(c: number): void {
  335. const isEnd = this.sequenceIndex === this.currentSequence.length
  336. const isMatch = isEnd
  337. ? // If we are at the end of the sequence, make sure the tag name has ended
  338. isEndOfTagSection(c)
  339. : // Otherwise, do a case-insensitive comparison
  340. (c | 0x20) === this.currentSequence[this.sequenceIndex]
  341. if (!isMatch) {
  342. this.inRCDATA = false
  343. } else if (!isEnd) {
  344. this.sequenceIndex++
  345. return
  346. }
  347. this.sequenceIndex = 0
  348. this.state = State.InTagName
  349. this.stateInTagName(c)
  350. }
  351. /** Look for an end tag. For <title> and <textarea>, also decode entities. */
  352. private stateInRCDATA(c: number): void {
  353. if (this.sequenceIndex === this.currentSequence.length) {
  354. if (c === CharCodes.Gt || isWhitespace(c)) {
  355. const endOfText = this.index - this.currentSequence.length
  356. if (this.sectionStart < endOfText) {
  357. // Spoof the index so that reported locations match up.
  358. const actualIndex = this.index
  359. this.index = endOfText
  360. this.cbs.ontext(this.sectionStart, endOfText)
  361. this.index = actualIndex
  362. }
  363. this.sectionStart = endOfText + 2 // Skip over the `</`
  364. this.stateInClosingTagName(c)
  365. this.inRCDATA = false
  366. return // We are done; skip the rest of the function.
  367. }
  368. this.sequenceIndex = 0
  369. }
  370. if ((c | 0x20) === this.currentSequence[this.sequenceIndex]) {
  371. this.sequenceIndex += 1
  372. } else if (this.sequenceIndex === 0) {
  373. if (
  374. this.currentSequence === Sequences.TitleEnd ||
  375. (this.currentSequence === Sequences.TextareaEnd && !this.inSFCRoot)
  376. ) {
  377. // We have to parse entities in <title> and <textarea> tags.
  378. if (!__BROWSER__ && c === CharCodes.Amp) {
  379. this.startEntity()
  380. } else if (c === this.delimiterOpen[0]) {
  381. // We also need to handle interpolation
  382. this.state = State.InterpolationOpen
  383. this.delimiterIndex = 0
  384. this.stateInterpolationOpen(c)
  385. }
  386. } else if (this.fastForwardTo(CharCodes.Lt)) {
  387. // Outside of <title> and <textarea> tags, we can fast-forward.
  388. this.sequenceIndex = 1
  389. }
  390. } else {
  391. // If we see a `<`, set the sequence index to 1; useful for eg. `<</script>`.
  392. this.sequenceIndex = Number(c === CharCodes.Lt)
  393. }
  394. }
  395. private stateCDATASequence(c: number): void {
  396. if (c === Sequences.Cdata[this.sequenceIndex]) {
  397. if (++this.sequenceIndex === Sequences.Cdata.length) {
  398. this.state = State.InCommentLike
  399. this.currentSequence = Sequences.CdataEnd
  400. this.sequenceIndex = 0
  401. this.sectionStart = this.index + 1
  402. }
  403. } else {
  404. this.sequenceIndex = 0
  405. this.state = State.InDeclaration
  406. this.stateInDeclaration(c) // Reconsume the character
  407. }
  408. }
  409. /**
  410. * When we wait for one specific character, we can speed things up
  411. * by skipping through the buffer until we find it.
  412. *
  413. * @returns Whether the character was found.
  414. */
  415. private fastForwardTo(c: number): boolean {
  416. while (++this.index < this.buffer.length) {
  417. const cc = this.buffer.charCodeAt(this.index)
  418. if (cc === CharCodes.NewLine) {
  419. this.newlines.push(this.index)
  420. }
  421. if (cc === c) {
  422. return true
  423. }
  424. }
  425. /*
  426. * We increment the index at the end of the `parse` loop,
  427. * so set it to `buffer.length - 1` here.
  428. *
  429. * TODO: Refactor `parse` to increment index before calling states.
  430. */
  431. this.index = this.buffer.length - 1
  432. return false
  433. }
  434. /**
  435. * Comments and CDATA end with `-->` and `]]>`.
  436. *
  437. * Their common qualities are:
  438. * - Their end sequences have a distinct character they start with.
  439. * - That character is then repeated, so we have to check multiple repeats.
  440. * - All characters but the start character of the sequence can be skipped.
  441. */
  442. private stateInCommentLike(c: number): void {
  443. if (c === this.currentSequence[this.sequenceIndex]) {
  444. if (++this.sequenceIndex === this.currentSequence.length) {
  445. if (this.currentSequence === Sequences.CdataEnd) {
  446. this.cbs.oncdata(this.sectionStart, this.index - 2)
  447. } else {
  448. this.cbs.oncomment(this.sectionStart, this.index - 2)
  449. }
  450. this.sequenceIndex = 0
  451. this.sectionStart = this.index + 1
  452. this.state = State.Text
  453. }
  454. } else if (this.sequenceIndex === 0) {
  455. // Fast-forward to the first character of the sequence
  456. if (this.fastForwardTo(this.currentSequence[0])) {
  457. this.sequenceIndex = 1
  458. }
  459. } else if (c !== this.currentSequence[this.sequenceIndex - 1]) {
  460. // Allow long sequences, eg. --->, ]]]>
  461. this.sequenceIndex = 0
  462. }
  463. }
  464. private startSpecial(sequence: Uint8Array, offset: number) {
  465. this.enterRCDATA(sequence, offset)
  466. this.state = State.SpecialStartSequence
  467. }
  468. public enterRCDATA(sequence: Uint8Array, offset: number) {
  469. this.inRCDATA = true
  470. this.currentSequence = sequence
  471. this.sequenceIndex = offset
  472. }
  473. private stateBeforeTagName(c: number): void {
  474. if (c === CharCodes.ExclamationMark) {
  475. this.state = State.BeforeDeclaration
  476. this.sectionStart = this.index + 1
  477. } else if (c === CharCodes.Questionmark) {
  478. this.state = State.InProcessingInstruction
  479. this.sectionStart = this.index + 1
  480. } else if (isTagStartChar(c)) {
  481. this.sectionStart = this.index
  482. if (this.mode === ParseMode.BASE) {
  483. // no special tags in base mode
  484. this.state = State.InTagName
  485. } else if (this.inSFCRoot) {
  486. // SFC mode + root level
  487. // - everything except <template> is RAWTEXT
  488. // - <template> with lang other than html is also RAWTEXT
  489. this.state = State.InSFCRootTagName
  490. } else if (!this.inXML) {
  491. // HTML mode
  492. // - <script>, <style> RAWTEXT
  493. // - <title>, <textarea> RCDATA
  494. const lower = c | 0x20
  495. if (lower === 116 /* t */) {
  496. this.state = State.BeforeSpecialT
  497. } else {
  498. this.state =
  499. lower === 115 /* s */ ? State.BeforeSpecialS : State.InTagName
  500. }
  501. } else {
  502. this.state = State.InTagName
  503. }
  504. } else if (c === CharCodes.Slash) {
  505. this.state = State.BeforeClosingTagName
  506. } else {
  507. this.state = State.Text
  508. this.stateText(c)
  509. }
  510. }
  511. private stateInTagName(c: number): void {
  512. if (isEndOfTagSection(c)) {
  513. this.handleTagName(c)
  514. }
  515. }
  516. private stateInSFCRootTagName(c: number): void {
  517. if (isEndOfTagSection(c)) {
  518. const tag = this.buffer.slice(this.sectionStart, this.index)
  519. if (tag !== 'template') {
  520. this.enterRCDATA(toCharCodes(`</` + tag), 0)
  521. }
  522. this.handleTagName(c)
  523. }
  524. }
  525. private handleTagName(c: number) {
  526. this.cbs.onopentagname(this.sectionStart, this.index)
  527. this.sectionStart = -1
  528. this.state = State.BeforeAttrName
  529. this.stateBeforeAttrName(c)
  530. }
  531. private stateBeforeClosingTagName(c: number): void {
  532. if (isWhitespace(c)) {
  533. // Ignore
  534. } else if (c === CharCodes.Gt) {
  535. if (__DEV__ || !__BROWSER__) {
  536. this.cbs.onerr(ErrorCodes.MISSING_END_TAG_NAME, this.index)
  537. }
  538. this.state = State.Text
  539. // Ignore
  540. this.sectionStart = this.index + 1
  541. } else {
  542. this.state = isTagStartChar(c)
  543. ? State.InClosingTagName
  544. : State.InSpecialComment
  545. this.sectionStart = this.index
  546. }
  547. }
  548. private stateInClosingTagName(c: number): void {
  549. if (c === CharCodes.Gt || isWhitespace(c)) {
  550. this.cbs.onclosetag(this.sectionStart, this.index)
  551. this.sectionStart = -1
  552. this.state = State.AfterClosingTagName
  553. this.stateAfterClosingTagName(c)
  554. }
  555. }
  556. private stateAfterClosingTagName(c: number): void {
  557. // Skip everything until ">"
  558. if (c === CharCodes.Gt) {
  559. this.state = State.Text
  560. this.sectionStart = this.index + 1
  561. }
  562. }
  563. private stateBeforeAttrName(c: number): void {
  564. if (c === CharCodes.Gt) {
  565. this.cbs.onopentagend(this.index)
  566. if (this.inRCDATA) {
  567. this.state = State.InRCDATA
  568. } else {
  569. this.state = State.Text
  570. }
  571. this.sectionStart = this.index + 1
  572. } else if (c === CharCodes.Slash) {
  573. this.state = State.InSelfClosingTag
  574. if ((__DEV__ || !__BROWSER__) && this.peek() !== CharCodes.Gt) {
  575. this.cbs.onerr(ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG, this.index)
  576. }
  577. } else if (c === CharCodes.Lt && this.peek() === CharCodes.Slash) {
  578. // special handling for </ appearing in open tag state
  579. // this is different from standard HTML parsing but makes practical sense
  580. // especially for parsing intermediate input state in IDEs.
  581. this.cbs.onopentagend(this.index)
  582. this.state = State.BeforeTagName
  583. this.sectionStart = this.index
  584. } else if (!isWhitespace(c)) {
  585. if ((__DEV__ || !__BROWSER__) && c === CharCodes.Eq) {
  586. this.cbs.onerr(
  587. ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME,
  588. this.index
  589. )
  590. }
  591. this.handleAttrStart(c)
  592. }
  593. }
  594. private handleAttrStart(c: number) {
  595. if (c === CharCodes.LowerV && this.peek() === CharCodes.Dash) {
  596. this.state = State.InDirName
  597. this.sectionStart = this.index
  598. } else if (
  599. c === CharCodes.Dot ||
  600. c === CharCodes.Colon ||
  601. c === CharCodes.At ||
  602. c === CharCodes.Number
  603. ) {
  604. this.cbs.ondirname(this.index, this.index + 1)
  605. this.state = State.InDirArg
  606. this.sectionStart = this.index + 1
  607. } else {
  608. this.state = State.InAttrName
  609. this.sectionStart = this.index
  610. }
  611. }
  612. private stateInSelfClosingTag(c: number): void {
  613. if (c === CharCodes.Gt) {
  614. this.cbs.onselfclosingtag(this.index)
  615. this.state = State.Text
  616. this.sectionStart = this.index + 1
  617. this.inRCDATA = false // Reset special state, in case of self-closing special tags
  618. } else if (!isWhitespace(c)) {
  619. this.state = State.BeforeAttrName
  620. this.stateBeforeAttrName(c)
  621. }
  622. }
  623. private stateInAttrName(c: number): void {
  624. if (c === CharCodes.Eq || isEndOfTagSection(c)) {
  625. this.cbs.onattribname(this.sectionStart, this.index)
  626. this.handleAttrNameEnd(c)
  627. } else if (
  628. (__DEV__ || !__BROWSER__) &&
  629. (c === CharCodes.DoubleQuote ||
  630. c === CharCodes.SingleQuote ||
  631. c === CharCodes.Lt)
  632. ) {
  633. this.cbs.onerr(
  634. ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME,
  635. this.index
  636. )
  637. }
  638. }
  639. private stateInDirName(c: number): void {
  640. if (c === CharCodes.Eq || isEndOfTagSection(c)) {
  641. this.cbs.ondirname(this.sectionStart, this.index)
  642. this.handleAttrNameEnd(c)
  643. } else if (c === CharCodes.Colon) {
  644. this.cbs.ondirname(this.sectionStart, this.index)
  645. this.state = State.InDirArg
  646. this.sectionStart = this.index + 1
  647. } else if (c === CharCodes.Dot) {
  648. this.cbs.ondirname(this.sectionStart, this.index)
  649. this.state = State.InDirModifier
  650. this.sectionStart = this.index + 1
  651. }
  652. }
  653. private stateInDirArg(c: number): void {
  654. if (c === CharCodes.Eq || isEndOfTagSection(c)) {
  655. this.cbs.ondirarg(this.sectionStart, this.index)
  656. this.handleAttrNameEnd(c)
  657. } else if (c === CharCodes.LeftSquare) {
  658. this.state = State.InDirDynamicArg
  659. } else if (c === CharCodes.Dot) {
  660. this.cbs.ondirarg(this.sectionStart, this.index)
  661. this.state = State.InDirModifier
  662. this.sectionStart = this.index + 1
  663. }
  664. }
  665. private stateInDynamicDirArg(c: number): void {
  666. if (c === CharCodes.RightSquare) {
  667. this.state = State.InDirArg
  668. } else if (c === CharCodes.Eq || isEndOfTagSection(c)) {
  669. this.cbs.ondirarg(this.sectionStart, this.index + 1)
  670. this.handleAttrNameEnd(c)
  671. if (__DEV__ || !__BROWSER__) {
  672. this.cbs.onerr(
  673. ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END,
  674. this.index
  675. )
  676. }
  677. }
  678. }
  679. private stateInDirModifier(c: number): void {
  680. if (c === CharCodes.Eq || isEndOfTagSection(c)) {
  681. this.cbs.ondirmodifier(this.sectionStart, this.index)
  682. this.handleAttrNameEnd(c)
  683. } else if (c === CharCodes.Dot) {
  684. this.cbs.ondirmodifier(this.sectionStart, this.index)
  685. this.sectionStart = this.index + 1
  686. }
  687. }
  688. private handleAttrNameEnd(c: number): void {
  689. this.sectionStart = this.index
  690. this.state = State.AfterAttrName
  691. this.cbs.onattribnameend(this.index)
  692. this.stateAfterAttrName(c)
  693. }
  694. private stateAfterAttrName(c: number): void {
  695. if (c === CharCodes.Eq) {
  696. this.state = State.BeforeAttrValue
  697. } else if (c === CharCodes.Slash || c === CharCodes.Gt) {
  698. this.cbs.onattribend(QuoteType.NoValue, this.sectionStart)
  699. this.sectionStart = -1
  700. this.state = State.BeforeAttrName
  701. this.stateBeforeAttrName(c)
  702. } else if (!isWhitespace(c)) {
  703. this.cbs.onattribend(QuoteType.NoValue, this.sectionStart)
  704. this.handleAttrStart(c)
  705. }
  706. }
  707. private stateBeforeAttrValue(c: number): void {
  708. if (c === CharCodes.DoubleQuote) {
  709. this.state = State.InAttrValueDq
  710. this.sectionStart = this.index + 1
  711. } else if (c === CharCodes.SingleQuote) {
  712. this.state = State.InAttrValueSq
  713. this.sectionStart = this.index + 1
  714. } else if (!isWhitespace(c)) {
  715. this.sectionStart = this.index
  716. this.state = State.InAttrValueNq
  717. this.stateInAttrValueNoQuotes(c) // Reconsume token
  718. }
  719. }
  720. private handleInAttrValue(c: number, quote: number) {
  721. if (c === quote || (__BROWSER__ && this.fastForwardTo(quote))) {
  722. this.cbs.onattribdata(this.sectionStart, this.index)
  723. this.sectionStart = -1
  724. this.cbs.onattribend(
  725. quote === CharCodes.DoubleQuote ? QuoteType.Double : QuoteType.Single,
  726. this.index + 1
  727. )
  728. this.state = State.BeforeAttrName
  729. } else if (!__BROWSER__ && c === CharCodes.Amp) {
  730. this.startEntity()
  731. }
  732. }
  733. private stateInAttrValueDoubleQuotes(c: number): void {
  734. this.handleInAttrValue(c, CharCodes.DoubleQuote)
  735. }
  736. private stateInAttrValueSingleQuotes(c: number): void {
  737. this.handleInAttrValue(c, CharCodes.SingleQuote)
  738. }
  739. private stateInAttrValueNoQuotes(c: number): void {
  740. if (isWhitespace(c) || c === CharCodes.Gt) {
  741. this.cbs.onattribdata(this.sectionStart, this.index)
  742. this.sectionStart = -1
  743. this.cbs.onattribend(QuoteType.Unquoted, this.index)
  744. this.state = State.BeforeAttrName
  745. this.stateBeforeAttrName(c)
  746. } else if (
  747. ((__DEV__ || !__BROWSER__) && c === CharCodes.DoubleQuote) ||
  748. c === CharCodes.SingleQuote ||
  749. c === CharCodes.Lt ||
  750. c === CharCodes.Eq ||
  751. c === CharCodes.GraveAccent
  752. ) {
  753. this.cbs.onerr(
  754. ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE,
  755. this.index
  756. )
  757. } else if (!__BROWSER__ && c === CharCodes.Amp) {
  758. this.startEntity()
  759. }
  760. }
  761. private stateBeforeDeclaration(c: number): void {
  762. if (c === CharCodes.LeftSquare) {
  763. this.state = State.CDATASequence
  764. this.sequenceIndex = 0
  765. } else {
  766. this.state =
  767. c === CharCodes.Dash ? State.BeforeComment : State.InDeclaration
  768. }
  769. }
  770. private stateInDeclaration(c: number): void {
  771. if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
  772. // this.cbs.ondeclaration(this.sectionStart, this.index)
  773. this.state = State.Text
  774. this.sectionStart = this.index + 1
  775. }
  776. }
  777. private stateInProcessingInstruction(c: number): void {
  778. if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
  779. this.cbs.onprocessinginstruction(this.sectionStart, this.index)
  780. this.state = State.Text
  781. this.sectionStart = this.index + 1
  782. }
  783. }
  784. private stateBeforeComment(c: number): void {
  785. if (c === CharCodes.Dash) {
  786. this.state = State.InCommentLike
  787. this.currentSequence = Sequences.CommentEnd
  788. // Allow short comments (eg. <!-->)
  789. this.sequenceIndex = 2
  790. this.sectionStart = this.index + 1
  791. } else {
  792. this.state = State.InDeclaration
  793. }
  794. }
  795. private stateInSpecialComment(c: number): void {
  796. if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
  797. this.cbs.oncomment(this.sectionStart, this.index)
  798. this.state = State.Text
  799. this.sectionStart = this.index + 1
  800. }
  801. }
  802. private stateBeforeSpecialS(c: number): void {
  803. const lower = c | 0x20
  804. if (lower === Sequences.ScriptEnd[3]) {
  805. this.startSpecial(Sequences.ScriptEnd, 4)
  806. } else if (lower === Sequences.StyleEnd[3]) {
  807. this.startSpecial(Sequences.StyleEnd, 4)
  808. } else {
  809. this.state = State.InTagName
  810. this.stateInTagName(c) // Consume the token again
  811. }
  812. }
  813. private stateBeforeSpecialT(c: number): void {
  814. const lower = c | 0x20
  815. if (lower === Sequences.TitleEnd[3]) {
  816. this.startSpecial(Sequences.TitleEnd, 4)
  817. } else if (lower === Sequences.TextareaEnd[3]) {
  818. this.startSpecial(Sequences.TextareaEnd, 4)
  819. } else {
  820. this.state = State.InTagName
  821. this.stateInTagName(c) // Consume the token again
  822. }
  823. }
  824. private startEntity() {
  825. if (!__BROWSER__) {
  826. this.baseState = this.state
  827. this.state = State.InEntity
  828. this.entityStart = this.index
  829. this.entityDecoder!.startEntity(
  830. this.baseState === State.Text || this.baseState === State.InRCDATA
  831. ? DecodingMode.Legacy
  832. : DecodingMode.Attribute
  833. )
  834. }
  835. }
  836. private stateInEntity(): void {
  837. if (!__BROWSER__) {
  838. const length = this.entityDecoder!.write(this.buffer, this.index)
  839. // If `length` is positive, we are done with the entity.
  840. if (length >= 0) {
  841. this.state = this.baseState
  842. if (length === 0) {
  843. this.index = this.entityStart
  844. }
  845. } else {
  846. // Mark buffer as consumed.
  847. this.index = this.buffer.length - 1
  848. }
  849. }
  850. }
  851. /**
  852. * Iterates through the buffer, calling the function corresponding to the current state.
  853. *
  854. * States that are more likely to be hit are higher up, as a performance improvement.
  855. */
  856. public parse(input: string) {
  857. this.buffer = input
  858. while (this.index < this.buffer.length) {
  859. const c = this.buffer.charCodeAt(this.index)
  860. if (c === CharCodes.NewLine) {
  861. this.newlines.push(this.index)
  862. }
  863. switch (this.state) {
  864. case State.Text: {
  865. this.stateText(c)
  866. break
  867. }
  868. case State.InterpolationOpen: {
  869. this.stateInterpolationOpen(c)
  870. break
  871. }
  872. case State.Interpolation: {
  873. this.stateInterpolation(c)
  874. break
  875. }
  876. case State.InterpolationClose: {
  877. this.stateInterpolationClose(c)
  878. break
  879. }
  880. case State.SpecialStartSequence: {
  881. this.stateSpecialStartSequence(c)
  882. break
  883. }
  884. case State.InRCDATA: {
  885. this.stateInRCDATA(c)
  886. break
  887. }
  888. case State.CDATASequence: {
  889. this.stateCDATASequence(c)
  890. break
  891. }
  892. case State.InAttrValueDq: {
  893. this.stateInAttrValueDoubleQuotes(c)
  894. break
  895. }
  896. case State.InAttrName: {
  897. this.stateInAttrName(c)
  898. break
  899. }
  900. case State.InDirName: {
  901. this.stateInDirName(c)
  902. break
  903. }
  904. case State.InDirArg: {
  905. this.stateInDirArg(c)
  906. break
  907. }
  908. case State.InDirDynamicArg: {
  909. this.stateInDynamicDirArg(c)
  910. break
  911. }
  912. case State.InDirModifier: {
  913. this.stateInDirModifier(c)
  914. break
  915. }
  916. case State.InCommentLike: {
  917. this.stateInCommentLike(c)
  918. break
  919. }
  920. case State.InSpecialComment: {
  921. this.stateInSpecialComment(c)
  922. break
  923. }
  924. case State.BeforeAttrName: {
  925. this.stateBeforeAttrName(c)
  926. break
  927. }
  928. case State.InTagName: {
  929. this.stateInTagName(c)
  930. break
  931. }
  932. case State.InSFCRootTagName: {
  933. this.stateInSFCRootTagName(c)
  934. break
  935. }
  936. case State.InClosingTagName: {
  937. this.stateInClosingTagName(c)
  938. break
  939. }
  940. case State.BeforeTagName: {
  941. this.stateBeforeTagName(c)
  942. break
  943. }
  944. case State.AfterAttrName: {
  945. this.stateAfterAttrName(c)
  946. break
  947. }
  948. case State.InAttrValueSq: {
  949. this.stateInAttrValueSingleQuotes(c)
  950. break
  951. }
  952. case State.BeforeAttrValue: {
  953. this.stateBeforeAttrValue(c)
  954. break
  955. }
  956. case State.BeforeClosingTagName: {
  957. this.stateBeforeClosingTagName(c)
  958. break
  959. }
  960. case State.AfterClosingTagName: {
  961. this.stateAfterClosingTagName(c)
  962. break
  963. }
  964. case State.BeforeSpecialS: {
  965. this.stateBeforeSpecialS(c)
  966. break
  967. }
  968. case State.BeforeSpecialT: {
  969. this.stateBeforeSpecialT(c)
  970. break
  971. }
  972. case State.InAttrValueNq: {
  973. this.stateInAttrValueNoQuotes(c)
  974. break
  975. }
  976. case State.InSelfClosingTag: {
  977. this.stateInSelfClosingTag(c)
  978. break
  979. }
  980. case State.InDeclaration: {
  981. this.stateInDeclaration(c)
  982. break
  983. }
  984. case State.BeforeDeclaration: {
  985. this.stateBeforeDeclaration(c)
  986. break
  987. }
  988. case State.BeforeComment: {
  989. this.stateBeforeComment(c)
  990. break
  991. }
  992. case State.InProcessingInstruction: {
  993. this.stateInProcessingInstruction(c)
  994. break
  995. }
  996. case State.InEntity: {
  997. this.stateInEntity()
  998. break
  999. }
  1000. }
  1001. this.index++
  1002. }
  1003. this.cleanup()
  1004. this.finish()
  1005. }
  1006. /**
  1007. * Remove data that has already been consumed from the buffer.
  1008. */
  1009. private cleanup() {
  1010. // If we are inside of text or attributes, emit what we already have.
  1011. if (this.sectionStart !== this.index) {
  1012. if (
  1013. this.state === State.Text ||
  1014. (this.state === State.InRCDATA && this.sequenceIndex === 0)
  1015. ) {
  1016. this.cbs.ontext(this.sectionStart, this.index)
  1017. this.sectionStart = this.index
  1018. } else if (
  1019. this.state === State.InAttrValueDq ||
  1020. this.state === State.InAttrValueSq ||
  1021. this.state === State.InAttrValueNq
  1022. ) {
  1023. this.cbs.onattribdata(this.sectionStart, this.index)
  1024. this.sectionStart = this.index
  1025. }
  1026. }
  1027. }
  1028. private finish() {
  1029. if (!__BROWSER__ && this.state === State.InEntity) {
  1030. this.entityDecoder!.end()
  1031. this.state = this.baseState
  1032. }
  1033. this.handleTrailingData()
  1034. this.cbs.onend()
  1035. }
  1036. /** Handle any trailing data. */
  1037. private handleTrailingData() {
  1038. const endIndex = this.buffer.length
  1039. // If there is no remaining data, we are done.
  1040. if (this.sectionStart >= endIndex) {
  1041. return
  1042. }
  1043. if (this.state === State.InCommentLike) {
  1044. if (this.currentSequence === Sequences.CdataEnd) {
  1045. this.cbs.oncdata(this.sectionStart, endIndex)
  1046. } else {
  1047. this.cbs.oncomment(this.sectionStart, endIndex)
  1048. }
  1049. } else if (
  1050. this.state === State.InTagName ||
  1051. this.state === State.BeforeAttrName ||
  1052. this.state === State.BeforeAttrValue ||
  1053. this.state === State.AfterAttrName ||
  1054. this.state === State.InAttrName ||
  1055. this.state === State.InDirName ||
  1056. this.state === State.InDirArg ||
  1057. this.state === State.InDirDynamicArg ||
  1058. this.state === State.InDirModifier ||
  1059. this.state === State.InAttrValueSq ||
  1060. this.state === State.InAttrValueDq ||
  1061. this.state === State.InAttrValueNq ||
  1062. this.state === State.InClosingTagName
  1063. ) {
  1064. /*
  1065. * If we are currently in an opening or closing tag, us not calling the
  1066. * respective callback signals that the tag should be ignored.
  1067. */
  1068. } else {
  1069. this.cbs.ontext(this.sectionStart, endIndex)
  1070. }
  1071. }
  1072. private emitCodePoint(cp: number, consumed: number): void {
  1073. if (!__BROWSER__) {
  1074. if (this.baseState !== State.Text && this.baseState !== State.InRCDATA) {
  1075. if (this.sectionStart < this.entityStart) {
  1076. this.cbs.onattribdata(this.sectionStart, this.entityStart)
  1077. }
  1078. this.sectionStart = this.entityStart + consumed
  1079. this.index = this.sectionStart - 1
  1080. this.cbs.onattribentity(
  1081. fromCodePoint(cp),
  1082. this.entityStart,
  1083. this.sectionStart
  1084. )
  1085. } else {
  1086. if (this.sectionStart < this.entityStart) {
  1087. this.cbs.ontext(this.sectionStart, this.entityStart)
  1088. }
  1089. this.sectionStart = this.entityStart + consumed
  1090. this.index = this.sectionStart - 1
  1091. this.cbs.ontextentity(
  1092. fromCodePoint(cp),
  1093. this.entityStart,
  1094. this.sectionStart
  1095. )
  1096. }
  1097. }
  1098. }
  1099. }