syntax.js 16 KB

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