Ruby 4.1.0dev (2026-11-26 revision a987e89fb6e5b61d905046ba86182898e56897f6)
comments.c
1#include "prism/internal/comments.h"
2
3#include "prism/internal/arena.h"
4#include "prism/internal/assert.h"
5#include "prism/internal/char.h"
6#include "prism/internal/memchr.h"
7#include "prism/internal/node.h"
8#include "prism/internal/parser.h"
9
10#include <string.h>
11
12/* The state used while walking the tree to find the owner of each comment. */
13typedef struct {
14 /*
15 * The arena for memory that is only needed during the walk, which is the
16 * scratch arena of the parser.
17 */
18 pm_arena_t *arena;
19
20 /* The start of the source that was parsed. */
21 const uint8_t *source;
22
23 /* The comments found while parsing, sorted by start offset. */
24 const pm_comment_t **comments;
25
26 /* The number of comments. */
27 uint32_t size;
28
29 /* The start offset of each comment. */
30 uint32_t *starts;
31
32 /*
33 * The result of the most recent search for the first comment after the end
34 * of a node. This is a hint to the search to avoid fully binary searching
35 * the comments list if possible.
36 */
37 uint32_t cursor;
38
39 /* The node each comment is attached to. */
40 const pm_node_t **attached;
41
42 /*
43 * A disjoint set over comment indices that maps each index to the next
44 * index at or after it that has not yet been claimed. It has one extra
45 * entry at the end that is never claimed, so that every lookup ends. This
46 * allows quickly finding the next unclaimed comment without having to check
47 * the state of each comment individually.
48 */
49 uint32_t *unclaimed;
50
51 /*
52 * A stack of nodes whose children are being visited. Each level of the
53 * walk pushes its children, visits them, then pops back to where it
54 * started.
55 */
56 struct {
57 const pm_node_t **nodes;
58 size_t size;
59 size_t capacity;
60 } stack;
62
63/*
64 * Insertion-sort the comments by start offset as we copy them from the list,
65 * then relink the list in source order. Usually only heredoc comments need
66 * to move.
67 */
68static const pm_comment_t **
69pm_comments_sort(pm_parser_t *parser, uint32_t size) {
70 pm_comment_t **comments = PM_ARENA_ALLOC_ARRAY(&parser->metadata_arena, pm_comment_t *, size);
71
72 uint32_t index = 0;
73 for (pm_list_node_t *node = parser->comment_list.head; node != NULL; node = node->next) {
74 pm_comment_t *comment = (pm_comment_t *) node;
75 uint32_t position = index++;
76 while (position > 0 && comments[position - 1]->location.start > comment->location.start) {
77 comments[position] = comments[position - 1];
78 position--;
79 }
80 comments[position] = comment;
81 }
82
83 for (index = 0; index + 1 < size; index++) {
84 comments[index]->node.next = &comments[index + 1]->node;
85 }
86
87 comments[size - 1]->node.next = NULL;
88 parser->comment_list.head = &comments[0]->node;
89 parser->comment_list.tail = &comments[size - 1]->node;
90
91 return (const pm_comment_t **) comments;
92}
93
94/*
95 * Return the index of the first comment in [left, right) that starts at or
96 * after the given offset, or right if there is none.
97 */
98static uint32_t
99pm_comments_lower_bound(const pm_comments_walk_t *walk, uint32_t left, uint32_t right, uint32_t offset) {
100 while (left < right) {
101 uint32_t middle = left + (right - left) / 2;
102
103 if (walk->starts[middle] < offset) {
104 left = middle + 1;
105 } else {
106 right = middle;
107 }
108 }
109
110 return left;
111}
112
113/*
114 * Return the index of the first comment that starts at or after the given
115 * offset, or the number of comments if there is none. This gallops outward
116 * from the previous result to find a range to search, so that a run of nearby
117 * offsets costs a constant number of comparisons each.
118 */
119static uint32_t
120pm_comments_seek(pm_comments_walk_t *walk, uint32_t offset) {
121 const uint32_t *starts = walk->starts;
122
123 uint32_t size = walk->size;
124 uint32_t cursor = walk->cursor;
125 uint32_t left;
126 uint32_t right;
127 uint32_t step = 1;
128
129 if (cursor == size || starts[cursor] >= offset) {
130 /*
131 * The answer is at or before the cursor. Widen the range backward
132 * until the comment before it starts before the offset.
133 */
134 right = cursor;
135 left = cursor;
136
137 while (left > 0 && starts[left - 1] >= offset) {
138 right = left - 1;
139 left = (left - 1 > step) ? left - 1 - step : 0;
140 step *= 2;
141 }
142 } else {
143 /*
144 * The answer is after the cursor. Widen the range forward until it
145 * ends at a comment that starts at or after the offset.
146 */
147 left = cursor + 1;
148 right = left;
149
150 while (right < size && starts[right] < offset) {
151 left = right + 1;
152 right = (size - left > step) ? left + step : size;
153 step *= 2;
154 }
155 }
156
157 walk->cursor = pm_comments_lower_bound(walk, left, right, offset);
158 return walk->cursor;
159}
160
161/*
162 * The first comment index at or after the given index that has not yet been
163 * claimed, compressing the path along the way.
164 */
165static uint32_t
166pm_comments_unclaimed(pm_comments_walk_t *walk, uint32_t index) {
167 uint32_t *unclaimed = walk->unclaimed;
168
169 while (unclaimed[index] != index) {
170 unclaimed[index] = unclaimed[unclaimed[index]];
171 index = unclaimed[index];
172 }
173
174 return index;
175}
176
177/*
178 * Return the earliest offset before the given one from which the source up to
179 * it holds only whitespace and comments. Any comment that starts at or after
180 * the returned offset is separated from the given offset by only whitespace and
181 * other comments.
182 */
183static uint32_t
184pm_comments_blank_before(const pm_comments_walk_t *walk, uint32_t offset) {
185 uint32_t index = pm_comments_lower_bound(walk, 0, walk->size, offset);
186
187 while (true) {
188 offset -= (uint32_t) pm_strrspn_whitespace(walk->source, (ptrdiff_t) offset);
189 if (index == 0) return offset;
190
191 /* An embedded document's location includes its trailing newline, so
192 * the whitespace that was just skipped can end inside a comment. */
193 const pm_location_t *location = &walk->comments[index - 1]->location;
194 if (location->start >= offset || PM_LOCATION_END(location) < offset) return offset;
195
196 offset = location->start;
197 index--;
198 }
199}
200
201/*
202 * Return the latest offset after the given one, and no later than the given
203 * end, up to which the source from the given offset holds only whitespace and
204 * comments. Any comment that ends at or before the returned offset is
205 * separated from the given offset by only whitespace and other comments.
206 */
207static uint32_t
208pm_comments_blank_after(const pm_comments_walk_t *walk, uint32_t offset, uint32_t end) {
209 uint32_t index = pm_comments_lower_bound(walk, 0, walk->size, offset);
210
211 while (true) {
212 offset += (uint32_t) pm_strspn_whitespace(walk->source + offset, (ptrdiff_t) end - (ptrdiff_t) offset);
213 if (index == walk->size || walk->starts[index] != offset) return offset;
214
215 offset = PM_LOCATION_END(&walk->comments[index]->location);
216 index++;
217 }
218}
219
220/*
221 * Push a child node onto the walk stack without descending into it. The walk
222 * descends itself, so that it can visit children in source order and handle
223 * each node after all of its descendants.
224 */
226pm_comments_push(const pm_node_t *node, void *data) {
227 pm_comments_walk_t *walk = (pm_comments_walk_t *) data;
228
229 if (walk->stack.size == walk->stack.capacity) {
230 size_t capacity = walk->stack.capacity == 0 ? 64 : walk->stack.capacity * 2;
231 const pm_node_t **nodes = PM_ARENA_ALLOC_ARRAY(walk->arena, const pm_node_t *, capacity);
232 if (walk->stack.size > 0) memcpy((void *) nodes, (const void *) walk->stack.nodes, sizeof(pm_node_t *) * walk->stack.size);
233
234 walk->stack.nodes = nodes;
235 walk->stack.capacity = capacity;
236 }
237
238 walk->stack.nodes[walk->stack.size++] = node;
239 return PM_VISIT_SKIP;
240}
241
242/*
243 * Visit the given node and its descendants in post-order, attaching comments as
244 * the nodes are visited.
245 */
246static void
247pm_comments_visit(pm_comments_walk_t *walk, const pm_node_t *node) {
248 /* First, push all of the children of this node onto the stack. */
249 size_t base = walk->stack.size;
250 pm_visit_child_nodes(node, pm_comments_push, walk);
251 size_t top = walk->stack.size;
252
253 /* Next, in-place sort the children by their starting location. */
254 for (size_t index = base + 1; index < top; index++) {
255 const pm_node_t *child = walk->stack.nodes[index];
256 size_t insert = index;
257
258 while (insert > base && walk->stack.nodes[insert - 1]->location.start > child->location.start) {
259 walk->stack.nodes[insert] = walk->stack.nodes[insert - 1];
260 insert--;
261 }
262
263 walk->stack.nodes[insert] = child;
264 }
265
266 /* Next, visit all of the children so that they can claim comments. */
267 for (size_t index = base; index < top; index++) {
268 pm_comments_visit(walk, walk->stack.nodes[index]);
269 }
270
271 uint32_t start = node->location.start;
272 uint32_t end = PM_LOCATION_END(&node->location);
273 uint32_t after = pm_comments_seek(walk, end);
274
275 /* If this node is followed by a comment on the same line, attach it if
276 * appropriate. Appropriate in this case means if no other node has claimed
277 * it or if we are closer in distance or equal in distance to the current
278 * claimant. */
279 if (
280 after < walk->size &&
281 !PM_NODE_TYPE_P(node, PM_PROGRAM_NODE) &&
282 !PM_NODE_TYPE_P(node, PM_STATEMENTS_NODE) &&
283 (node->location.length == 0 || walk->source[end - 1] != '\n')
284 ) {
285 uint32_t comment_start = walk->starts[after];
286
287 if (pm_memchr(walk->source + end, '\n', comment_start - end) == NULL) {
288 const pm_node_t *attached = walk->attached[after];
289 uint32_t attached_end = attached == NULL ? 0 : PM_LOCATION_END(&attached->location);
290
291 if (end >= attached_end || attached_end > comment_start) {
292 walk->attached[after] = node;
293 }
294 }
295 }
296
297 /* Grab up the remaining comments within the range of this node that were
298 * not claimed by any of its descendants. A comment that is separated by
299 * only whitespace and other comments from a statements node child, either
300 * the child after it or the child before it, is attached to the statements
301 * instead, so that the comments before the first statement and after the
302 * last statement in a body belong to the body. The claimed comments are in
303 * order, so the children around each one are found by moving forward
304 * through the sorted children. */
305 if (after > 0 && walk->starts[after - 1] >= start) {
306 uint32_t index = pm_comments_unclaimed(walk, pm_comments_lower_bound(walk, 0, after, start));
307 size_t child_index = base;
308
309 /* The boundaries around the statements children are each found once,
310 * when the first comment that needs them is reached, since the
311 * comments that follow reach the same children. */
312 const pm_node_t *leading = NULL;
313 uint32_t leading_boundary = 0;
314 const pm_node_t *trailing = NULL;
315 uint32_t trailing_boundary = 0;
316
317 while (index < after && PM_LOCATION_END(&walk->comments[index]->location) <= end) {
318 if (walk->attached[index] == NULL) {
319 uint32_t comment_end = PM_LOCATION_END(&walk->comments[index]->location);
320 const pm_node_t *attached = node;
321
322 while (child_index < top && walk->stack.nodes[child_index]->location.start < comment_end) child_index++;
323
324 if (child_index < top) {
325 const pm_node_t *child = walk->stack.nodes[child_index];
326
327 if (PM_NODE_TYPE_P(child, PM_STATEMENTS_NODE)) {
328 if (child != leading) {
329 leading = child;
330 leading_boundary = pm_comments_blank_before(walk, child->location.start);
331 }
332
333 if (walk->starts[index] >= leading_boundary) attached = child;
334 }
335 }
336
337 if (attached == node && child_index > base) {
338 const pm_node_t *child = walk->stack.nodes[child_index - 1];
339
340 /* A rescue clause ends at its last statement rather than at
341 * the keyword that follows it, and the first clause in a
342 * body contains the clauses after it. So a comment after
343 * the statements of the last clause follows the first
344 * clause, and belongs to the statements of the last. */
345 if (PM_NODE_TYPE_P(child, PM_RESCUE_NODE)) {
346 const pm_rescue_node_t *rescue = (const pm_rescue_node_t *) child;
347 while (rescue->subsequent != NULL) rescue = rescue->subsequent;
348 child = (const pm_node_t *) rescue->statements;
349 }
350
351 if (child != NULL && PM_NODE_TYPE_P(child, PM_STATEMENTS_NODE) && PM_LOCATION_END(&child->location) <= walk->starts[index]) {
352 if (child != trailing) {
353 trailing = child;
354 trailing_boundary = pm_comments_blank_after(walk, PM_LOCATION_END(&child->location), end);
355 }
356
357 if (comment_end <= trailing_boundary) attached = child;
358 }
359 }
360
361 walk->attached[index] = attached;
362 }
363
364 walk->unclaimed[index] = index + 1;
365 index = pm_comments_unclaimed(walk, index + 1);
366 }
367 }
368
369 /* Truncate the stack back to the base size. */
370 walk->stack.size = base;
371}
372
373/*
374 * Sort the parser's comment list in place by start offset, then assign every
375 * comment to the node that owns it. A comment is owned by:
376 *
377 * 1. the node that ends latest on the comment's line before the comment starts,
378 * with ties going to the node that is higher in the tree;
379 * 2. otherwise, the innermost node whose location contains the comment, or the
380 * statements node child of that node if only whitespace and other comments
381 * come between the statements and the comment, on either side;
382 * 3. otherwise, the top-level statements node of the program.
383 */
384void
385pm_comments_attach(pm_parser_t *parser, const pm_node_t *root) {
386 PRISM_ASSERT(PM_NODE_TYPE_P(root, PM_PROGRAM_NODE));
387
388 uint32_t size = (uint32_t) parser->comment_list.size;
389 if (size == 0) return;
390
391 pm_arena_t *arena = &parser->scratch_arena;
392 pm_comments_walk_t walk = {
393 .arena = arena,
394 .source = parser->start,
395 .comments = pm_comments_sort(parser, size),
396 .size = size,
397 .starts = PM_ARENA_ALLOC_ARRAY(arena, uint32_t, size),
398 .attached = PM_ARENA_ZALLOC_ARRAY(arena, const pm_node_t *, size),
399 .unclaimed = PM_ARENA_ALLOC_ARRAY(arena, uint32_t, size + 1)
400 };
401
402 for (uint32_t index = 0; index < size; index++) walk.starts[index] = walk.comments[index]->location.start;
403 for (uint32_t index = 0; index <= size; index++) walk.unclaimed[index] = index;
404
405 pm_comments_visit(&walk, root);
406
407 /*
408 * Attach comments that no node attached to during the walk to the
409 * top-level statements, then group the comments by node with a counting
410 * sort. Comments are placed in sorted order, so each node's comments stay
411 * sorted by start offset.
412 */
413 const pm_node_t *statements = (const pm_node_t *) ((const pm_program_node_t *) root)->statements;
414 uint32_t ranges_size = 0;
415
416 for (uint32_t index = 0; index < size; index++) {
417 if (walk.attached[index] == NULL) walk.attached[index] = statements;
418
419 uint32_t node_id = walk.attached[index]->node_id;
420 PRISM_ASSERT(node_id <= parser->node_id);
421 if (node_id >= ranges_size) ranges_size = node_id + 1;
422 }
423
424 /* The ranges only extend to the largest node id that owns a comment, since
425 * none of the nodes after it own any. */
426 pm_comment_range_t *ranges = PM_ARENA_ZALLOC_ARRAY(&parser->metadata_arena, pm_comment_range_t, ranges_size);
427 uint32_t *attachments = PM_ARENA_ALLOC_ARRAY(&parser->metadata_arena, uint32_t, size);
428
429 for (uint32_t index = 0; index < size; index++) {
430 ranges[walk.attached[index]->node_id].length++;
431 }
432
433 uint32_t offset = 0;
434 for (uint32_t index = 0; index < ranges_size; index++) {
435 ranges[index].index = offset;
436 offset += ranges[index].length;
437 ranges[index].length = 0;
438 }
439
440 for (uint32_t index = 0; index < size; index++) {
441 pm_comment_range_t *range = &ranges[walk.attached[index]->node_id];
442 attachments[range->index + range->length++] = index;
443 }
444
445 parser->comment_attachments = (pm_comment_attachments_t) {
446 .comments = walk.comments,
447 .attachments = attachments,
448 .ranges = ranges,
449 .ranges_size = ranges_size
450 };
451}
comment_range comments(const pm_parser_t *parser PRISM_LIFETIMEBOUND) noexcept
The comments found while parsing, in source order.
Definition parser.hpp:257
pm_visit_result_t
The value returned by a visitor callback, which determines where the walk goes next.
Definition node.h:49
@ PM_VISIT_SKIP
Continue the walk without visiting this node's children.
Definition node.h:51
The comments owned by a node, as a slice of the comment attachments of the parser that produced it.
Definition comments.h:34
uint32_t index
The index of the first attachment owned by the node.
Definition comments.h:36
uint32_t length
The number of attachments owned by the node.
Definition comments.h:39
This struct represents a slice in the source code, defined by an offset and a length.
Definition ast.h:579
uint32_t start
The offset of the location from the start of the source.
Definition ast.h:581
uint32_t length
The length of the location.
Definition ast.h:584
uint32_t node_id
The unique identifier for this node, which is deterministic based on the source.
Definition ast.h:1110
pm_location_t location
This is the location of the node in the source.
Definition ast.h:1116
PM_NODE_ALIGNAS struct pm_statements_node * statements
RescueNode::statements.
Definition ast.h:7167
PM_NODE_ALIGNAS struct pm_rescue_node * subsequent
RescueNode::subsequent.
Definition ast.h:7172