syntax.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. /**
  2. * @typedef {import('micromark-util-types').Extension} Extension
  3. * @typedef {import('micromark-util-types').Resolver} Resolver
  4. * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
  5. * @typedef {import('micromark-util-types').State} State
  6. * @typedef {import('micromark-util-types').Token} Token
  7. */
  8. /**
  9. * @typedef {'left'|'center'|'right'|'none'} Align
  10. */
  11. import { factorySpace } from 'micromark-factory-space';
  12. import {
  13. markdownLineEnding,
  14. markdownLineEndingOrSpace,
  15. markdownSpace,
  16. } from 'micromark-util-character';
  17. import { codes } from 'micromark-util-symbol/codes.js';
  18. import { constants } from 'micromark-util-symbol/constants.js';
  19. import { types } from 'micromark-util-symbol/types.js';
  20. import { ok as assert } from 'uvu/assert';
  21. /**
  22. * Syntax extension for micromark (passed in `extensions`).
  23. *
  24. * @type {Extension}
  25. */
  26. export const gfmTable = {
  27. flow: { null: { tokenize: tokenizeTable, resolve: resolveTable } },
  28. };
  29. const nextPrefixedOrBlank = {
  30. tokenize: tokenizeNextPrefixedOrBlank,
  31. partial: true,
  32. };
  33. /** @type {Resolver} */
  34. // eslint-disable-next-line complexity
  35. function resolveTable(events, context) {
  36. let index = -1;
  37. /** @type {boolean|undefined} */
  38. let inHead;
  39. /** @type {boolean|undefined} */
  40. let inDelimiterRow;
  41. /** @type {boolean|undefined} */
  42. let inRow;
  43. /** @type {number|undefined} */
  44. let contentStart;
  45. /** @type {number|undefined} */
  46. let contentEnd;
  47. /** @type {number|undefined} */
  48. let cellStart;
  49. /** @type {boolean|undefined} */
  50. let seenCellInRow;
  51. while (++index < events.length) {
  52. const token = events[index][1];
  53. if (inRow) {
  54. if (token.type === 'temporaryTableCellContent') {
  55. contentStart = contentStart || index;
  56. contentEnd = index;
  57. }
  58. if (
  59. // Combine separate content parts into one.
  60. (token.type === 'tableCellDivider' || token.type === 'tableRow')
  61. && contentEnd
  62. ) {
  63. assert(
  64. contentStart,
  65. 'expected `contentStart` to be defined if `contentEnd` is',
  66. );
  67. const content = {
  68. type: 'tableContent',
  69. start: events[contentStart][1].start,
  70. end: events[contentEnd][1].end,
  71. };
  72. /** @type {Token} */
  73. const text = {
  74. type: types.chunkText,
  75. start: content.start,
  76. end: content.end,
  77. // @ts-expect-error It’s fine.
  78. contentType: constants.contentTypeText,
  79. };
  80. assert(
  81. contentStart,
  82. 'expected `contentStart` to be defined if `contentEnd` is',
  83. );
  84. events.splice(
  85. contentStart,
  86. contentEnd - contentStart + 1,
  87. ['enter', content, context],
  88. ['enter', text, context],
  89. ['exit', text, context],
  90. ['exit', content, context],
  91. );
  92. index -= contentEnd - contentStart - 3;
  93. contentStart = undefined;
  94. contentEnd = undefined;
  95. }
  96. }
  97. if (
  98. events[index][0] === 'exit'
  99. && cellStart !== undefined
  100. && cellStart + (seenCellInRow ? 0 : 1) < index
  101. && (token.type === 'tableCellDivider'
  102. || (token.type === 'tableRow'
  103. && (cellStart + 3 < index
  104. || events[cellStart][1].type !== types.whitespace)))
  105. ) {
  106. const cell = {
  107. // eslint-disable-next-line no-nested-ternary
  108. type: inDelimiterRow
  109. ? 'tableDelimiter'
  110. : inHead
  111. ? 'tableHeader'
  112. : 'tableData',
  113. start: events[cellStart][1].start,
  114. end: events[index][1].end,
  115. };
  116. events.splice(index + (token.type === 'tableCellDivider' ? 1 : 0), 0, [
  117. 'exit',
  118. cell,
  119. context,
  120. ]);
  121. events.splice(cellStart, 0, ['enter', cell, context]);
  122. index += 2;
  123. cellStart = index + 1;
  124. seenCellInRow = true;
  125. }
  126. if (token.type === 'tableRow') {
  127. inRow = events[index][0] === 'enter';
  128. if (inRow) {
  129. cellStart = index + 1;
  130. seenCellInRow = false;
  131. }
  132. }
  133. if (token.type === 'tableDelimiterRow') {
  134. inDelimiterRow = events[index][0] === 'enter';
  135. if (inDelimiterRow) {
  136. cellStart = index + 1;
  137. seenCellInRow = false;
  138. }
  139. }
  140. if (token.type === 'tableHead') {
  141. inHead = events[index][0] === 'enter';
  142. }
  143. }
  144. return events;
  145. }
  146. /** @type {Tokenizer} */
  147. function tokenizeTable(effects, ok, nok) {
  148. // eslint-disable-next-line @typescript-eslint/no-this-alias
  149. const self = this;
  150. /** @type {Array<Align>} */
  151. const align = [];
  152. let tableHeaderCount = 0;
  153. /** @type {boolean|undefined} */
  154. let seenDelimiter;
  155. /** @type {boolean|undefined} */
  156. let hasDash;
  157. return start;
  158. /** @type {State} */
  159. function start(code) {
  160. // @ts-expect-error Custom.
  161. effects.enter('table')._align = align;
  162. effects.enter('tableHead');
  163. effects.enter('tableRow');
  164. // If we start with a pipe, we open a cell marker.
  165. if (code === codes.verticalBar) {
  166. return cellDividerHead(code);
  167. }
  168. tableHeaderCount++;
  169. effects.enter('temporaryTableCellContent');
  170. // Can’t be space or eols at the start of a construct, so we’re in a cell.
  171. assert(!markdownLineEndingOrSpace(code), 'expected non-space');
  172. return inCellContentHead(code);
  173. }
  174. /** @type {State} */
  175. function cellDividerHead(code) {
  176. assert(code === codes.verticalBar, 'expected `|`');
  177. effects.enter('tableCellDivider');
  178. effects.consume(code);
  179. effects.exit('tableCellDivider');
  180. seenDelimiter = true;
  181. return cellBreakHead;
  182. }
  183. /** @type {State} */
  184. function cellBreakHead(code) {
  185. if (code === codes.eof || markdownLineEnding(code)) {
  186. return atRowEndHead(code);
  187. }
  188. if (markdownSpace(code)) {
  189. effects.enter(types.whitespace);
  190. effects.consume(code);
  191. return inWhitespaceHead;
  192. }
  193. if (seenDelimiter) {
  194. seenDelimiter = undefined;
  195. tableHeaderCount++;
  196. }
  197. if (code === codes.verticalBar) {
  198. return cellDividerHead(code);
  199. }
  200. // Anything else is cell content.
  201. effects.enter('temporaryTableCellContent');
  202. return inCellContentHead(code);
  203. }
  204. /** @type {State} */
  205. function inWhitespaceHead(code) {
  206. if (markdownSpace(code)) {
  207. effects.consume(code);
  208. return inWhitespaceHead;
  209. }
  210. effects.exit(types.whitespace);
  211. return cellBreakHead(code);
  212. }
  213. /** @type {State} */
  214. function inCellContentHead(code) {
  215. // EOF, whitespace, pipe
  216. if (
  217. code === codes.eof
  218. || code === codes.verticalBar
  219. || markdownLineEndingOrSpace(code)
  220. ) {
  221. effects.exit('temporaryTableCellContent');
  222. return cellBreakHead(code);
  223. }
  224. effects.consume(code);
  225. console.log('[consume in Head]', String.fromCharCode(code));
  226. return code === codes.backslash
  227. ? inCellContentEscapeHead
  228. : inCellContentHead;
  229. }
  230. /** @type {State} */
  231. function inCellContentEscapeHead(code) {
  232. if (code === codes.backslash || code === codes.verticalBar) {
  233. effects.consume(code);
  234. return inCellContentHead;
  235. }
  236. // Anything else.
  237. return inCellContentHead(code);
  238. }
  239. /** @type {State} */
  240. function atRowEndHead(code) {
  241. let rowEndCount = self.containerState.rowEndCount ?? 0;
  242. rowEndCount++;
  243. self.containerState.rowEndCount = rowEndCount;
  244. console.log({ method: 'atRowEndHead', rowEndCount });
  245. if (code === codes.eof) {
  246. return nok(code);
  247. }
  248. assert(markdownLineEnding(code), 'expected eol');
  249. effects.exit('tableRow');
  250. effects.exit('tableHead');
  251. const originalInterrupt = self.interrupt;
  252. self.interrupt = true;
  253. return effects.attempt(
  254. { tokenize: tokenizeRowEnd, partial: true },
  255. (code) => {
  256. self.interrupt = originalInterrupt;
  257. effects.enter('tableDelimiterRow');
  258. return atDelimiterRowBreak(code);
  259. },
  260. (code) => {
  261. self.interrupt = originalInterrupt;
  262. return nok(code);
  263. },
  264. )(code);
  265. }
  266. /** @type {State} */
  267. function atDelimiterRowBreak(code) {
  268. if (code === codes.eof || markdownLineEnding(code)) {
  269. return rowEndDelimiter(code);
  270. }
  271. if (markdownSpace(code)) {
  272. effects.enter(types.whitespace);
  273. effects.consume(code);
  274. return inWhitespaceDelimiter;
  275. }
  276. if (code === codes.dash) {
  277. effects.enter('tableDelimiterFiller');
  278. effects.consume(code);
  279. hasDash = true;
  280. align.push('none');
  281. return inFillerDelimiter;
  282. }
  283. if (code === codes.colon) {
  284. effects.enter('tableDelimiterAlignment');
  285. effects.consume(code);
  286. effects.exit('tableDelimiterAlignment');
  287. align.push('left');
  288. return afterLeftAlignment;
  289. }
  290. // If we start with a pipe, we open a cell marker.
  291. if (code === codes.verticalBar) {
  292. effects.enter('tableCellDivider');
  293. effects.consume(code);
  294. effects.exit('tableCellDivider');
  295. return atDelimiterRowBreak;
  296. }
  297. return nok(code);
  298. }
  299. /** @type {State} */
  300. function inWhitespaceDelimiter(code) {
  301. if (markdownSpace(code)) {
  302. effects.consume(code);
  303. return inWhitespaceDelimiter;
  304. }
  305. effects.exit(types.whitespace);
  306. return atDelimiterRowBreak(code);
  307. }
  308. /** @type {State} */
  309. function inFillerDelimiter(code) {
  310. if (code === codes.dash) {
  311. effects.consume(code);
  312. return inFillerDelimiter;
  313. }
  314. effects.exit('tableDelimiterFiller');
  315. if (code === codes.colon) {
  316. effects.enter('tableDelimiterAlignment');
  317. effects.consume(code);
  318. effects.exit('tableDelimiterAlignment');
  319. align[align.length - 1] = align[align.length - 1] === 'left' ? 'center' : 'right';
  320. return afterRightAlignment;
  321. }
  322. return atDelimiterRowBreak(code);
  323. }
  324. /** @type {State} */
  325. function afterLeftAlignment(code) {
  326. if (code === codes.dash) {
  327. effects.enter('tableDelimiterFiller');
  328. effects.consume(code);
  329. hasDash = true;
  330. return inFillerDelimiter;
  331. }
  332. // Anything else is not ok.
  333. return nok(code);
  334. }
  335. /** @type {State} */
  336. function afterRightAlignment(code) {
  337. if (code === codes.eof || markdownLineEnding(code)) {
  338. return rowEndDelimiter(code);
  339. }
  340. if (markdownSpace(code)) {
  341. effects.enter(types.whitespace);
  342. effects.consume(code);
  343. return inWhitespaceDelimiter;
  344. }
  345. // `|`
  346. if (code === codes.verticalBar) {
  347. effects.enter('tableCellDivider');
  348. effects.consume(code);
  349. effects.exit('tableCellDivider');
  350. return atDelimiterRowBreak;
  351. }
  352. return nok(code);
  353. }
  354. /** @type {State} */
  355. function rowEndDelimiter(code) {
  356. effects.exit('tableDelimiterRow');
  357. // Exit if there was no dash at all, or if the header cell count is not the
  358. // delimiter cell count.
  359. if (!hasDash || tableHeaderCount !== align.length) {
  360. return nok(code);
  361. }
  362. if (code === codes.eof) {
  363. return tableClose(code);
  364. }
  365. assert(markdownLineEnding(code), 'expected eol');
  366. return effects.check(
  367. nextPrefixedOrBlank,
  368. tableClose,
  369. effects.attempt(
  370. { tokenize: tokenizeRowEnd, partial: true },
  371. factorySpace(effects, bodyStart, types.linePrefix, constants.tabSize),
  372. tableClose,
  373. ),
  374. )(code);
  375. }
  376. /** @type {State} */
  377. function tableClose(code) {
  378. effects.exit('table');
  379. return ok(code);
  380. }
  381. /** @type {State} */
  382. function bodyStart(code) {
  383. effects.enter('tableBody');
  384. return rowStartBody(code);
  385. }
  386. /** @type {State} */
  387. function rowStartBody(code) {
  388. effects.enter('tableRow');
  389. // If we start with a pipe, we open a cell marker.
  390. if (code === codes.verticalBar) {
  391. return cellDividerBody(code);
  392. }
  393. effects.enter('temporaryTableCellContent');
  394. // Can’t be space or eols at the start of a construct, so we’re in a cell.
  395. return inCellContentBody(code);
  396. }
  397. /** @type {State} */
  398. function cellDividerBody(code) {
  399. assert(code === codes.verticalBar, 'expected `|`');
  400. effects.enter('tableCellDivider');
  401. effects.consume(code);
  402. effects.exit('tableCellDivider');
  403. return cellBreakBody;
  404. }
  405. /** @type {State} */
  406. function cellBreakBody(code) {
  407. if (code === codes.eof || markdownLineEnding(code)) {
  408. return atRowEndBody(code);
  409. }
  410. if (markdownSpace(code)) {
  411. effects.enter(types.whitespace);
  412. effects.consume(code);
  413. return inWhitespaceBody;
  414. }
  415. // `|`
  416. if (code === codes.verticalBar) {
  417. return cellDividerBody(code);
  418. }
  419. // Anything else is cell content.
  420. effects.enter('temporaryTableCellContent');
  421. return inCellContentBody(code);
  422. }
  423. /** @type {State} */
  424. function inWhitespaceBody(code) {
  425. if (markdownSpace(code)) {
  426. effects.consume(code);
  427. return inWhitespaceBody;
  428. }
  429. effects.exit(types.whitespace);
  430. return cellBreakBody(code);
  431. }
  432. /** @type {State} */
  433. function inCellContentBody(code) {
  434. // EOF, whitespace, pipe
  435. if (
  436. code === codes.eof
  437. || code === codes.verticalBar
  438. || markdownLineEndingOrSpace(code)
  439. ) {
  440. effects.exit('temporaryTableCellContent');
  441. return cellBreakBody(code);
  442. }
  443. effects.consume(code);
  444. console.log('[consume in Body]', String.fromCharCode(code));
  445. return code === codes.backslash
  446. ? inCellContentEscapeBody
  447. : inCellContentBody;
  448. }
  449. /** @type {State} */
  450. function inCellContentEscapeBody(code) {
  451. if (code === codes.backslash || code === codes.verticalBar) {
  452. effects.consume(code);
  453. return inCellContentBody;
  454. }
  455. // Anything else.
  456. return inCellContentBody(code);
  457. }
  458. /** @type {State} */
  459. function atRowEndBody(code) {
  460. let rowEndCount = self.containerState.rowEndCount ?? 0;
  461. rowEndCount++;
  462. self.containerState.rowEndCount = rowEndCount;
  463. console.log({ method: 'atRowEndBody', rowEndCount });
  464. effects.exit('tableRow');
  465. if (code === codes.eof) {
  466. return tableBodyClose(code);
  467. }
  468. return effects.check(
  469. nextPrefixedOrBlank,
  470. tableBodyClose,
  471. effects.attempt(
  472. { tokenize: tokenizeRowEnd, partial: true },
  473. factorySpace(
  474. effects,
  475. rowStartBody,
  476. types.linePrefix,
  477. constants.tabSize,
  478. ),
  479. tableBodyClose,
  480. ),
  481. )(code);
  482. }
  483. /** @type {State} */
  484. function tableBodyClose(code) {
  485. effects.exit('tableBody');
  486. return tableClose(code);
  487. }
  488. /** @type {Tokenizer} */
  489. function tokenizeRowEnd(effects, ok, nok) {
  490. return start;
  491. /** @type {State} */
  492. function start(code) {
  493. assert(markdownLineEnding(code), 'expected eol');
  494. effects.enter(types.lineEnding);
  495. effects.consume(code);
  496. effects.exit(types.lineEnding);
  497. return factorySpace(effects, prefixed, types.linePrefix);
  498. }
  499. /** @type {State} */
  500. function prefixed(code) {
  501. // Blank or interrupting line.
  502. if (
  503. self.parser.lazy[self.now().line]
  504. || code === codes.eof
  505. || markdownLineEnding(code)
  506. ) {
  507. return nok(code);
  508. }
  509. const tail = self.events[self.events.length - 1];
  510. // Indented code can interrupt delimiter and body rows.
  511. if (
  512. !self.parser.constructs.disable.null.includes('codeIndented')
  513. && tail
  514. && tail[1].type === types.linePrefix
  515. && tail[2].sliceSerialize(tail[1], true).length >= constants.tabSize
  516. ) {
  517. return nok(code);
  518. }
  519. self._gfmTableDynamicInterruptHack = true;
  520. return effects.check(
  521. self.parser.constructs.flow,
  522. (code) => {
  523. self._gfmTableDynamicInterruptHack = false;
  524. return nok(code);
  525. },
  526. (code) => {
  527. self._gfmTableDynamicInterruptHack = false;
  528. return ok(code);
  529. },
  530. )(code);
  531. }
  532. }
  533. }
  534. /** @type {Tokenizer} */
  535. function tokenizeNextPrefixedOrBlank(effects, ok, nok) {
  536. let size = 0;
  537. return start;
  538. /** @type {State} */
  539. function start(code) {
  540. // This is a check, so we don’t care about tokens, but we open a bogus one
  541. // so we’re valid.
  542. effects.enter('check');
  543. // EOL.
  544. effects.consume(code);
  545. return whitespace;
  546. }
  547. /** @type {State} */
  548. function whitespace(code) {
  549. if (code === codes.virtualSpace || code === codes.space) {
  550. effects.consume(code);
  551. size++;
  552. return size === constants.tabSize ? ok : whitespace;
  553. }
  554. // EOF or whitespace
  555. if (code === codes.eof || markdownLineEndingOrSpace(code)) {
  556. return ok(code);
  557. }
  558. // Anything else.
  559. return nok(code);
  560. }
  561. }