aboutsummaryrefslogtreecommitdiff
path: root/src/blocks.c
blob: a74d97e94bc57fad481a9a92c3df3258a208e1f1 (plain)
  1. #include <stdlib.h>
  2. #include <assert.h>
  3. #include <stdio.h>
  4. #include <stdbool.h>
  5. #include <ctype.h>
  6. #include "cmark.h"
  7. #include "utf8.h"
  8. #include "scanners.h"
  9. #include "inlines.h"
  10. #include "html/houdini.h"
  11. #include "bench.h"
  12. #define peek_at(i, n) (i)->data[n]
  13. static void incorporate_line(strbuf *ln, int line_number, node_block** curptr);
  14. static void finalize(node_block* b, int line_number);
  15. static node_block* make_block(int tag, int start_line, int start_column)
  16. {
  17. node_block* e;
  18. e = calloc(1, sizeof(*e));
  19. if(e != NULL) {
  20. e->tag = tag;
  21. e->open = true;
  22. e->start_line = start_line;
  23. e->start_column = start_column;
  24. e->end_line = start_line;
  25. strbuf_init(&e->string_content, 32);
  26. }
  27. return e;
  28. }
  29. // Create a root document node_block.
  30. static node_block* make_document()
  31. {
  32. node_block *e = make_block(BLOCK_DOCUMENT, 1, 1);
  33. e->as.document.refmap = reference_map_new();
  34. e->top = e;
  35. return e;
  36. }
  37. // Returns true if line has only space characters, else false.
  38. static bool is_blank(strbuf *s, int offset)
  39. {
  40. while (offset < s->size) {
  41. switch (s->ptr[offset]) {
  42. case '\n':
  43. return true;
  44. case ' ':
  45. offset++;
  46. break;
  47. default:
  48. return false;
  49. }
  50. }
  51. return true;
  52. }
  53. static inline bool can_contain(int parent_type, int child_type)
  54. {
  55. return ( parent_type == BLOCK_DOCUMENT ||
  56. parent_type == BLOCK_BQUOTE ||
  57. parent_type == BLOCK_LIST_ITEM ||
  58. (parent_type == BLOCK_LIST && child_type == BLOCK_LIST_ITEM) );
  59. }
  60. static inline bool accepts_lines(int block_type)
  61. {
  62. return (block_type == BLOCK_PARAGRAPH ||
  63. block_type == BLOCK_ATX_HEADER ||
  64. block_type == BLOCK_INDENTED_CODE ||
  65. block_type == BLOCK_FENCED_CODE);
  66. }
  67. static void add_line(node_block* node_block, chunk *ch, int offset)
  68. {
  69. assert(node_block->open);
  70. strbuf_put(&node_block->string_content, ch->data + offset, ch->len - offset);
  71. }
  72. static void remove_trailing_blank_lines(strbuf *ln)
  73. {
  74. int i;
  75. for (i = ln->size - 1; i >= 0; --i) {
  76. unsigned char c = ln->ptr[i];
  77. if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
  78. break;
  79. }
  80. if (i < 0) {
  81. strbuf_clear(ln);
  82. return;
  83. }
  84. i = strbuf_strchr(ln, '\n', i);
  85. if (i >= 0)
  86. strbuf_truncate(ln, i);
  87. }
  88. // Check to see if a node_block ends with a blank line, descending
  89. // if needed into lists and sublists.
  90. static bool ends_with_blank_line(node_block* node_block)
  91. {
  92. if (node_block->last_line_blank) {
  93. return true;
  94. }
  95. if ((node_block->tag == BLOCK_LIST || node_block->tag == BLOCK_LIST_ITEM) && node_block->last_child) {
  96. return ends_with_blank_line(node_block->last_child);
  97. } else {
  98. return false;
  99. }
  100. }
  101. // Break out of all containing lists
  102. static int break_out_of_lists(node_block ** bptr, int line_number)
  103. {
  104. node_block *container = *bptr;
  105. node_block *b = container->top;
  106. // find first containing BLOCK_LIST:
  107. while (b && b->tag != BLOCK_LIST) {
  108. b = b->last_child;
  109. }
  110. if (b) {
  111. while (container && container != b) {
  112. finalize(container, line_number);
  113. container = container->parent;
  114. }
  115. finalize(b, line_number);
  116. *bptr = b->parent;
  117. }
  118. return 0;
  119. }
  120. static void finalize(node_block* b, int line_number)
  121. {
  122. int firstlinelen;
  123. int pos;
  124. node_block* item;
  125. node_block* subitem;
  126. if (!b->open)
  127. return; // don't do anything if the node_block is already closed
  128. b->open = false;
  129. if (line_number > b->start_line) {
  130. b->end_line = line_number - 1;
  131. } else {
  132. b->end_line = line_number;
  133. }
  134. switch (b->tag) {
  135. case BLOCK_PARAGRAPH:
  136. pos = 0;
  137. while (strbuf_at(&b->string_content, 0) == '[' &&
  138. (pos = parse_reference_inline(&b->string_content, b->top->as.document.refmap))) {
  139. strbuf_drop(&b->string_content, pos);
  140. }
  141. if (is_blank(&b->string_content, 0)) {
  142. b->tag = BLOCK_REFERENCE_DEF;
  143. }
  144. break;
  145. case BLOCK_INDENTED_CODE:
  146. remove_trailing_blank_lines(&b->string_content);
  147. strbuf_putc(&b->string_content, '\n');
  148. break;
  149. case BLOCK_FENCED_CODE:
  150. // first line of contents becomes info
  151. firstlinelen = strbuf_strchr(&b->string_content, '\n', 0);
  152. strbuf_init(&b->as.code.info, 0);
  153. houdini_unescape_html_f(
  154. &b->as.code.info,
  155. b->string_content.ptr,
  156. firstlinelen
  157. );
  158. strbuf_drop(&b->string_content, firstlinelen + 1);
  159. strbuf_trim(&b->as.code.info);
  160. strbuf_unescape(&b->as.code.info);
  161. break;
  162. case BLOCK_LIST: // determine tight/loose status
  163. b->as.list.tight = true; // tight by default
  164. item = b->children;
  165. while (item) {
  166. // check for non-final non-empty list item ending with blank line:
  167. if (item->last_line_blank && item->next) {
  168. b->as.list.tight = false;
  169. break;
  170. }
  171. // recurse into children of list item, to see if there are
  172. // spaces between them:
  173. subitem = item->children;
  174. while (subitem) {
  175. if (ends_with_blank_line(subitem) &&
  176. (item->next || subitem->next)) {
  177. b->as.list.tight = false;
  178. break;
  179. }
  180. subitem = subitem->next;
  181. }
  182. if (!(b->as.list.tight)) {
  183. break;
  184. }
  185. item = item->next;
  186. }
  187. break;
  188. default:
  189. break;
  190. }
  191. }
  192. // Add a node_block as child of another. Return pointer to child.
  193. static node_block* add_child(node_block* parent,
  194. int block_type, int start_line, int start_column)
  195. {
  196. assert(parent);
  197. // if 'parent' isn't the kind of node_block that can accept this child,
  198. // then back up til we hit a node_block that can.
  199. while (!can_contain(parent->tag, block_type)) {
  200. finalize(parent, start_line);
  201. parent = parent->parent;
  202. }
  203. node_block* child = make_block(block_type, start_line, start_column);
  204. child->parent = parent;
  205. child->top = parent->top;
  206. if (parent->last_child) {
  207. parent->last_child->next = child;
  208. child->prev = parent->last_child;
  209. } else {
  210. parent->children = child;
  211. child->prev = NULL;
  212. }
  213. parent->last_child = child;
  214. return child;
  215. }
  216. typedef struct BlockStack {
  217. struct BlockStack *previous;
  218. node_block *next_sibling;
  219. } block_stack;
  220. // Walk through node_block and all children, recursively, parsing
  221. // string content into inline content where appropriate.
  222. static void process_inlines(node_block* cur, reference_map *refmap)
  223. {
  224. block_stack* stack = NULL;
  225. block_stack* newstack = NULL;
  226. while (cur != NULL) {
  227. switch (cur->tag) {
  228. case BLOCK_PARAGRAPH:
  229. case BLOCK_ATX_HEADER:
  230. case BLOCK_SETEXT_HEADER:
  231. cur->inline_content = parse_inlines(&cur->string_content, refmap);
  232. break;
  233. default:
  234. break;
  235. }
  236. if (cur->children) {
  237. newstack = (block_stack*)malloc(sizeof(block_stack));
  238. if (newstack == NULL) return;
  239. newstack->previous = stack;
  240. stack = newstack;
  241. stack->next_sibling = cur->next;
  242. cur = cur->children;
  243. } else {
  244. cur = cur->next;
  245. }
  246. while (cur == NULL && stack != NULL) {
  247. cur = stack->next_sibling;
  248. newstack = stack->previous;
  249. free(stack);
  250. stack = newstack;
  251. }
  252. }
  253. while (stack != NULL) {
  254. newstack = stack->previous;
  255. free(stack);
  256. stack = newstack;
  257. }
  258. }
  259. // Attempts to parse a list item marker (bullet or enumerated).
  260. // On success, returns length of the marker, and populates
  261. // data with the details. On failure, returns 0.
  262. static int parse_list_marker(chunk *input, int pos, struct ListData ** dataptr)
  263. {
  264. unsigned char c;
  265. int startpos;
  266. struct ListData * data;
  267. startpos = pos;
  268. c = peek_at(input, pos);
  269. if ((c == '*' || c == '-' || c == '+') && !scan_hrule(input, pos)) {
  270. pos++;
  271. if (!isspace(peek_at(input, pos))) {
  272. return 0;
  273. }
  274. data = calloc(1, sizeof(*data));
  275. if(data == NULL) {
  276. return 0;
  277. } else {
  278. data->marker_offset = 0; // will be adjusted later
  279. data->list_type = bullet;
  280. data->bullet_char = c;
  281. data->start = 1;
  282. data->delimiter = period;
  283. data->tight = false;
  284. }
  285. } else if (isdigit(c)) {
  286. int start = 0;
  287. do {
  288. start = (10 * start) + (peek_at(input, pos) - '0');
  289. pos++;
  290. } while (isdigit(peek_at(input, pos)));
  291. c = peek_at(input, pos);
  292. if (c == '.' || c == ')') {
  293. pos++;
  294. if (!isspace(peek_at(input, pos))) {
  295. return 0;
  296. }
  297. data = calloc(1, sizeof(*data));
  298. if(data == NULL) {
  299. return 0;
  300. } else {
  301. data->marker_offset = 0; // will be adjusted later
  302. data->list_type = ordered;
  303. data->bullet_char = 0;
  304. data->start = start;
  305. data->delimiter = (c == '.' ? period : parens);
  306. data->tight = false;
  307. }
  308. } else {
  309. return 0;
  310. }
  311. } else {
  312. return 0;
  313. }
  314. *dataptr = data;
  315. return (pos - startpos);
  316. }
  317. // Return 1 if list item belongs in list, else 0.
  318. static int lists_match(struct ListData *list_data, struct ListData *item_data)
  319. {
  320. return (list_data->list_type == item_data->list_type &&
  321. list_data->delimiter == item_data->delimiter &&
  322. // list_data->marker_offset == item_data.marker_offset &&
  323. list_data->bullet_char == item_data->bullet_char);
  324. }
  325. static node_block *finalize_document(node_block *document, int linenum)
  326. {
  327. start_timer();
  328. while (document != document->top) {
  329. finalize(document, linenum);
  330. document = document->parent;
  331. }
  332. finalize(document, linenum);
  333. process_inlines(document, document->as.document.refmap);
  334. end_timer("finalize_document");
  335. return document;
  336. }
  337. extern node_block *cmark_parse_file(FILE *f)
  338. {
  339. strbuf line = GH_BUF_INIT;
  340. unsigned char buffer[4096];
  341. int linenum = 1;
  342. node_block *document = make_document();
  343. start_timer();
  344. while (fgets((char *)buffer, sizeof(buffer), f)) {
  345. utf8proc_detab(&line, buffer, strlen((char *)buffer));
  346. incorporate_line(&line, linenum, &document);
  347. strbuf_clear(&line);
  348. linenum++;
  349. }
  350. end_timer("incorporate_line(s)");
  351. strbuf_free(&line);
  352. return finalize_document(document, linenum);
  353. }
  354. extern node_block *cmark_parse_document(const unsigned char *buffer, size_t len)
  355. {
  356. strbuf line = GH_BUF_INIT;
  357. int linenum = 1;
  358. const unsigned char *end = buffer + len;
  359. node_block *document = make_document();
  360. while (buffer < end) {
  361. const unsigned char *eol = memchr(buffer, '\n', end - buffer);
  362. if (!eol) {
  363. utf8proc_detab(&line, buffer, end - buffer);
  364. buffer = end;
  365. } else {
  366. utf8proc_detab(&line, buffer, (eol - buffer) + 1);
  367. buffer += (eol - buffer) + 1;
  368. }
  369. incorporate_line(&line, linenum, &document);
  370. strbuf_clear(&line);
  371. linenum++;
  372. }
  373. strbuf_free(&line);
  374. return finalize_document(document, linenum);
  375. }
  376. static void chop_trailing_hashtags(chunk *ch)
  377. {
  378. int n, orig_n;
  379. chunk_rtrim(ch);
  380. orig_n = n = ch->len - 1;
  381. // if string ends in space followed by #s, remove these:
  382. while (n >= 0 && peek_at(ch, n) == '#')
  383. n--;
  384. // Check for a be a space before the final #s:
  385. if (n != orig_n && n >= 0 && peek_at(ch, n) == ' ') {
  386. ch->len = n;
  387. chunk_rtrim(ch);
  388. }
  389. }
  390. // Process one line at a time, modifying a node_block.
  391. static void incorporate_line(strbuf *line, int line_number, node_block** curptr)
  392. {
  393. node_block* last_matched_container;
  394. int offset = 0;
  395. int matched = 0;
  396. int lev = 0;
  397. int i;
  398. struct ListData * data = NULL;
  399. bool all_matched = true;
  400. node_block* container;
  401. node_block* cur = *curptr;
  402. bool blank = false;
  403. int first_nonspace;
  404. int indent;
  405. chunk input;
  406. // Add a newline to the end if not present:
  407. if (line->ptr[line->size - 1] != '\n') {
  408. strbuf_putc(line, '\n');
  409. }
  410. input.data = line->ptr;
  411. input.len = line->size;
  412. // container starts at the document root.
  413. container = cur->top;
  414. // for each containing node_block, try to parse the associated line start.
  415. // bail out on failure: container will point to the last matching node_block.
  416. while (container->last_child && container->last_child->open) {
  417. container = container->last_child;
  418. first_nonspace = offset;
  419. while (peek_at(&input, first_nonspace) == ' ') {
  420. first_nonspace++;
  421. }
  422. indent = first_nonspace - offset;
  423. blank = peek_at(&input, first_nonspace) == '\n';
  424. if (container->tag == BLOCK_BQUOTE) {
  425. matched = indent <= 3 && peek_at(&input, first_nonspace) == '>';
  426. if (matched) {
  427. offset = first_nonspace + 1;
  428. if (peek_at(&input, offset) == ' ')
  429. offset++;
  430. } else {
  431. all_matched = false;
  432. }
  433. } else if (container->tag == BLOCK_LIST_ITEM) {
  434. if (indent >= container->as.list.marker_offset +
  435. container->as.list.padding) {
  436. offset += container->as.list.marker_offset +
  437. container->as.list.padding;
  438. } else if (blank) {
  439. offset = first_nonspace;
  440. } else {
  441. all_matched = false;
  442. }
  443. } else if (container->tag == BLOCK_INDENTED_CODE) {
  444. if (indent >= CODE_INDENT) {
  445. offset += CODE_INDENT;
  446. } else if (blank) {
  447. offset = first_nonspace;
  448. } else {
  449. all_matched = false;
  450. }
  451. } else if (container->tag == BLOCK_ATX_HEADER ||
  452. container->tag == BLOCK_SETEXT_HEADER) {
  453. // a header can never contain more than one line
  454. all_matched = false;
  455. } else if (container->tag == BLOCK_FENCED_CODE) {
  456. // skip optional spaces of fence offset
  457. i = container->as.code.fence_offset;
  458. while (i > 0 && peek_at(&input, offset) == ' ') {
  459. offset++;
  460. i--;
  461. }
  462. } else if (container->tag == BLOCK_HTML) {
  463. if (blank) {
  464. all_matched = false;
  465. }
  466. } else if (container->tag == BLOCK_PARAGRAPH) {
  467. if (blank) {
  468. container->last_line_blank = true;
  469. all_matched = false;
  470. }
  471. }
  472. if (!all_matched) {
  473. container = container->parent; // back up to last matching node_block
  474. break;
  475. }
  476. }
  477. last_matched_container = container;
  478. // check to see if we've hit 2nd blank line, break out of list:
  479. if (blank && container->last_line_blank) {
  480. break_out_of_lists(&container, line_number);
  481. }
  482. // unless last matched container is code node_block, try new container starts:
  483. while (container->tag != BLOCK_FENCED_CODE && container->tag != BLOCK_INDENTED_CODE &&
  484. container->tag != BLOCK_HTML) {
  485. first_nonspace = offset;
  486. while (peek_at(&input, first_nonspace) == ' ')
  487. first_nonspace++;
  488. indent = first_nonspace - offset;
  489. blank = peek_at(&input, first_nonspace) == '\n';
  490. if (indent >= CODE_INDENT) {
  491. if (cur->tag != BLOCK_PARAGRAPH && !blank) {
  492. offset += CODE_INDENT;
  493. container = add_child(container, BLOCK_INDENTED_CODE, line_number, offset + 1);
  494. } else { // indent > 4 in lazy line
  495. break;
  496. }
  497. } else if (peek_at(&input, first_nonspace) == '>') {
  498. offset = first_nonspace + 1;
  499. // optional following character
  500. if (peek_at(&input, offset) == ' ')
  501. offset++;
  502. container = add_child(container, BLOCK_BQUOTE, line_number, offset + 1);
  503. } else if ((matched = scan_atx_header_start(&input, first_nonspace))) {
  504. offset = first_nonspace + matched;
  505. container = add_child(container, BLOCK_ATX_HEADER, line_number, offset + 1);
  506. int hashpos = chunk_strchr(&input, '#', first_nonspace);
  507. int level = 0;
  508. while (peek_at(&input, hashpos) == '#') {
  509. level++;
  510. hashpos++;
  511. }
  512. container->as.header.level = level;
  513. } else if ((matched = scan_open_code_fence(&input, first_nonspace))) {
  514. container = add_child(container, BLOCK_FENCED_CODE, line_number, first_nonspace + 1);
  515. container->as.code.fence_char = peek_at(&input, first_nonspace);
  516. container->as.code.fence_length = matched;
  517. container->as.code.fence_offset = first_nonspace - offset;
  518. offset = first_nonspace + matched;
  519. } else if ((matched = scan_html_block_tag(&input, first_nonspace))) {
  520. container = add_child(container, BLOCK_HTML, line_number, first_nonspace + 1);
  521. // note, we don't adjust offset because the tag is part of the text
  522. } else if (container->tag == BLOCK_PARAGRAPH &&
  523. (lev = scan_setext_header_line(&input, first_nonspace)) &&
  524. // check that there is only one line in the paragraph:
  525. strbuf_strrchr(&container->string_content, '\n',
  526. strbuf_len(&container->string_content) - 2) < 0) {
  527. container->tag = BLOCK_SETEXT_HEADER;
  528. container->as.header.level = lev;
  529. offset = input.len - 1;
  530. } else if (!(container->tag == BLOCK_PARAGRAPH && !all_matched) &&
  531. (matched = scan_hrule(&input, first_nonspace))) {
  532. // it's only now that we know the line is not part of a setext header:
  533. container = add_child(container, BLOCK_HRULE, line_number, first_nonspace + 1);
  534. finalize(container, line_number);
  535. container = container->parent;
  536. offset = input.len - 1;
  537. } else if ((matched = parse_list_marker(&input, first_nonspace, &data))) {
  538. // compute padding:
  539. offset = first_nonspace + matched;
  540. i = 0;
  541. while (i <= 5 && peek_at(&input, offset + i) == ' ') {
  542. i++;
  543. }
  544. // i = number of spaces after marker, up to 5
  545. if (i >= 5 || i < 1 || peek_at(&input, offset) == '\n') {
  546. data->padding = matched + 1;
  547. if (i > 0) {
  548. offset += 1;
  549. }
  550. } else {
  551. data->padding = matched + i;
  552. offset += i;
  553. }
  554. // check container; if it's a list, see if this list item
  555. // can continue the list; otherwise, create a list container.
  556. data->marker_offset = indent;
  557. if (container->tag != BLOCK_LIST ||
  558. !lists_match(&container->as.list, data)) {
  559. container = add_child(container, BLOCK_LIST, line_number,
  560. first_nonspace + 1);
  561. memcpy(&container->as.list, data, sizeof(*data));
  562. }
  563. // add the list item
  564. container = add_child(container, BLOCK_LIST_ITEM, line_number,
  565. first_nonspace + 1);
  566. /* TODO: static */
  567. memcpy(&container->as.list, data, sizeof(*data));
  568. free(data);
  569. } else {
  570. break;
  571. }
  572. if (accepts_lines(container->tag)) {
  573. // if it's a line container, it can't contain other containers
  574. break;
  575. }
  576. }
  577. // what remains at offset is a text line. add the text to the
  578. // appropriate container.
  579. first_nonspace = offset;
  580. while (peek_at(&input, first_nonspace) == ' ')
  581. first_nonspace++;
  582. indent = first_nonspace - offset;
  583. blank = peek_at(&input, first_nonspace) == '\n';
  584. // node_block quote lines are never blank as they start with >
  585. // and we don't count blanks in fenced code for purposes of tight/loose
  586. // lists or breaking out of lists. we also don't set last_line_blank
  587. // on an empty list item.
  588. container->last_line_blank = (blank &&
  589. container->tag != BLOCK_BQUOTE &&
  590. container->tag != BLOCK_FENCED_CODE &&
  591. !(container->tag == BLOCK_LIST_ITEM &&
  592. container->children == NULL &&
  593. container->start_line == line_number));
  594. node_block *cont = container;
  595. while (cont->parent) {
  596. cont->parent->last_line_blank = false;
  597. cont = cont->parent;
  598. }
  599. if (cur != last_matched_container &&
  600. container == last_matched_container &&
  601. !blank &&
  602. cur->tag == BLOCK_PARAGRAPH &&
  603. strbuf_len(&cur->string_content) > 0) {
  604. add_line(cur, &input, offset);
  605. } else { // not a lazy continuation
  606. // finalize any blocks that were not matched and set cur to container:
  607. while (cur != last_matched_container) {
  608. finalize(cur, line_number);
  609. cur = cur->parent;
  610. assert(cur != NULL);
  611. }
  612. if (container->tag == BLOCK_INDENTED_CODE) {
  613. add_line(container, &input, offset);
  614. } else if (container->tag == BLOCK_FENCED_CODE) {
  615. matched = 0;
  616. if (indent <= 3 &&
  617. peek_at(&input, first_nonspace) == container->as.code.fence_char) {
  618. int fence_len = scan_close_code_fence(&input, first_nonspace);
  619. if (fence_len > container->as.code.fence_length)
  620. matched = 1;
  621. }
  622. if (matched) {
  623. // if closing fence, don't add line to container; instead, close it:
  624. finalize(container, line_number);
  625. container = container->parent; // back up to parent
  626. } else {
  627. add_line(container, &input, offset);
  628. }
  629. } else if (container->tag == BLOCK_HTML) {
  630. add_line(container, &input, offset);
  631. } else if (blank) {
  632. // ??? do nothing
  633. } else if (container->tag == BLOCK_ATX_HEADER) {
  634. chop_trailing_hashtags(&input);
  635. add_line(container, &input, first_nonspace);
  636. finalize(container, line_number);
  637. container = container->parent;
  638. } else if (accepts_lines(container->tag)) {
  639. add_line(container, &input, first_nonspace);
  640. } else if (container->tag != BLOCK_HRULE && container->tag != BLOCK_SETEXT_HEADER) {
  641. // create paragraph container for line
  642. container = add_child(container, BLOCK_PARAGRAPH, line_number, first_nonspace + 1);
  643. add_line(container, &input, first_nonspace);
  644. } else {
  645. assert(false);
  646. }
  647. *curptr = container;
  648. }
  649. }