Skip to content

Commit 15906eb

Browse files
committed
fix(swift): keep the first parse when masking directives reads less
The conditional-compilation retry always kept the masked re-parse. When the dropped branch holds an `#error(...)` line inside a type body the re-parse reads less of the file: Alamofire Protected.swift went from 3 to 14 unreadable lines and lost its Protected initializer. The re-parse is now kept only when its error regions cover no more lines than those of the first parse. Counting regions instead would reject re-parses that split one large region into a few small ones; on swift-nio that gave back 1,312 of the recovered lines. Signed-off-by: Martin Vogel <[email protected]>
1 parent 8087c1c commit 15906eb

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

‎internal/cbm/cbm.c‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3382,6 +3382,21 @@ static const char *swift_mask_conditional_directives(CBMArena *a, TSNode root, c
33823382
return masked ? masked : source;
33833383
}
33843384

3385+
/* Lines the error regions of this tree cover; a region past the cap counts one. */
3386+
static uint64_t swift_error_lines(TSTree *tree, const char *source, int source_len) {
3387+
cbm_error_regions_t regions = {{0}, {0}, 0, 0};
3388+
cbm_collect_error_regions(ts_tree_root_node(tree), &regions, source, source_len);
3389+
uint64_t lines = (uint64_t)regions.dropped;
3390+
for (int i = 0; i < regions.count; i++) {
3391+
lines += regions.ends[i] - regions.starts[i] + SKIP_ONE;
3392+
}
3393+
return lines;
3394+
}
3395+
3396+
/* Masking can also make a file read worse: an `#error` line from a dropped
3397+
* branch stays in a type body. Keep the re-parse only when its error regions
3398+
* cover no more lines than the first parse's (#2061). Counting regions instead
3399+
* would reject a re-parse that splits one large region into a few small ones. */
33853400
static TSTree *swift_retry_conditional_parse(CBMArena *a, TSParser *parser, TSTree *tree,
33863401
CBMLanguage language, const char *source,
33873402
int source_len, TSParseOptions opts) {
@@ -3393,9 +3408,17 @@ static TSTree *swift_retry_conditional_parse(CBMArena *a, TSParser *parser, TSTr
33933408
if (masked == source) {
33943409
return tree;
33953410
}
3396-
ts_tree_delete(tree);
33973411
ts_parser_reset(parser);
3398-
return cbm_parse_source(parser, masked, (uint32_t)source_len, opts);
3412+
TSTree *retry = cbm_parse_source(parser, masked, (uint32_t)source_len, opts);
3413+
if (retry && swift_error_lines(retry, masked, source_len) <=
3414+
swift_error_lines(tree, source, source_len)) {
3415+
ts_tree_delete(tree);
3416+
return retry;
3417+
}
3418+
if (retry) {
3419+
ts_tree_delete(retry);
3420+
}
3421+
return tree;
33993422
}
34003423

34013424
/* Initial block for the per-file traversal scratch arena, chosen by measuring

0 commit comments

Comments
 (0)