summaryrefslogtreecommitdiff
path: root/docs/handbook/cmark/code-style.md
blob: 0ac2af2def84a26a11777b49f5d581b6d57f6589 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# cmark — Code Style and Conventions

## Overview

This document describes the coding conventions and patterns used throughout the cmark codebase. Understanding these conventions makes the source code easier to navigate.

## Naming Conventions

### Public API Functions

All public functions use the `cmark_` prefix:
```c
cmark_node *cmark_node_new(cmark_node_type type);
cmark_parser *cmark_parser_new(int options);
char *cmark_render_html(cmark_node *root, int options);
```

### Internal (Static) Functions

File-local static functions use the `S_` prefix:
```c
static void S_render_node(cmark_node *node, cmark_event_type ev_type,
                          struct render_state *state, int options);
static cmark_node *S_node_new(cmark_node_type type, cmark_mem *mem);
static void S_free_nodes(cmark_node *e);
static bool S_is_leaf(cmark_node *node);
static int S_get_enumlevel(cmark_node *node);
```

This convention makes it immediately clear whether a function has file-local scope.

### Internal (Non-Static) Functions

Functions that are internal to the library but shared across translation units use:
- `cmark_` prefix (same as public) — declared in private headers (e.g., `parser.h`, `node.h`)
- No `S_` prefix

Examples:
```c
// In node.h (private header):
void cmark_node_set_type(cmark_node *node, cmark_node_type type);
cmark_node *make_block(cmark_mem *mem, cmark_node_type type,
                       int start_line, int start_column);
```

### Struct Members

No prefix convention — struct members use plain names:
```c
struct cmark_node {
  cmark_mem *mem;
  cmark_node *next;
  cmark_node *prev;
  cmark_node *parent;
  cmark_node *first_child;
  cmark_node *last_child;
  // ...
};
```

### Type Names

Typedefs use the `cmark_` prefix:
```c
typedef struct cmark_node cmark_node;
typedef struct cmark_parser cmark_parser;
typedef struct cmark_iter cmark_iter;
typedef int32_t bufsize_t;      // Exception: no cmark_ prefix
```

### Enum Values

Enum constants use the `CMARK_` prefix with UPPER_CASE:
```c
typedef enum {
  CMARK_NODE_NONE,
  CMARK_NODE_DOCUMENT,
  CMARK_NODE_BLOCK_QUOTE,
  // ...
} cmark_node_type;
```

### Preprocessor Macros

Macros use UPPER_CASE, sometimes with `CMARK_` prefix:
```c
#define CMARK_OPT_SOURCEPOS   (1 << 1)
#define CMARK_BUF_INIT(mem)   { mem, cmark_strbuf__initbuf, 0, 0 }
#define MAX_LINK_LABEL_LENGTH 999
#define CODE_INDENT           4
```

## Error Handling Patterns

### Allocation Failure

The default allocator (`xcalloc`, `xrealloc`) aborts on failure:
```c
static void *xcalloc(size_t nmemb, size_t size) {
  void *ptr = calloc(nmemb, size);
  if (!ptr) abort();
  return ptr;
}
```

Functions that allocate never return NULL — they either succeed or terminate. This eliminates NULL-check boilerplate throughout the codebase.

### Invalid Input

Functions that receive invalid arguments typically:
1. Return 0/false/NULL for queries
2. Do nothing for mutations
3. Never crash

Example from `node.c`:
```c
int cmark_node_set_heading_level(cmark_node *node, int level) {
  if (node == NULL || node->type != CMARK_NODE_HEADING) return 0;
  if (level < 1 || level > 6) return 0;
  node->as.heading.level = level;
  return 1;
}
```

### Return Conventions

- **0/1 for success/failure**: Setter functions return 1 on success, 0 on failure
- **NULL for not found**: Lookup functions return NULL when the item doesn't exist
- **Assertion for invariants**: Internal invariants use `assert()`:
  ```c
  assert(googled_node->type == CMARK_NODE_DOCUMENT);
  ```

## Header Guard Style

```c
#ifndef CMARK_NODE_H
#define CMARK_NODE_H
// ...
#endif
```

Guards use `CMARK_` prefix + uppercase filename + `_H`.

## Include Patterns

### Public Headers
```c
#include "cmark.h"  // Always first — provides all public types
```

### Private Headers
```c
#include "node.h"      // Internal node definitions
#include "parser.h"    // Parser internals
#include "buffer.h"    // cmark_strbuf
#include "chunk.h"     // cmark_chunk
#include "references.h" // Reference map
#include "utf8.h"      // UTF-8 utilities
#include "scanners.h"  // re2c-generated scanners
```

### System Headers
```c
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
```

## Inline Functions

The `CMARK_INLINE` macro abstracts compiler-specific inline syntax:
```c
#ifdef _MSC_VER
#define CMARK_INLINE __forceinline
#else
#define CMARK_INLINE __inline__
#endif
```

Used for small, hot-path functions in headers:
```c
static CMARK_INLINE void cmark_chunk_free(cmark_mem *mem, cmark_chunk *c) { ... }
static CMARK_INLINE cmark_chunk cmark_chunk_dup(...) { ... }
```

## Memory Ownership Patterns

### Owning vs Non-Owning

The `cmark_chunk` type makes ownership explicit:
- `alloc > 0` → the chunk owns the memory and must free it
- `alloc == 0` → the chunk borrows memory from elsewhere

### Transfer of Ownership

`cmark_strbuf_detach()` transfers ownership from a strbuf to the caller:
```c
unsigned char *data = cmark_strbuf_detach(&buf);
// Caller now owns 'data' and must free it
```

### Consistent Cleanup

Free functions null out pointers after freeing:
```c
static CMARK_INLINE void cmark_chunk_free(cmark_mem *mem, cmark_chunk *c) {
  if (c->alloc)
    mem->free((void *)c->data);
  c->data = NULL;      // NULL after free
  c->alloc = 0;
  c->len = 0;
}
```

## Iterative vs Recursive Patterns

The codebase avoids recursion for tree operations to prevent stack overflow on deeply nested input:

### Iterative Tree Destruction
`S_free_nodes()` uses sibling-list splicing instead of recursion:
```c
// Splice children into sibling chain
if (e->first_child) {
  cmark_node *last = e->last_child;
  last->next = e->next;
  e->next = e->first_child;
}
```

### Iterator-Based Traversal
All rendering uses `cmark_iter` instead of recursive `render_children()`:
```c
while ((ev_type = cmark_iter_next(iter)) != CMARK_EVENT_DONE) {
  cur = cmark_iter_get_node(iter);
  S_render_node(cur, ev_type, &state, options);
}
```

## Type Size Definitions

```c
typedef int32_t bufsize_t;
```

Buffer sizes use `int32_t` (not `size_t`) to:
1. Allow negative values for error signaling
2. Keep node structs compact (32-bit vs 64-bit on LP64)
3. Limit maximum allocation to 2GB (adequate for text processing)

## Bitmask Patterns

Option flags use single-bit constants:
```c
#define CMARK_OPT_SOURCEPOS      (1 << 1)
#define CMARK_OPT_HARDBREAKS     (1 << 2)
#define CMARK_OPT_UNSAFE         (1 << 17)
#define CMARK_OPT_NOBREAKS       (1 << 4)
#define CMARK_OPT_VALIDATE_UTF8  (1 << 9)
#define CMARK_OPT_SMART          (1 << 10)
```

Tested with bitwise AND:
```c
if (options & CMARK_OPT_SOURCEPOS) { ... }
```

Combined with bitwise OR:
```c
int options = CMARK_OPT_SOURCEPOS | CMARK_OPT_SMART;
```

## Leaf Mask Pattern

`S_is_leaf()` in `iterator.c` uses a bitmask for O(1) node-type classification:
```c
static const int S_leaf_mask =
    (1 << CMARK_NODE_HTML_BLOCK) | (1 << CMARK_NODE_THEMATIC_BREAK) |
    (1 << CMARK_NODE_CODE_BLOCK) | (1 << CMARK_NODE_TEXT) | ...;

static bool S_is_leaf(cmark_node *node) {
  return ((1 << node->type) & S_leaf_mask) != 0;
}
```

This is more efficient than a switch statement for a simple boolean classification.

## Cross-References

- [architecture.md](architecture.md) — Design decisions
- [memory-management.md](memory-management.md) — Allocator patterns
- [public-api.md](public-api.md) — Public API naming