Skip to content

Commit a47827c

Browse files
kddnewtonmatzbot
authored andcommitted
[ruby/prism] Provide a single-entry cache on parser for avoiding constant hashes
ruby/prism@56cdcbbb8c
1 parent 203a03e commit a47827c

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

prism/internal/parser.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,18 @@ struct pm_parser_t {
582582
*/
583583
uint32_t node_id;
584584

585+
/*
586+
* A single-entry cache for pm_parser_constant_id_raw. Avoids redundant
587+
* constant pool lookups when the same token is resolved multiple times
588+
* (e.g., once during lexing for local variable detection, and again
589+
* during parsing for node creation).
590+
*/
591+
struct {
592+
const uint8_t *start;
593+
const uint8_t *end;
594+
pm_constant_id_t id;
595+
} constant_cache;
596+
585597
/* The current state of the lexer. */
586598
pm_lex_state_t lex_state;
587599

prism/prism.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1120,7 +1120,19 @@ pm_locals_order(pm_parser_t *parser, pm_locals_t *locals, pm_constant_id_list_t
11201120
*/
11211121
static PRISM_INLINE pm_constant_id_t
11221122
pm_parser_constant_id_raw(pm_parser_t *parser, const uint8_t *start, const uint8_t *end) {
1123-
return pm_constant_pool_insert_shared(&parser->metadata_arena, &parser->constant_pool, start, (size_t) (end - start));
1123+
/* Fast path: if this is the same token as the last lookup (same pointer
1124+
* range), return the cached result. */
1125+
if (start == parser->constant_cache.start && end == parser->constant_cache.end) {
1126+
return parser->constant_cache.id;
1127+
}
1128+
1129+
pm_constant_id_t id = pm_constant_pool_insert_shared(&parser->metadata_arena, &parser->constant_pool, start, (size_t) (end - start));
1130+
1131+
parser->constant_cache.start = start;
1132+
parser->constant_cache.end = end;
1133+
parser->constant_cache.id = id;
1134+
1135+
return id;
11241136
}
11251137

11261138
/**

0 commit comments

Comments
 (0)