syntax.js 17 KB

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