syntax.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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. const originalEnter = effects.enter;
  158. const originalExit = effects.exit;
  159. effects.enter = (...args) => {
  160. console.log(`>> enter ${args[0]}`);
  161. return originalEnter(...args);
  162. };
  163. effects.exit = (...args) => {
  164. console.log(`<< exit ${args[0]}`);
  165. return originalExit(...args);
  166. };
  167. return start;
  168. /** @type {State} */
  169. function start(code) {
  170. // @ts-expect-error Custom.
  171. effects.enter('table')._align = align;
  172. effects.enter('tableHead');
  173. effects.enter('tableRow');
  174. // If we start with a pipe, we open a cell marker.
  175. if (code === codes.verticalBar) {
  176. return cellDividerHead(code);
  177. }
  178. tableHeaderCount++;
  179. effects.enter('temporaryTableCellContent');
  180. // Can’t be space or eols at the start of a construct, so we’re in a cell.
  181. assert(!markdownLineEndingOrSpace(code), 'expected non-space');
  182. return inCellContentHead(code);
  183. }
  184. /** @type {State} */
  185. function cellDividerHead(code) {
  186. assert(code === codes.verticalBar, 'expected `|`');
  187. effects.enter('tableCellDivider');
  188. effects.consume(code);
  189. effects.exit('tableCellDivider');
  190. seenDelimiter = true;
  191. return cellBreakHead;
  192. }
  193. /** @type {State} */
  194. function cellBreakHead(code) {
  195. if (code === codes.eof || markdownLineEnding(code)) {
  196. return atRowEndHead(code);
  197. }
  198. if (markdownSpace(code)) {
  199. effects.enter(types.whitespace);
  200. effects.consume(code);
  201. return inWhitespaceHead;
  202. }
  203. if (seenDelimiter) {
  204. seenDelimiter = undefined;
  205. tableHeaderCount++;
  206. }
  207. if (code === codes.verticalBar) {
  208. return cellDividerHead(code);
  209. }
  210. // Anything else is cell content.
  211. effects.enter('temporaryTableCellContent');
  212. return inCellContentHead(code);
  213. }
  214. /** @type {State} */
  215. function inWhitespaceHead(code) {
  216. if (markdownSpace(code)) {
  217. effects.consume(code);
  218. return inWhitespaceHead;
  219. }
  220. effects.exit(types.whitespace);
  221. return cellBreakHead(code);
  222. }
  223. /** @type {State} */
  224. function inCellContentHead(code) {
  225. // EOF, whitespace, pipe
  226. if (
  227. code === codes.eof
  228. || code === codes.verticalBar
  229. || markdownLineEndingOrSpace(code)
  230. ) {
  231. effects.exit('temporaryTableCellContent');
  232. return cellBreakHead(code);
  233. }
  234. effects.consume(code);
  235. console.log('[consume in Head]', String.fromCharCode(code));
  236. return code === codes.backslash
  237. ? inCellContentEscapeHead
  238. : inCellContentHead;
  239. }
  240. /** @type {State} */
  241. function inCellContentEscapeHead(code) {
  242. if (code === codes.backslash || code === codes.verticalBar) {
  243. effects.consume(code);
  244. return inCellContentHead;
  245. }
  246. // Anything else.
  247. return inCellContentHead(code);
  248. }
  249. /** @type {State} */
  250. function atRowEndHead(code) {
  251. if (code === codes.eof) {
  252. return nok(code);
  253. }
  254. assert(markdownLineEnding(code), 'expected eol');
  255. effects.exit('tableRow');
  256. effects.exit('tableHead');
  257. const originalInterrupt = self.interrupt;
  258. self.interrupt = true;
  259. return effects.attempt(
  260. { tokenize: tokenizeRowEnd, partial: true },
  261. (code) => {
  262. self.interrupt = originalInterrupt;
  263. effects.enter('tableDelimiterRow');
  264. return atDelimiterRowBreak(code);
  265. },
  266. (code) => {
  267. self.interrupt = originalInterrupt;
  268. return nok(code);
  269. },
  270. )(code);
  271. }
  272. /** @type {State} */
  273. function atDelimiterRowBreak(code) {
  274. if (code === codes.eof || markdownLineEnding(code)) {
  275. return rowEndDelimiter(code);
  276. }
  277. if (markdownSpace(code)) {
  278. effects.enter(types.whitespace);
  279. effects.consume(code);
  280. return inWhitespaceDelimiter;
  281. }
  282. if (code === codes.dash) {
  283. effects.enter('tableDelimiterFiller');
  284. effects.consume(code);
  285. hasDash = true;
  286. align.push('none');
  287. return inFillerDelimiter;
  288. }
  289. if (code === codes.colon) {
  290. effects.enter('tableDelimiterAlignment');
  291. effects.consume(code);
  292. effects.exit('tableDelimiterAlignment');
  293. align.push('left');
  294. return afterLeftAlignment;
  295. }
  296. // If we start with a pipe, we open a cell marker.
  297. if (code === codes.verticalBar) {
  298. effects.enter('tableCellDivider');
  299. effects.consume(code);
  300. effects.exit('tableCellDivider');
  301. return atDelimiterRowBreak;
  302. }
  303. return nok(code);
  304. }
  305. /** @type {State} */
  306. function inWhitespaceDelimiter(code) {
  307. if (markdownSpace(code)) {
  308. effects.consume(code);
  309. return inWhitespaceDelimiter;
  310. }
  311. effects.exit(types.whitespace);
  312. return atDelimiterRowBreak(code);
  313. }
  314. /** @type {State} */
  315. function inFillerDelimiter(code) {
  316. if (code === codes.dash) {
  317. effects.consume(code);
  318. return inFillerDelimiter;
  319. }
  320. effects.exit('tableDelimiterFiller');
  321. if (code === codes.colon) {
  322. effects.enter('tableDelimiterAlignment');
  323. effects.consume(code);
  324. effects.exit('tableDelimiterAlignment');
  325. align[align.length - 1] = align[align.length - 1] === 'left' ? 'center' : 'right';
  326. return afterRightAlignment;
  327. }
  328. return atDelimiterRowBreak(code);
  329. }
  330. /** @type {State} */
  331. function afterLeftAlignment(code) {
  332. if (code === codes.dash) {
  333. effects.enter('tableDelimiterFiller');
  334. effects.consume(code);
  335. hasDash = true;
  336. return inFillerDelimiter;
  337. }
  338. // Anything else is not ok.
  339. return nok(code);
  340. }
  341. /** @type {State} */
  342. function afterRightAlignment(code) {
  343. if (code === codes.eof || markdownLineEnding(code)) {
  344. return rowEndDelimiter(code);
  345. }
  346. if (markdownSpace(code)) {
  347. effects.enter(types.whitespace);
  348. effects.consume(code);
  349. return inWhitespaceDelimiter;
  350. }
  351. // `|`
  352. if (code === codes.verticalBar) {
  353. effects.enter('tableCellDivider');
  354. effects.consume(code);
  355. effects.exit('tableCellDivider');
  356. return atDelimiterRowBreak;
  357. }
  358. return nok(code);
  359. }
  360. /** @type {State} */
  361. function rowEndDelimiter(code) {
  362. effects.exit('tableDelimiterRow');
  363. // Exit if there was no dash at all, or if the header cell count is not the
  364. // delimiter cell count.
  365. if (!hasDash || tableHeaderCount !== align.length) {
  366. return nok(code);
  367. }
  368. if (code === codes.eof) {
  369. return tableClose(code);
  370. }
  371. assert(markdownLineEnding(code), 'expected eol');
  372. return effects.check(
  373. nextPrefixedOrBlank,
  374. tableClose,
  375. effects.attempt(
  376. { tokenize: tokenizeRowEnd, partial: true },
  377. factorySpace(effects, bodyStart, types.linePrefix, constants.tabSize),
  378. tableClose,
  379. ),
  380. )(code);
  381. }
  382. /** @type {State} */
  383. function tableClose(code) {
  384. effects.exit('table');
  385. return ok(code);
  386. }
  387. /** @type {State} */
  388. function bodyStart(code) {
  389. effects.enter('tableBody');
  390. return rowStartBody(code);
  391. }
  392. /** @type {State} */
  393. function rowStartBody(code) {
  394. effects.enter('tableRow');
  395. // If we start with a pipe, we open a cell marker.
  396. if (code === codes.verticalBar) {
  397. return cellDividerBody(code);
  398. }
  399. effects.enter('temporaryTableCellContent');
  400. // Can’t be space or eols at the start of a construct, so we’re in a cell.
  401. return inCellContentBody(code);
  402. }
  403. /** @type {State} */
  404. function cellDividerBody(code) {
  405. assert(code === codes.verticalBar, 'expected `|`');
  406. effects.enter('tableCellDivider');
  407. effects.consume(code);
  408. effects.exit('tableCellDivider');
  409. return cellBreakBody;
  410. }
  411. /** @type {State} */
  412. function cellBreakBody(code) {
  413. if (code === codes.eof || markdownLineEnding(code)) {
  414. return atRowEndBody(code);
  415. }
  416. if (markdownSpace(code)) {
  417. effects.enter(types.whitespace);
  418. effects.consume(code);
  419. return inWhitespaceBody;
  420. }
  421. // `|`
  422. if (code === codes.verticalBar) {
  423. return cellDividerBody(code);
  424. }
  425. // Anything else is cell content.
  426. effects.enter('temporaryTableCellContent');
  427. return inCellContentBody(code);
  428. }
  429. /** @type {State} */
  430. function inWhitespaceBody(code) {
  431. if (markdownSpace(code)) {
  432. effects.consume(code);
  433. return inWhitespaceBody;
  434. }
  435. effects.exit(types.whitespace);
  436. return cellBreakBody(code);
  437. }
  438. /** @type {State} */
  439. function inCellContentBody(code) {
  440. // EOF, whitespace, pipe
  441. if (
  442. code === codes.eof
  443. || code === codes.verticalBar
  444. || markdownLineEndingOrSpace(code)
  445. ) {
  446. effects.exit('temporaryTableCellContent');
  447. return cellBreakBody(code);
  448. }
  449. effects.consume(code);
  450. console.log('[consume in Body]', String.fromCharCode(code));
  451. return code === codes.backslash
  452. ? inCellContentEscapeBody
  453. : inCellContentBody;
  454. }
  455. /** @type {State} */
  456. function inCellContentEscapeBody(code) {
  457. if (code === codes.backslash || code === codes.verticalBar) {
  458. effects.consume(code);
  459. return inCellContentBody;
  460. }
  461. // Anything else.
  462. return inCellContentBody(code);
  463. }
  464. /** @type {State} */
  465. function atRowEndBody(code) {
  466. effects.exit('tableRow');
  467. if (code === codes.eof) {
  468. return tableBodyClose(code);
  469. }
  470. return effects.check(
  471. nextPrefixedOrBlank,
  472. tableBodyClose,
  473. effects.attempt(
  474. { tokenize: tokenizeRowEnd, partial: true },
  475. factorySpace(
  476. effects,
  477. rowStartBody,
  478. types.linePrefix,
  479. constants.tabSize,
  480. ),
  481. tableBodyClose,
  482. ),
  483. )(code);
  484. }
  485. /** @type {State} */
  486. function tableBodyClose(code) {
  487. effects.exit('tableBody');
  488. return tableClose(code);
  489. }
  490. /** @type {Tokenizer} */
  491. function tokenizeRowEnd(effects, ok, nok) {
  492. return start;
  493. /** @type {State} */
  494. function start(code) {
  495. assert(markdownLineEnding(code), 'expected eol');
  496. effects.enter(types.lineEnding);
  497. effects.consume(code);
  498. effects.exit(types.lineEnding);
  499. return factorySpace(effects, prefixed, types.linePrefix);
  500. }
  501. /** @type {State} */
  502. function prefixed(code) {
  503. // Blank or interrupting line.
  504. if (
  505. self.parser.lazy[self.now().line]
  506. || code === codes.eof
  507. || markdownLineEnding(code)
  508. ) {
  509. return nok(code);
  510. }
  511. const tail = self.events[self.events.length - 1];
  512. // Indented code can interrupt delimiter and body rows.
  513. if (
  514. !self.parser.constructs.disable.null.includes('codeIndented')
  515. && tail
  516. && tail[1].type === types.linePrefix
  517. && tail[2].sliceSerialize(tail[1], true).length >= constants.tabSize
  518. ) {
  519. return nok(code);
  520. }
  521. self._gfmTableDynamicInterruptHack = true;
  522. return effects.check(
  523. self.parser.constructs.flow,
  524. (code) => {
  525. self._gfmTableDynamicInterruptHack = false;
  526. return nok(code);
  527. },
  528. (code) => {
  529. self._gfmTableDynamicInterruptHack = false;
  530. return ok(code);
  531. },
  532. )(code);
  533. }
  534. }
  535. }
  536. /** @type {Tokenizer} */
  537. function tokenizeNextPrefixedOrBlank(effects, ok, nok) {
  538. let size = 0;
  539. return start;
  540. /** @type {State} */
  541. function start(code) {
  542. // This is a check, so we don’t care about tokens, but we open a bogus one
  543. // so we’re valid.
  544. effects.enter('check');
  545. // EOL.
  546. effects.consume(code);
  547. return whitespace;
  548. }
  549. /** @type {State} */
  550. function whitespace(code) {
  551. if (code === codes.virtualSpace || code === codes.space) {
  552. effects.consume(code);
  553. size++;
  554. return size === constants.tabSize ? ok : whitespace;
  555. }
  556. // EOF or whitespace
  557. if (code === codes.eof || markdownLineEndingOrSpace(code)) {
  558. return ok(code);
  559. }
  560. // Anything else.
  561. return nok(code);
  562. }
  563. }