syntax.js 16 KB

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