Commit da8e9147

da8e9147f743Merged

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

Description

Implement regex hex-digit shorthands \h and \H

The regex engine recognized \d/\D, \w/\W and \s/\S but not the hex-digit shorthands. \h ([0-9a-fA-F]) compiled to nothing and never matched; \H had no handler and effectively always "matched", inverting the intended non-hex-digit semantics.

Add \h and \H to class_add_shorthand and to both dispatch sites (top-level and inside [...]). \h builds the positive hex-digit set; \H builds the explicit complement set. Both are emitted as RE_CLASS at the top level so \H carries its own complement bits rather than being routed through the uppercase->RE_NCLASS auto-path, which keeps the [...] and top-level forms consistent.

Closes #1349

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
da8e9147f743
Parent
ab16f03537b8

lib/regexp/re_compile.cmodifiedView file

@@ -228,6 +228,26 @@
228228 }
229229 cc->utf8_any = TRUE;
230230 break;
231+ case 'h':
232+ /* hex digit: [0-9a-fA-F] */
233+ class_set_range(cc, '0', '9');
234+ class_set_range(cc, 'a', 'f');
235+ class_set_range(cc, 'A', 'F');
236+ break;
237+ case 'H':
238+ /* non-hex-digit: complement of [0-9a-fA-F]. Built as an explicit
239+ positive set so the top-level dispatcher can emit it as RE_CLASS
240+ and the `[...]` path can add it directly -- both contexts need the
241+ complement bits present (the uppercase->RE_NCLASS auto-route used
242+ by \D/\W/\S is deliberately bypassed for \H). */
243+ for (int i = 0; i < 128; i++) {
244+ mrb_bool is_hex = (i >= '0' && i <= '9') ||
245+ (i >= 'a' && i <= 'f') ||
246+ (i >= 'A' && i <= 'F');
247+ if (!is_hex) class_set_bit(cc, (uint8_t)i);
248+ }
249+ cc->utf8_any = TRUE;
250+ break;
231251 }
232252 }
233253
@@ -336,7 +356,8 @@
336356 intact. */
337357 if (peek(c) == '\\') {
338358 int esc = (c->p + 1 < c->src_end) ? (uint8_t)c->p[1] : -1;
339- if (esc == 'd' || esc == 'D' || esc == 'w' || esc == 'W' || esc == 's' || esc == 'S') {
359+ if (esc == 'd' || esc == 'D' || esc == 'w' || esc == 'W' ||
360+ esc == 's' || esc == 'S' || esc == 'h' || esc == 'H') {
340361 next_char(c); /* '\\' */
341362 next_char(c); /* spec */
342363 class_add_shorthand(cc, esc);
@@ -659,6 +680,15 @@
659680 class_add_shorthand(&c->classes[id], ch);
660681 emit(c, (ch >= 'A' && ch <= 'Z') ? RE_NCLASS : RE_CLASS, (uint8_t)id, 0);
661682 }
683+ else if (ch == 'h' || ch == 'H') {
684+ /* \h / \H both carry their full positive set (hex digits /
685+ non-hex-digits), so emit RE_CLASS for both rather than routing
686+ \H through the uppercase RE_NCLASS path. */
687+ next_char(c);
688+ uint16_t id = add_class(c);
689+ class_add_shorthand(&c->classes[id], ch);
690+ emit(c, RE_CLASS, (uint8_t)id, 0);
691+ }
662692 else if (ch == 'A') {
663693 next_char(c);
664694 emit(c, RE_BOT, 0, 0);