Commit 8b8859c4

8b8859c42730Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified

Description

Regex literals bound to a constant

A constant assigned a regex literal (PATTERN = /re/, optionally .freeze, possibly namespaced) now resolves at compile time to that literal's precompiled pattern, so gsub/sub/scan/split with the constant dispatch to the engine. The constant is not stored as a runtime value (its write is a no-op and analyze does not intern it). re_has_captures is NULL-guarded and capture detection resolves the constant's source.

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
8b8859c42730
Parent
83f93d0cd5b3

src/analyze.cmodifiedView file

@@ -1316,8 +1316,15 @@
13161316 }
13171317 else if (!strcmp(ty, "ConstantWriteNode")) {
13181318 const char *nm = nt_str(nt, id, "name");
1319+ /* a constant bound to a regex literal is resolved at compile time to a
1320+ precompiled pattern, not stored as a runtime value */
1321+ int rv = nt_ref(nt, id, "value");
1322+ if (rv >= 0 && nt_type(nt, rv) && !strcmp(nt_type(nt, rv), "CallNode") &&
1323+ nt_str(nt, rv, "name") && !strcmp(nt_str(nt, rv, "name"), "freeze"))
1324+ rv = nt_ref(nt, rv, "receiver");
1325+ int is_regex_const = rv >= 0 && nt_type(nt, rv) && !strcmp(nt_type(nt, rv), "RegularExpressionNode");
13191326 /* a Struct/Data const names a class, not a value constant */
1320- if (nm && is_c_ident(nm) && comp_class_index(c, nm) < 0) {
1327+ if (nm && is_c_ident(nm) && comp_class_index(c, nm) < 0 && !is_regex_const) {
13211328 LocalVar *cv = comp_const_intern(c, nm);
13221329 /* `CONST = SomeClass.new(...)`: reads of CONST during the new()
13231330 (i.e. inside initialize or anything it calls) must raise