12#include "ruby/internal/config.h"
19#include "internal/bignum.h"
20#include "internal/encoding.h"
21#include "internal/error.h"
22#include "internal/gc.h"
23#include "internal/hash.h"
24#include "internal/imemo.h"
25#include "internal/re.h"
26#include "internal/string.h"
27#include "internal/object.h"
28#include "internal/ractor.h"
29#include "internal/variable.h"
35#include "ractor_core.h"
54#define KCODE_FIXED FL_USER4
55#define REG_ENCODING_NONE FL_USER6
65#define MATCH_BUSY FL_USER0
69typedef char onig_errmsg_buffer[ONIG_MAX_ERROR_MESSAGE_LEN];
70#define errcpy(err, msg) strlcpy((err), (msg), ONIG_MAX_ERROR_MESSAGE_LEN)
73static const char casetable[] = {
74 '\000',
'\001',
'\002',
'\003',
'\004',
'\005',
'\006',
'\007',
75 '\010',
'\011',
'\012',
'\013',
'\014',
'\015',
'\016',
'\017',
76 '\020',
'\021',
'\022',
'\023',
'\024',
'\025',
'\026',
'\027',
77 '\030',
'\031',
'\032',
'\033',
'\034',
'\035',
'\036',
'\037',
79 '\040',
'\041',
'\042',
'\043',
'\044',
'\045',
'\046',
'\047',
81 '\050',
'\051',
'\052',
'\053',
'\054',
'\055',
'\056',
'\057',
83 '\060',
'\061',
'\062',
'\063',
'\064',
'\065',
'\066',
'\067',
85 '\070',
'\071',
'\072',
'\073',
'\074',
'\075',
'\076',
'\077',
87 '\100',
'\141',
'\142',
'\143',
'\144',
'\145',
'\146',
'\147',
89 '\150',
'\151',
'\152',
'\153',
'\154',
'\155',
'\156',
'\157',
91 '\160',
'\161',
'\162',
'\163',
'\164',
'\165',
'\166',
'\167',
93 '\170',
'\171',
'\172',
'\133',
'\134',
'\135',
'\136',
'\137',
95 '\140',
'\141',
'\142',
'\143',
'\144',
'\145',
'\146',
'\147',
97 '\150',
'\151',
'\152',
'\153',
'\154',
'\155',
'\156',
'\157',
99 '\160',
'\161',
'\162',
'\163',
'\164',
'\165',
'\166',
'\167',
101 '\170',
'\171',
'\172',
'\173',
'\174',
'\175',
'\176',
'\177',
102 '\200',
'\201',
'\202',
'\203',
'\204',
'\205',
'\206',
'\207',
103 '\210',
'\211',
'\212',
'\213',
'\214',
'\215',
'\216',
'\217',
104 '\220',
'\221',
'\222',
'\223',
'\224',
'\225',
'\226',
'\227',
105 '\230',
'\231',
'\232',
'\233',
'\234',
'\235',
'\236',
'\237',
106 '\240',
'\241',
'\242',
'\243',
'\244',
'\245',
'\246',
'\247',
107 '\250',
'\251',
'\252',
'\253',
'\254',
'\255',
'\256',
'\257',
108 '\260',
'\261',
'\262',
'\263',
'\264',
'\265',
'\266',
'\267',
109 '\270',
'\271',
'\272',
'\273',
'\274',
'\275',
'\276',
'\277',
110 '\300',
'\301',
'\302',
'\303',
'\304',
'\305',
'\306',
'\307',
111 '\310',
'\311',
'\312',
'\313',
'\314',
'\315',
'\316',
'\317',
112 '\320',
'\321',
'\322',
'\323',
'\324',
'\325',
'\326',
'\327',
113 '\330',
'\331',
'\332',
'\333',
'\334',
'\335',
'\336',
'\337',
114 '\340',
'\341',
'\342',
'\343',
'\344',
'\345',
'\346',
'\347',
115 '\350',
'\351',
'\352',
'\353',
'\354',
'\355',
'\356',
'\357',
116 '\360',
'\361',
'\362',
'\363',
'\364',
'\365',
'\366',
'\367',
117 '\370',
'\371',
'\372',
'\373',
'\374',
'\375',
'\376',
'\377',
120# error >>> "You lose. You will need a translation table for your character set." <<<
124rb_hrtime_t rb_reg_match_time_limit = 0;
129 const unsigned char *p1 = x, *p2 = y;
133 if ((tmp = casetable[(
unsigned)*p1++] - casetable[(
unsigned)*p2++]))
139#if defined(HAVE_MEMMEM) && !defined(__APPLE__)
141rb_memsearch_ss(
const unsigned char *xs,
rb_len_t m,
const unsigned char *ys,
rb_len_t n)
143 const unsigned char *y;
145 if ((y = memmem(ys, n, xs, m)) != NULL)
152rb_memsearch_ss(
const unsigned char *xs,
rb_len_t m,
const unsigned char *ys,
rb_len_t n)
154 const unsigned char *x = xs, *xe = xs + m;
155 const unsigned char *y = ys, *ye = ys + n;
156#define VALUE_MAX ((VALUE)~(VALUE)0)
160 rb_bug(
"!!too long pattern string!!");
162 if (!(y = memchr(y, *x, n - m + 1)))
166 for (hx = *x++, hy = *y++; x < xe; ++x, ++y) {
186rb_memsearch_qs(
const unsigned char *xs,
rb_len_t m,
const unsigned char *ys,
rb_len_t n)
188 const unsigned char *x = xs, *xe = xs + m;
189 const unsigned char *y = ys;
190 VALUE i, qstable[256];
193 for (i = 0; i < 256; ++i)
196 qstable[*x] = xe - x;
198 for (; y + m <= ys + n; y += *(qstable + y[m])) {
199 if (*xs == *y && memcmp(xs, y, m) == 0)
205static inline unsigned int
206rb_memsearch_qs_utf8_hash(
const unsigned char *x,
const unsigned char *e)
208 register const unsigned int mix = 8353;
209 register unsigned int h = *x;
213 else if (e - x < (h < 0xE0 ? 2 : h < 0xF0 ? 3 : 4)) {
237 return (
unsigned char)h;
241rb_memsearch_qs_utf8(
const unsigned char *xs,
rb_len_t m,
const unsigned char *ys,
rb_len_t n)
243 const unsigned char *x = xs, *xe = xs + m;
244 const unsigned char *y = ys;
245 VALUE i, qstable[512];
248 for (i = 0; i < 512; ++i) {
251 for (; x < xe; ++x) {
252 qstable[rb_memsearch_qs_utf8_hash(x, xe)] = xe - x;
255 for (; y + m <= ys + n; y += qstable[rb_memsearch_qs_utf8_hash(y+m, ys+n)]) {
256 if (*xs == *y && memcmp(xs, y, m) == 0)
263rb_memsearch_with_char_size(
const unsigned char *xs,
rb_len_t m,
const unsigned char *ys,
rb_len_t n,
int char_size)
265 const unsigned char *x = xs, x0 = *xs, *y = ys;
267 for (n -= m; n >= 0; n -= char_size, y += char_size) {
268 if (x0 == *y && memcmp(x+1, y+1, m-1) == 0)
275rb_memsearch_wchar(
const unsigned char *xs,
rb_len_t m,
const unsigned char *ys,
rb_len_t n)
277 return rb_memsearch_with_char_size(xs, m, ys, n, 2);
281rb_memsearch_qchar(
const unsigned char *xs,
rb_len_t m,
const unsigned char *ys,
rb_len_t n)
283 return rb_memsearch_with_char_size(xs, m, ys, n, 4);
289 const unsigned char *x = x0, *y = y0;
291 if (m > n)
return -1;
293 return memcmp(x0, y0, m) == 0 ? 0 : -1;
299 const unsigned char *ys = memchr(y, *x, n);
306 else if (LIKELY(rb_enc_mbminlen(enc) == 1)) {
308 return rb_memsearch_ss(x0, m, y0, n);
311 return rb_memsearch_qs_utf8(x0, m, y0, n);
314 else if (LIKELY(rb_enc_mbminlen(enc) == 2)) {
315 return rb_memsearch_wchar(x0, m, y0, n);
317 else if (LIKELY(rb_enc_mbminlen(enc) == 4)) {
318 return rb_memsearch_qchar(x0, m, y0, n);
320 return rb_memsearch_qs(x0, m, y0, n);
330 val = ONIG_OPTION_IGNORECASE;
333 val = ONIG_OPTION_EXTEND;
336 val = ONIG_OPTION_MULTILINE;
345enum { OPTBUF_SIZE = 4 };
348option_to_str(
char str[OPTBUF_SIZE],
int options)
351 if (options & ONIG_OPTION_MULTILINE) *p++ =
'm';
352 if (options & ONIG_OPTION_IGNORECASE) *p++ =
'i';
353 if (options & ONIG_OPTION_EXTEND) *p++ =
'x';
366 return (*option = ARG_ENCODING_NONE);
368 *kcode = ENCINDEX_EUC_JP;
371 *kcode = ENCINDEX_Windows_31J;
378 return (*option = char_to_option(c));
380 *option = ARG_ENCODING_FIXED;
385reg_initialized_p(
VALUE re)
391rb_reg_check(
VALUE re)
393 if (!reg_initialized_p(re)) {
400 rb_encoding *enc, rb_encoding *resenc,
int term)
402 const char *p, *pend;
407 p = s; pend = p +
len;
408 rb_str_coderange_scan_restartable(p, pend, enc, &cr);
411 c = rb_enc_ascget(p, pend, &clen, enc);
414 p += mbclen(p, pend, enc);
438 int unicode_p = rb_enc_unicode_p(enc);
441 c = rb_enc_ascget(p, pend, &clen, enc);
442 if (c ==
'\\' && p+clen < pend) {
443 int n = clen + mbclen(p+clen, pend, enc);
449 clen = rb_enc_precise_mbclen(p, pend, enc);
451 c = (
unsigned char)*p;
456 unsigned int c = rb_enc_mbc_to_codepoint(p, pend, enc);
457 rb_str_buf_cat_escaped_char(str, c, unicode_p);
464 else if (c == term) {
472 else if (!rb_enc_isspace(c, enc)) {
476 snprintf(b,
sizeof(b),
"\\x%02X", c);
490 rb_encoding *enc = rb_enc_get(re);
495 if (re && rb_enc_asciicompat(enc)) {
496 rb_enc_copy(str, re);
503 rb_reg_expr_str(str, RSTRING_PTR(src_str), RSTRING_LEN(src_str), enc, resenc,
'/');
508 char opts[OPTBUF_SIZE];
510 if (*option_to_str(opts,
RREGEXP_PTR(re)->options))
512 if (
RBASIC(re)->flags & REG_ENCODING_NONE)
538rb_reg_source(
VALUE re)
559rb_reg_inspect(
VALUE re)
561 if (!reg_initialized_p(re)) {
564 return rb_reg_desc(re);
567static VALUE rb_reg_str_with_term(
VALUE re,
int term);
599 return rb_reg_str_with_term(re,
'/');
612#ifdef ONIG_THREAD_LOCAL
613static ONIG_THREAD_LOCAL
int reg_onig_depth;
614static ONIG_THREAD_LOCAL
int reg_onig_interrupt_state;
615static ONIG_THREAD_LOCAL
struct {
618 const char *sourcefile;
626#ifdef ONIG_THREAD_LOCAL
634#ifdef ONIG_THREAD_LOCAL
650rb_reg_check_ints(
void)
652#ifdef ONIG_THREAD_LOCAL
653 if (reg_onig_depth > 0) {
654 int depth = reg_onig_depth, state;
656 if (!RUBY_VM_INTERRUPTED_ANY(GET_EC()))
return 0;
660 rb_protect(reg_check_ints_i,
Qnil, &state);
661 reg_onig_depth = depth;
663 reg_onig_interrupt_state = state;
673NORETURN(
static void reg_onig_raise_interrupt(
void));
675reg_onig_raise_interrupt(
void)
677#ifdef ONIG_THREAD_LOCAL
678 int state = reg_onig_interrupt_state;
679 reg_onig_interrupt_state = 0;
687reg_warn_now(
const char *sourcefile,
int sourceline,
const char *msg)
689 if (sourcefile == NULL)
692 rb_compile_warn(sourcefile, sourceline,
"%s", msg);
697rb_reg_warn(
const char *sourcefile,
int sourceline,
const char *msg)
699#ifdef ONIG_THREAD_LOCAL
700 if (reg_onig_depth > 0) {
701 size_t n = strlen(msg) + 1;
703 if (reg_onig_warnings.capa - reg_onig_warnings.len < n) {
704 size_t capa = reg_onig_warnings.capa * 2 + n;
706 char *buf = realloc(reg_onig_warnings.buf,
capa);
708 reg_onig_warnings.buf = buf;
709 reg_onig_warnings.capa =
capa;
711 memcpy(reg_onig_warnings.buf + reg_onig_warnings.len, msg, n);
712 reg_onig_warnings.len += n;
713 reg_onig_warnings.sourcefile = sourcefile;
714 reg_onig_warnings.sourceline = sourceline;
718 reg_warn_now(sourcefile, sourceline, msg);
725#ifdef ONIG_THREAD_LOCAL
726 if (reg_onig_warnings.len == 0)
return;
728 const char *sourcefile = reg_onig_warnings.sourcefile;
729 int sourceline = reg_onig_warnings.sourceline;
731 const char *p = reg_onig_warnings.buf, *e = p + reg_onig_warnings.len;
733 for (; p < e; p += strlen(p) + 1) {
736 free(reg_onig_warnings.buf);
737 reg_onig_warnings.buf = NULL;
738 reg_onig_warnings.len = reg_onig_warnings.capa = 0;
741 reg_warn_now(sourcefile, sourceline, RSTRING_PTR(
RARRAY_AREF(msgs, i)));
748reg_warn_discard(
void)
750#ifdef ONIG_THREAD_LOCAL
751 free(reg_onig_warnings.buf);
752 reg_onig_warnings.buf = NULL;
753 reg_onig_warnings.len = reg_onig_warnings.capa = 0;
765rb_reg_preprocess(
const char *p,
const char *end, rb_encoding *enc,
766 rb_encoding **fixed_enc, onig_errmsg_buffer err,
int options);
769rb_reg_str_with_term(
VALUE re,
int term)
772 const int embeddable = ONIG_OPTION_MULTILINE|ONIG_OPTION_IGNORECASE|ONIG_OPTION_EXTEND;
774 char optbuf[OPTBUF_SIZE + 1];
775 rb_encoding *enc = rb_enc_get(re);
779 rb_enc_copy(str, re);
782 const UChar *ptr = (UChar *)RSTRING_PTR(src_str);
785 if (
len >= 4 && ptr[0] ==
'(' && ptr[1] ==
'?' && rb_enc_asciicompat(enc)) {
788 if ((
len -= 2) > 0) {
790 opt = char_to_option((
int )*ptr);
800 if (
len > 1 && *ptr ==
'-') {
804 opt = char_to_option((
int )*ptr);
819 if (*ptr ==
':' && ptr[
len-1] ==
')') {
822 rb_encoding *fixed_enc = 0;
823 onig_errmsg_buffer errmsg =
"";
828 unescaped = rb_reg_preprocess((
const char *)ptr, (
const char *)ptr +
len,
829 enc, &fixed_enc, errmsg, options);
830 if (!
NIL_P(unescaped) && (!fixed_enc || fixed_enc == enc)) {
833 err = onig_new(&rp, (UChar *)RSTRING_PTR(unescaped),
835 enc, OnigDefaultSyntax, NULL);
852 if ((options & embeddable) != embeddable) {
854 option_to_str(optbuf + 1, ~options);
859 if (rb_enc_asciicompat(enc)) {
860 rb_reg_expr_str(str, (
char*)ptr,
len, enc, NULL, term);
872 s = RSTRING_PTR(str);
878 rb_str_resize(str, RSTRING_LEN(str) - n);
880 rb_reg_expr_str(str, (
char*)ptr,
len, enc, NULL, term);
883 rb_enc_copy(str, re);
890NORETURN(
static void rb_reg_raise(
const char *err,
VALUE re));
893rb_reg_raise(
const char *err,
VALUE re)
895 VALUE desc = rb_reg_desc(re);
901rb_enc_reg_error_desc(
const char *s,
rb_len_t len, rb_encoding *enc,
int options,
const char *err)
903 char opts[OPTBUF_SIZE + 1];
908 rb_enc_associate(desc, enc);
910 rb_reg_expr_str(desc, s,
len, enc, resenc,
'/');
912 option_to_str(opts + 1, options);
917NORETURN(
static void rb_enc_reg_raise(
const char *s,
rb_len_t len, rb_encoding *enc,
int options,
const char *err));
920rb_enc_reg_raise(
const char *s,
rb_len_t len, rb_encoding *enc,
int options,
const char *err)
926rb_reg_error_desc(
VALUE str,
int options,
const char *err)
928 return rb_enc_reg_error_desc(RSTRING_PTR(str), RSTRING_LEN(str),
929 rb_enc_get(str), options, err);
932NORETURN(
static void rb_reg_raise_str(
VALUE str,
int options,
const char *err));
935rb_reg_raise_str(
VALUE str,
int options,
const char *err)
955rb_reg_casefold_p(
VALUE re)
958 return RBOOL(
RREGEXP_PTR(re)->options & ONIG_OPTION_IGNORECASE);
1000rb_reg_options_m(
VALUE re)
1007reg_names_iter(
const OnigUChar *name,
const OnigUChar *name_end,
1008 int back_num,
int *back_refs, OnigRegex regex,
void *arg)
1011 rb_ary_push(ary, rb_enc_str_new((
const char *)name, name_end-name, regex->enc));
1029rb_reg_names(
VALUE re)
1034 onig_foreach_name(
RREGEXP_PTR(re), reg_names_iter, (
void*)ary);
1039reg_named_captures_iter(
const OnigUChar *name,
const OnigUChar *name_end,
1040 int back_num,
int *back_refs, OnigRegex regex,
void *arg)
1046 for (i = 0; i < back_num; i++)
1049 rb_hash_aset(hash,
rb_str_new((
const char*)name, name_end-name),ary);
1073rb_reg_named_captures(
VALUE re)
1075 regex_t *reg = (rb_reg_check(re),
RREGEXP_PTR(re));
1076 VALUE hash = rb_hash_new_capa(onig_number_of_names(reg));
1077 onig_foreach_name(reg, reg_named_captures_iter, (
void*)hash);
1082onig_new_with_source(regex_t* reg,
const UChar* pattern,
const UChar* pattern_end,
1083 OnigOptionType option, OnigEncoding enc,
const OnigSyntaxType* syntax,
1084 OnigErrorInfo* einfo,
const char *sourcefile,
int sourceline)
1088 if (IS_NULL(reg))
return ONIGERR_MEMORY;
1090 r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
1093 r = onig_compile_ruby(reg, pattern, pattern_end, einfo, sourcefile, sourceline);
1096 onig_free_body(reg);
1102make_regexp(
Regexp *rp,
const char *s,
rb_len_t len, rb_encoding *enc,
int flags, onig_errmsg_buffer err,
1103 const char *sourcefile,
int sourceline)
1117 r = onig_new_with_source(rp, (UChar*)s, (UChar*)(s +
len), flags,
1118 enc, OnigDefaultSyntax, &einfo, sourcefile, sourceline);
1121 onig_error_code_to_str((UChar*)err, r, &einfo);
1285match_alloc_n(
VALUE klass,
int num_regs)
1287 int capa = num_regs * 2;
1288 size_t alloc_size = offsetof(
struct RMatch, as) +
sizeof(OnigPosition) *
capa;
1289 if (alloc_size <
sizeof(
struct RMatch)) {
1290 alloc_size =
sizeof(
struct RMatch);
1294 if (!rb_gc_size_allocatable_p(alloc_size)) {
1295 alloc_size =
sizeof(
struct RMatch);
1296 flags |= RMATCH_ONIG;
1300 NEWOBJ_OF(match,
struct RMatch, klass, flags, alloc_size);
1301 memset(((
char *)match) +
sizeof(
struct RBasic), 0, alloc_size -
sizeof(
struct RBasic));
1303 return (
VALUE)match;
1307match_alloc(
VALUE klass)
1309 return match_alloc_n(klass, 0);
1315 onig_region_copy(to, (OnigRegion *)from);
1316 if (to->allocated)
return 0;
1318 onig_region_copy(to, (OnigRegion *)from);
1319 if (to->allocated)
return 0;
1320 return ONIGERR_MEMORY;
1324match_to_onig(
VALUE match,
int num_regs,
const OnigPosition *src_beg,
const OnigPosition *src_end)
1328 if (onig_region_resize(&tmp, num_regs)) {
1331 memcpy(tmp.beg, src_beg, num_regs *
sizeof(OnigPosition));
1332 memcpy(tmp.end, src_end, num_regs *
sizeof(OnigPosition));
1338rb_match_ensure_onig(
VALUE match)
1343 match_to_onig(match, n, &rm->
as.embed[0], &rm->
as.embed[n]);
1350match_set_regs(
VALUE match,
int num_regs,
const OnigPosition *beg,
const OnigPosition *end)
1355 if (onig_region_resize(&rm->
as.onig,
num_regs)) {
1358 memcpy(rm->
as.onig.beg, beg,
num_regs *
sizeof(OnigPosition));
1359 memcpy(rm->
as.onig.end, end,
num_regs *
sizeof(OnigPosition));
1362 memcpy(&rm->
as.embed[0], beg,
num_regs *
sizeof(OnigPosition));
1366 match_to_onig(match,
num_regs, beg, end);
1372match_reuse(
VALUE match)
1376 onig_region_free(&rm->
as.onig, 0);
1377 memset(&rm->
as.onig, 0,
sizeof(rm->
as.onig));
1390rb_match_blob_dump(
VALUE match,
VALUE *regexp_out,
VALUE *str_out,
int *num_regs_out,
bool release_source)
1394 *regexp_out = rm->
regexp;
1398 OnigPosition *blob =
ALLOC_N(OnigPosition, n ? 2 * n : 1);
1399 const OnigPosition *beg = RMATCH_BEG_PTR(match);
1400 const OnigPosition *end = RMATCH_END_PTR(match);
1401 for (
int i = 0; i < n; i++) {
1402 blob[2 * i] = beg[i];
1403 blob[2 * i + 1] = end[i];
1407 if (release_source) {
1416 return match_alloc_n(klass,
num_regs);
1422 const OnigPosition *blob = blob_;
1429 for (
int i = 0; i <
num_regs; i++) {
1430 beg[i] = blob[2 * i];
1431 end[i] = blob[2 * i + 1];
1433 match_set_regs(match,
num_regs, beg, end);
1439rb_match_blob_free(
void *blob)
1450pair_byte_cmp(
const void *pair1,
const void *pair2)
1453#if SIZEOF_RB_LEN_T > SIZEOF_INT
1454 return diff ? diff > 0 ? 1 : -1 : 0;
1463match_char_offsets(
VALUE match)
1468 int i, num_regs, num_pos;
1475 if (offsets)
return offsets;
1477 num_regs = RMATCH_NREGS(match);
1478 enc = rb_enc_get(
RMATCH(match)->str);
1482 for (i = 0; i < num_regs; i++) {
1483 offsets[i].
beg = RMATCH_BEG(match, i);
1484 offsets[i].
end = RMATCH_END(match, i);
1491 for (i = 0; i < num_regs; i++) {
1492 if (RMATCH_BEG(match, i) < 0)
1494 pairs[num_pos++].byte_pos = RMATCH_BEG(match, i);
1495 pairs[num_pos++].byte_pos = RMATCH_END(match, i);
1497 qsort(pairs, num_pos,
sizeof(
pair_t), pair_byte_cmp);
1499 s = p = RSTRING_PTR(
RMATCH(match)->str);
1501 for (i = 0; i < num_pos; i++) {
1502 q = s + pairs[i].byte_pos;
1504 pairs[i].char_pos = c;
1509 for (i = 0; i < num_regs; i++) {
1511 if (RMATCH_BEG(match, i) < 0) {
1512 offsets[i].
beg = -1;
1513 offsets[i].
end = -1;
1517 key.byte_pos = RMATCH_BEG(match, i);
1518 found = bsearch(&key, pairs, num_pos,
sizeof(
pair_t), pair_byte_cmp);
1519 offsets[i].
beg = found->char_pos;
1521 key.byte_pos = RMATCH_END(match, i);
1522 found = bsearch(&key, pairs, num_pos,
sizeof(
pair_t), pair_byte_cmp);
1523 offsets[i].
end = found->char_pos;
1531 SIZED_FREE_N(offsets, num_regs);
1539match_check(
VALUE match)
1541 if (!
RMATCH(match)->regexp) {
1558 match_set_regs(obj, RMATCH_NREGS(orig), RMATCH_BEG_PTR(orig), RMATCH_END_PTR(orig));
1593match_regexp(
VALUE match)
1597 regexp =
RMATCH(match)->regexp;
1598 if (
NIL_P(regexp)) {
1624match_names(
VALUE match)
1629 return rb_reg_names(
RMATCH(match)->regexp);
1650match_size(
VALUE match)
1653 return INT2FIX(RMATCH_NREGS(match));
1656static int match_name_to_backref_number(
VALUE match,
VALUE name);
1657NORETURN(
static void name_to_backref_error(
VALUE name));
1660name_to_backref_error(
VALUE name)
1662 rb_raise(
rb_eIndexError,
"undefined group name reference: % "PRIsVALUE,
1667backref_number_check(
VALUE match,
int i)
1669 if (i < 0 || RMATCH_NREGS(match) <= i)
1674match_backref_number(
VALUE match,
VALUE backref)
1686 num = match_name_to_backref_number(match, backref);
1689 name_to_backref_error(backref);
1698 return match_backref_number(match, backref);
1752 int i = match_backref_number(match, n);
1755 backref_number_check(match, i);
1757 if (RMATCH_BEG(match, i) < 0)
1760 const struct rmatch_offset *ofs = &match_char_offsets(match)[i];
1812 int i = match_backref_number(match, n);
1815 backref_number_check(match, i);
1817 if (RMATCH_BEG(match, i) < 0)
1871 int i = match_backref_number(match, n);
1874 backref_number_check(match, i);
1876 if (RMATCH_BEG(match, i) < 0)
1878 return LEN2NUM(RMATCH_BEG(match, i));
1931 int i = match_backref_number(match, n);
1934 backref_number_check(match, i);
1936 if (RMATCH_BEG(match, i) < 0)
1938 return LEN2NUM(RMATCH_END(match, i));
1990 int i = match_backref_number(match, n);
1993 backref_number_check(match, i);
1995 if (RMATCH_BEG(match, i) < 0)
1998 return LEN2NUM(match_char_offsets(match)[i].
beg);
2049 int i = match_backref_number(match, n);
2052 backref_number_check(match, i);
2054 if (RMATCH_BEG(match, i) < 0)
2057 return LEN2NUM(match_char_offsets(match)[i].
end);
2131 int i = match_backref_number(match, n);
2133 backref_number_check(match, i);
2135 rb_len_t start = RMATCH_BEG(match, i),
end = RMATCH_END(match, i);
2192 int i = match_backref_number(match, n);
2195 backref_number_check(match, i);
2197 if (RMATCH_BEG(match, i) < 0)
2200 const struct rmatch_offset *
const ofs = &match_char_offsets(match)[i];
2207 FL_SET(match, MATCH_BUSY);
2211rb_match_unbusy(
VALUE match)
2217rb_match_count(
VALUE match)
2219 if (
NIL_P(match))
return -1;
2220 return RMATCH_NREGS(match);
2224match_alloc_or_reuse(
VALUE existing,
int num_regs)
2230 if (!
NIL_P(existing) &&
2232 !
FL_TEST(existing, MATCH_BUSY) &&
2234 match_reuse(existing);
2237 return match_alloc_n(
rb_cMatch, num_regs);
2247 OnigPosition beg = pos, end = pos +
len;
2248 match_set_regs(m, 1, &beg, &end);
2255 match_set_string(match,
string, pos,
len);
2290rb_reg_fixed_encoding_p(
VALUE re)
2292 return RBOOL(
FL_TEST(re, KCODE_FIXED));
2301 "incompatible encoding regexp match (%s regexp with %s string)",
2302 rb_enc_inspect_name(rb_enc_get(re)),
2303 rb_enc_inspect_name(rb_enc_get(
str)));
2309 rb_encoding *enc = 0;
2310 int cr = rb_enc_str_coderange(
str);
2313 rb_raise(rb_eArgError,
2314 "invalid byte sequence in %s",
2315 rb_enc_name(rb_enc_get(
str)));
2319 enc = rb_enc_get(
str);
2326 else if (!rb_enc_asciicompat(enc)) {
2327 reg_enc_error(re,
str);
2329 else if (rb_reg_fixed_encoding_p(re)) {
2332 reg_enc_error(re,
str);
2336 else if (warn && (
RBASIC(re)->flags & REG_ENCODING_NONE) &&
2339 rb_warn(
"historical binary regexp match /.../n against %s string",
2348 for (; variant; variant = variant->next) {
2349 if (variant->reg.enc == enc)
return &variant->reg;
2360 rb_encoding *fixed_enc = 0;
2361 rb_encoding *enc = rb_reg_prepare_enc(re,
str, 1);
2364 if (reg->enc == enc)
return reg;
2367 regex_t *cached = reg_find_encoding(head, enc);
2368 if (cached && !caller_owned)
return cached;
2371 const char *pattern = RSTRING_PTR(src_str);
2373 onig_errmsg_buffer err =
"";
2374 unescaped = rb_reg_preprocess(
2375 pattern, pattern + RSTRING_LEN(src_str), enc,
2376 &fixed_enc, err, reg->options);
2378 if (
NIL_P(unescaped)) {
2379 rb_raise(rb_eArgError,
"regexp preprocess failed: %s", err);
2383 rb_hrtime_t timelimit = reg->timelimit;
2391 r = onig_new_without_alloc(&variant->reg, (UChar *)ptr, (UChar *)(ptr +
len),
2392 reg->options, enc, OnigDefaultSyntax, &einfo);
2396 onig_free_body(&variant->reg);
2397 SIZED_FREE(variant);
2399 onig_error_code_to_str((UChar*)err, r, &einfo);
2400 rb_reg_raise(err, re);
2403 reg = &variant->reg;
2404 reg->timelimit = timelimit;
2406 rb_bug(
"group count mismatch in the recompiled regexp: %d != %d", reg->num_mem,
RREGEXP_PTR(re)->num_mem);
2412 rb_protect(reg_warn_kept_i,
Qnil, &state);
2414 onig_free_body(&variant->reg);
2415 SIZED_FREE(variant);
2422 reg = malloc(
sizeof(regex_t));
2424 onig_free_body(&variant->reg);
2425 SIZED_FREE(variant);
2428 *reg = variant->reg;
2429 SIZED_FREE(variant);
2437 variant->next = head;
2439 if (previous == head)
break;
2442 cached = reg_find_encoding(head, enc);
2445 onig_free_body(&variant->reg);
2446 SIZED_FREE(variant);
2463 return reg_prepare_re(re, str,
true);
2468 OnigPosition (*match)(regex_t *reg,
VALUE str,
struct re_registers *regs,
void *args),
2471 regex_t *reg = reg_prepare_re(re, str,
false);
2475 const char *
const ptr = RSTRING_PTR(str);
2477 VALUE lock = rb_str_try_locktmp(str);
2479 OnigPosition result = match(reg, str, regs, args);
2481 rb_str_try_unlocktmp(str, lock);
2487 if (result == ONIGERR_INTERRUPTED) reg_onig_raise_interrupt();
2489 if (lock !=
Qtrue && (RSTRING_PTR(str) != ptr || RSTRING_LEN(str) !=
len)) {
2493 if (result == ONIGERR_MEMORY) {
2501 case ONIGERR_INTERRUPTED:
2502 reg_onig_raise_interrupt();
2503 case ONIGERR_TIMEOUT:
2504 rb_raise(rb_eRegexpTimeoutError,
"regexp match timeout");
2506 onig_errmsg_buffer err =
"";
2507 onig_error_code_to_str((UChar*)err, (
int)result);
2508 rb_reg_raise(err, re);
2523 enc = rb_reg_prepare_enc(re, str, 0);
2529 range = RSTRING_LEN(str) - pos;
2532 if (pos > 0 && ONIGENC_MBC_MAXLEN(enc) != 1 && pos < RSTRING_LEN(str)) {
2533 string = (UChar*)RSTRING_PTR(str);
2536 p = onigenc_get_right_adjust_char_head(enc,
string,
string + pos,
string + RSTRING_LEN(str));
2539 p = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc,
string,
string + pos,
string + RSTRING_LEN(str));
2553reg_onig_search(regex_t *reg,
VALUE str,
struct re_registers *regs,
void *args_ptr)
2563 (UChar *)(ptr +
len),
2564 (UChar *)(ptr + args->pos),
2565 (UChar *)(ptr + args->range),
2575 if (pos >
len || pos < 0) {
2582 .range = reverse ? 0 :
len,
2590 int cap = n < ONIG_NREGION ? ONIG_NREGION : n;
2592 OnigPosition *buf =
ALLOCV_N(OnigPosition, regs_buf, (
size_t)cap * 2);
2600 OnigPosition result =
rb_reg_onig_match(re, str, reg_onig_search, &args, ®s);
2602 if (result == ONIG_MISMATCH) {
2605 return ONIG_MISMATCH;
2609 VALUE match = match_alloc_or_reuse(existing, regs.num_regs);
2611 match_set_regs(match, regs.num_regs, regs.beg, regs.end);
2614 if (set_backref_str) {
2618 else if (!
RMATCH(match)->str) {
2628 if (set_match) *set_match = match;
2636 return rb_reg_search_set_match(re, str, pos, reverse, set_backref_str, match);
2642 return rb_reg_search_set_match(re, str, pos, reverse, 1, NULL);
2655 (UChar *)(ptr +
len),
2667 int cap = n < ONIG_NREGION ? ONIG_NREGION : n;
2669 OnigPosition *buf =
ALLOCV_N(OnigPosition, regs_buf, (
size_t)cap * 2);
2684 match_set_regs(match, regs.num_regs, regs.beg, regs.end);
2700 int num_regs = RMATCH_NREGS(match);
2701 if (nth >= num_regs) {
2706 if (nth <= 0)
return Qnil;
2708 return RBOOL(RMATCH_BEG(match, nth) != -1);
2719 int num_regs = RMATCH_NREGS(match);
2720 if (nth >= num_regs) {
2725 if (nth <= 0)
return Qnil;
2727 start = RMATCH_BEG(match, nth);
2728 if (start == -1)
return Qnil;
2729 end = RMATCH_END(match, nth);
2768 if (RMATCH_BEG(match, 0) == -1)
return Qnil;
2801 if (RMATCH_BEG(match, 0) == -1)
return Qnil;
2802 str =
RMATCH(match)->str;
2803 pos = RMATCH_END(match, 0);
2809match_last_index(
VALUE match)
2813 if (
NIL_P(match))
return -1;
2815 if (RMATCH_BEG(match, 0) == -1)
return -1;
2817 for (i = RMATCH_NREGS(match) - 1; RMATCH_BEG(match, i) == -1 && i > 0; i--)
2825 int i = match_last_index(match);
2826 if (i <= 0)
return Qnil;
2827 rb_len_t start = RMATCH_BEG(match, i);
2832rb_reg_last_defined(
VALUE match)
2834 int i = match_last_index(match);
2835 if (i < 0)
return Qnil;
2840last_match_getter(
ID _x,
VALUE *_y)
2846prematch_getter(
ID _x,
VALUE *_y)
2852postmatch_getter(
ID _x,
VALUE *_y)
2858last_paren_match_getter(
ID _x,
VALUE *_y)
2864match_array(
VALUE match,
int start)
2871 int num_regs = RMATCH_NREGS(match);
2873 target =
RMATCH(match)->str;
2875 for (i = start; i < num_regs; i++) {
2876 rb_len_t beg = RMATCH_BEG(match, i);
2907match_to_a(
VALUE match)
2909 return match_array(match, 0);
2935match_captures(
VALUE match)
2937 return match_array(match, 1);
2941name_to_backref_number(
const struct re_registers *regs,
VALUE regexp,
const char* name,
const char* name_end)
2943 if (
NIL_P(regexp))
return -1;
2944 return onig_name_to_backref_number(
RREGEXP_PTR(regexp),
2945 (
const unsigned char *)name, (
const unsigned char *)name_end, regs);
2948#define NAME_TO_NUMBER(regs, re, name, name_ptr, name_end) \
2950 !rb_enc_compatible(RREGEXP_SRC(re), (name)) ? 0 : \
2951 name_to_backref_number((regs), (re), (name_ptr), (name_end)))
2954match_name_to_backref_number(
VALUE match,
VALUE name)
2957 if (
NIL_P(regexp))
return -1;
2960 int n = onig_name_to_group_numbers(
RREGEXP_PTR(regexp),
2961 (
const unsigned char *)RSTRING_PTR(name),
2963 if (n < 0)
return n;
2964 if (n == 0)
return ONIGERR_PARSER_BUG;
2965 if (n == 1)
return nums[0];
2966 for (
int i = n - 1; i >= 0; i--) {
2967 if (RMATCH_BEG(match, nums[i]) != ONIG_REGION_NOTPOS)
2974namev_to_backref_number(
VALUE match,
VALUE name)
2990 num = match_name_to_backref_number(match, name);
2993 name_to_backref_error(name);
3001 rb_len_t olen = RMATCH_NREGS(match);
3004 if (
len == 0)
return result;
3006 for (j = beg; j < end; j++) {
3009 if (beg +
len > j) {
3019 int num_regs = RMATCH_NREGS(match);
3030 return match_ary_subseq(match, beg,
len, result);
3132match_aref(
int argc,
VALUE *argv,
VALUE match)
3139 if (
NIL_P(length)) {
3144 int num = namev_to_backref_number(match, idx);
3149 return match_ary_aref(match, idx,
Qnil);
3156 rb_len_t num_regs = RMATCH_NREGS(match);
3162 if (beg < 0)
return Qnil;
3164 else if (beg > num_regs) {
3167 if (beg+
len > num_regs) {
3168 len = num_regs - beg;
3170 return match_ary_subseq(match, beg,
len,
Qnil);
3250match_values_at(
int argc,
VALUE *argv,
VALUE match)
3258 for (i=0; i<argc; i++) {
3263 int num = namev_to_backref_number(match, argv[i]);
3268 match_ary_aref(match, argv[i], result);
3295match_to_s(
VALUE match)
3310match_named_captures_iter(
const OnigUChar *name,
const OnigUChar *name_end,
3311 int back_num,
int *back_refs, OnigRegex regex,
void *arg)
3314 VALUE hash = data->hash;
3315 VALUE match = data->match;
3317 VALUE key = rb_enc_str_new((
const char *)name, name_end-name, regex->enc);
3319 if (data->symbolize) {
3328 for (i = 0; i < back_num; i++) {
3331 rb_hash_aset(hash, key, value);
3337 rb_hash_aset(hash, key,
Qnil);
3379match_named_captures(
int argc,
VALUE *argv,
VALUE match)
3388 int symbolize_names = 0;
3393 static ID keyword_ids[1];
3395 VALUE symbolize_names_val;
3397 if (!keyword_ids[0]) {
3400 rb_get_kwargs(opt, keyword_ids, 0, 1, &symbolize_names_val);
3401 if (!UNDEF_P(symbolize_names_val) &&
RTEST(symbolize_names_val)) {
3402 symbolize_names = 1;
3409 onig_foreach_name(
RREGEXP_PTR(
RMATCH(match)->regexp), match_named_captures_iter, &data);
3455match_deconstruct_keys(
VALUE match,
VALUE keys)
3471 onig_foreach_name(
RREGEXP_PTR(
RMATCH(match)->regexp), match_named_captures_iter, &data);
3492 int num = match_name_to_backref_number(match, name);
3524match_string(
VALUE match)
3527 return RMATCH(match)->str;
3536match_inspect_name_iter(
const OnigUChar *name,
const OnigUChar *name_end,
3537 int back_num,
int *back_refs, OnigRegex regex,
void *arg0)
3542 for (i = 0; i < back_num; i++) {
3543 arg[back_refs[i]].name = name;
3544 arg[back_refs[i]].len = name_end - name;
3574match_inspect(
VALUE match)
3579 int num_regs = RMATCH_NREGS(match);
3585 return rb_sprintf(
"#<%"PRIsVALUE
":%p>", cname, (
void*)match);
3587 else if (
NIL_P(regexp)) {
3588 return rb_sprintf(
"#<%"PRIsVALUE
": %"PRIsVALUE
">",
3596 match_inspect_name_iter, names);
3601 for (i = 0; i < num_regs; i++) {
3608 rb_str_catf(str,
"%d", i);
3627read_escaped_byte(
const char **pp,
const char *end, onig_errmsg_buffer err)
3629 const char *p = *pp;
3631 int meta_prefix = 0, ctrl_prefix = 0;
3634 if (p == end || *p++ !=
'\\') {
3635 errcpy(err,
"too short escaped multibyte character");
3641 errcpy(err,
"too short escape sequence");
3645 case '\\': code =
'\\';
break;
3646 case 'n': code =
'\n';
break;
3647 case 't': code =
'\t';
break;
3648 case 'r': code =
'\r';
break;
3649 case 'f': code =
'\f';
break;
3650 case 'v': code =
'\013';
break;
3651 case 'a': code =
'\007';
break;
3652 case 'e': code =
'\033';
break;
3655 case '0':
case '1':
case '2':
case '3':
3656 case '4':
case '5':
case '6':
case '7':
3665 errcpy(err,
"invalid hex escape");
3673 errcpy(err,
"duplicate meta escape");
3677 if (p+1 < end && *p++ ==
'-' && (*p & 0x80) == 0) {
3687 errcpy(err,
"too short meta escape");
3691 if (p == end || *p++ !=
'-') {
3692 errcpy(err,
"too short control escape");
3697 errcpy(err,
"duplicate control escape");
3701 if (p < end && (*p & 0x80) == 0) {
3711 errcpy(err,
"too short control escape");
3715 errcpy(err,
"unexpected escape sequence");
3718 if (code < 0 || 0xff < code) {
3719 errcpy(err,
"invalid escape code");
3733unescape_escaped_nonascii(
const char **pp,
const char *end, rb_encoding *enc,
3734 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
3736 const char *p = *pp;
3738 unsigned char *area =
ALLOCA_N(
unsigned char, chmaxlen);
3739 char *chbuf = (
char *)area;
3744 memset(chbuf, 0, chmaxlen);
3746 byte = read_escaped_byte(&p, end, err);
3751 area[chlen++] = byte;
3752 while (chlen < chmaxlen &&
3754 byte = read_escaped_byte(&p, end, err);
3758 area[chlen++] = byte;
3761 l = rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc);
3763 errcpy(err,
"invalid multibyte escape");
3766 if (1 < chlen || (area[0] & 0x80)) {
3771 else if (*encp != enc) {
3772 errcpy(err,
"escaped non ASCII character in UTF-8 regexp");
3778 snprintf(escbuf,
sizeof(escbuf),
"\\x%02X", area[0]&0xff);
3786check_unicode_range(
unsigned long code, onig_errmsg_buffer err)
3788 if ((0xd800 <= code && code <= 0xdfff) ||
3790 errcpy(err,
"invalid Unicode range");
3797append_utf8(
unsigned long uv,
3798 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
3800 if (check_unicode_range(uv, err) != 0)
3804 snprintf(escbuf,
sizeof(escbuf),
"\\x%02X", (
int)uv);
3816 errcpy(err,
"UTF-8 character in non UTF-8 regexp");
3824unescape_unicode_list(
const char **pp,
const char *end,
3825 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
3827 const char *p = *pp;
3828 int has_unicode = 0;
3832 while (p < end &&
ISSPACE(*p)) p++;
3839 errcpy(err,
"invalid Unicode range");
3843 if (append_utf8(code, buf, encp, err) != 0)
3847 while (p < end &&
ISSPACE(*p)) p++;
3850 if (has_unicode == 0) {
3851 errcpy(err,
"invalid Unicode list");
3861unescape_unicode_bmp(
const char **pp,
const char *end,
3862 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
3864 const char *p = *pp;
3869 errcpy(err,
"invalid Unicode escape");
3874 errcpy(err,
"invalid Unicode escape");
3877 if (append_utf8(code, buf, encp, err) != 0)
3884unescape_nonascii0(
const char **pp,
const char *end, rb_encoding *enc,
3885 VALUE buf, rb_encoding **encp,
int *has_property,
3886 onig_errmsg_buffer err,
int options,
int recurse)
3888 const char *p = *pp;
3891 int in_char_class = 0;
3893 int extended_mode = options & ONIG_OPTION_EXTEND;
3897 int chlen = rb_enc_precise_mbclen(p, end, enc);
3900 errcpy(err,
"invalid multibyte character");
3904 if (1 < chlen || (*p & 0x80)) {
3910 else if (*encp != enc) {
3911 errcpy(err,
"non ASCII character in UTF-8 regexp");
3920 errcpy(err,
"too short escape sequence");
3923 chlen = rb_enc_precise_mbclen(p, end, enc);
3925 goto invalid_multibyte;
3934 case '1':
case '2':
case '3':
3935 case '4':
case '5':
case '6':
case '7':
3937 size_t len = end-(p-1), octlen;
3954 if (rb_is_usascii_enc(enc)) {
3955 const char *pbeg = p;
3956 int byte = read_escaped_byte(&p, end, err);
3957 if (
byte == -1)
return -1;
3962 if (unescape_escaped_nonascii(&p, end, enc, buf, encp, err) != 0)
3969 errcpy(err,
"too short escape sequence");
3975 if (unescape_unicode_list(&p, end, buf, encp, err) != 0)
3977 if (p == end || *p++ !=
'}') {
3978 errcpy(err,
"invalid Unicode list");
3985 if (unescape_unicode_bmp(&p, end, buf, encp, err) != 0)
4007 if (extended_mode && !in_char_class) {
4009 while ((p < end) && ((c = *p++) !=
'\n')) {
4024 if (in_char_class) {
4031 if (!in_char_class && recurse) {
4032 if (--parens == 0) {
4039 if (!in_char_class && p + 1 < end && *p ==
'?') {
4040 if (*(p+1) ==
'#') {
4042 const char *orig_p = p;
4045 while (cont && (p < end)) {
4048 if (!(c & 0x80))
break;
4055 chlen = rb_enc_precise_mbclen(p, end, enc);
4057 goto invalid_multibyte;
4081 int local_extend = 0;
4088 for (s = p+1; s < end; s++) {
4091 local_extend = invert ? -1 : 1;
4098 if (local_extend == 0 ||
4099 (local_extend == -1 && !extended_mode) ||
4100 (local_extend == 1 && extended_mode)) {
4107 int local_options = options;
4108 if (local_extend == 1) {
4109 local_options |= ONIG_OPTION_EXTEND;
4112 local_options &= ~ONIG_OPTION_EXTEND;
4116 int ret = unescape_nonascii0(&p, end, enc, buf, encp,
4119 if (ret < 0)
return ret;
4124 extended_mode = local_extend == 1;
4141 else if (!in_char_class && recurse) {
4159unescape_nonascii(
const char *p,
const char *end, rb_encoding *enc,
4160 VALUE buf, rb_encoding **encp,
int *has_property,
4161 onig_errmsg_buffer err,
int options)
4163 return unescape_nonascii0(&p, end, enc, buf, encp, has_property,
4168rb_reg_preprocess(
const char *p,
const char *end, rb_encoding *enc,
4169 rb_encoding **fixed_enc, onig_errmsg_buffer err,
int options)
4172 int has_property = 0;
4176 if (rb_enc_asciicompat(enc))
4180 rb_enc_associate(buf, enc);
4183 if (unescape_nonascii(p, end, enc, buf, fixed_enc, &has_property, err, options) != 0)
4186 if (has_property && !*fixed_enc) {
4191 rb_enc_associate(buf, *fixed_enc);
4198rb_reg_check_preprocess(
VALUE str)
4200 rb_encoding *fixed_enc = 0;
4201 onig_errmsg_buffer err =
"";
4207 p = RSTRING_PTR(str);
4208 end = p + RSTRING_LEN(str);
4209 enc = rb_enc_get(str);
4211 buf = rb_reg_preprocess(p, end, enc, &fixed_enc, err, 0);
4215 return rb_reg_error_desc(str, 0, err);
4221rb_reg_preprocess_dregexp(
VALUE ary,
int options)
4223 rb_encoding *fixed_enc = 0;
4224 rb_encoding *regexp_enc = 0;
4225 onig_errmsg_buffer err =
"";
4231 rb_raise(rb_eArgError,
"no arguments given");
4238 rb_encoding *src_enc;
4240 src_enc = rb_enc_get(str);
4241 if (options & ARG_ENCODING_NONE &&
4242 src_enc != ascii8bit) {
4244 rb_raise(
rb_eRegexpError,
"/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
4246 src_enc = ascii8bit;
4250 p = RSTRING_PTR(str);
4251 end = p + RSTRING_LEN(str);
4253 buf = rb_reg_preprocess(p, end, src_enc, &fixed_enc, err, options);
4256 rb_raise(rb_eArgError,
"%s", err);
4258 if (fixed_enc != 0) {
4259 if (regexp_enc != 0 && regexp_enc != fixed_enc) {
4260 rb_raise(
rb_eRegexpError,
"encoding mismatch in dynamic regexp : %s and %s",
4261 rb_enc_name(regexp_enc), rb_enc_name(fixed_enc));
4263 regexp_enc = fixed_enc;
4272 rb_enc_associate(result, regexp_enc);
4279rb_reg_initialize_check(
VALUE obj)
4281 rb_check_frozen(obj);
4289 int options, onig_errmsg_buffer err,
4290 const char *sourcefile,
int sourceline)
4294 rb_encoding *fixed_enc = 0;
4297 rb_reg_initialize_check(obj);
4299 if (rb_enc_dummy_p(enc)) {
4300 errcpy(err,
"can't make regexp with dummy encoding");
4304 unescaped = rb_reg_preprocess(s, s+
len, enc, &fixed_enc, err, options);
4305 if (
NIL_P(unescaped))
4309 if ((fixed_enc != enc && (options & ARG_ENCODING_FIXED)) ||
4310 (fixed_enc != a_enc && (options & ARG_ENCODING_NONE))) {
4311 errcpy(err,
"incompatible character encoding");
4314 if (fixed_enc != a_enc) {
4315 options |= ARG_ENCODING_FIXED;
4319 else if (!(options & ARG_ENCODING_FIXED)) {
4324 bool success = make_regexp(®, RSTRING_PTR(unescaped), RSTRING_LEN(unescaped), enc,
4325 options & ARG_REG_OPTION_MASK, err,
4326 sourcefile, sourceline);
4332 onig_free_body(®);
4333 rb_reg_initialize_check(obj);
4337 rb_enc_associate((
VALUE)re, enc);
4338 if ((options & ARG_ENCODING_FIXED) || fixed_enc) {
4341 if (options & ARG_ENCODING_NONE) {
4356reg_set_source(
VALUE reg,
VALUE str, rb_encoding *enc)
4358 rb_encoding *regenc = rb_enc_get(reg);
4360 if (regenc != enc) {
4362 str = rb_enc_associate(dup, enc = regenc);
4364 str = rb_fstring(str);
4369rb_reg_initialize_str(
VALUE obj,
VALUE str,
int options, onig_errmsg_buffer err,
4370 const char *sourcefile,
int sourceline)
4373 rb_encoding *str_enc = rb_enc_get(str), *enc = str_enc;
4374 if (options & ARG_ENCODING_NONE) {
4376 if (enc != ascii8bit) {
4378 errcpy(err,
"/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
4384 ret = rb_reg_initialize(obj, RSTRING_PTR(str), RSTRING_LEN(str), enc,
4385 options, err, sourcefile, sourceline);
4386 if (ret == 0) reg_set_source(obj, str, str_enc);
4391rb_reg_s_alloc(
VALUE klass)
4411 return rb_reg_init_str(rb_reg_alloc(), s, options);
4415rb_reg_init_str(
VALUE re,
VALUE s,
int options)
4417 onig_errmsg_buffer err =
"";
4419 if (rb_reg_initialize_str(re, s, options, err, NULL, 0) != 0) {
4420 rb_reg_raise_str(s, options, err);
4427rb_reg_init_str_enc(
VALUE re,
VALUE s, rb_encoding *enc,
int options)
4429 onig_errmsg_buffer err =
"";
4431 if (rb_reg_initialize(re, RSTRING_PTR(s), RSTRING_LEN(s),
4432 enc, options, err, NULL, 0) != 0) {
4433 rb_reg_raise_str(s, options, err);
4435 reg_set_source(re, s, enc);
4441rb_reg_new_from_values(
rb_len_t cnt,
const VALUE *elements,
int opt)
4443 const VALUE ary = rb_ary_tmp_new_from_values(0, cnt, elements);
4452 VALUE re = rb_reg_alloc();
4453 onig_errmsg_buffer err =
"";
4455 if (rb_reg_initialize(re, s,
len, enc, options, err, NULL, 0) != 0) {
4456 rb_enc_reg_raise(s,
len, enc, options, err);
4470rb_reg_compile(
VALUE str,
int options,
const char *sourcefile,
int sourceline)
4472 VALUE re = rb_reg_alloc();
4473 onig_errmsg_buffer err =
"";
4476 if (rb_reg_initialize_str(re, str, options, err, sourcefile, sourceline) != 0) {
4477 rb_set_errinfo(rb_reg_error_desc(str, options, err));
4483static VALUE reg_cache;
4488 if (rb_ractor_main_p()) {
4491 && memcmp(
RREGEXP_SRC_PTR(reg_cache), RSTRING_PTR(str), RSTRING_LEN(str)) == 0)
4501static st_index_t reg_hash(
VALUE re);
4513rb_reg_hash(
VALUE re)
4515 st_index_t hashval = reg_hash(re);
4548 if (re1 == re2)
return Qtrue;
4550 rb_reg_check(re1); rb_reg_check(re2);
4580match_hash(
VALUE match)
4586 hashval =
rb_hash_uint(hashval, reg_hash(match_regexp(match)));
4587 int num_regs = RMATCH_NREGS(match);
4622 if (match1 == match2)
return Qtrue;
4626 if (!rb_reg_equal(match_regexp(match1), match_regexp(match2)))
return Qfalse;
4627 int num_regs = RMATCH_NREGS(match1);
4628 if (num_regs != RMATCH_NREGS(match2))
return Qfalse;
4629 if (memcmp(RMATCH_BEG_PTR(match1), RMATCH_BEG_PTR(match2), num_regs *
sizeof(OnigPosition)))
return Qfalse;
4630 if (memcmp(RMATCH_END_PTR(match1), RMATCH_END_PTR(match2), num_regs *
sizeof(OnigPosition)))
return Qfalse;
4689match_integer_at(
int argc,
VALUE *argv,
VALUE match)
4701 else if ((nth = namev_to_backref_number(match, idx)) < 0) {
4702 name_to_backref_error(idx);
4705 if (argc > 1 && (base =
NUM2INT(argv[1])) < 0) {
4706 rb_raise(rb_eArgError,
"invalid radix %d", base);
4709 if (nth >= RMATCH_NREGS(match))
return Qnil;
4710 if (nth < 0 && (nth += RMATCH_NREGS(match)) <= 0)
return Qnil;
4712 rb_len_t start = RMATCH_BEG(match, nth), end = RMATCH_END(match, nth);
4713 if (start < 0)
return Qnil;
4714 RUBY_ASSERT(start <= end, "%"PRIdLEN" > %
"PRIdLEN, start, end);
4716 VALUE str = RMATCH(match)->str;
4717 RUBY_ASSERT(end <= RSTRING_LEN(str), "%
"PRIdLEN" > %
"PRIdLEN, end, RSTRING_LEN(str));
4720 return rb_int_parse_cstr(RSTRING_PTR(str) + start, end - start, &endp, NULL,
4721 base, RB_INT_PARSE_DEFAULT);
4725reg_operand(VALUE s, int check)
4728 return rb_sym2str(s);
4730 else if (RB_TYPE_P(s, T_STRING)) {
4734 return check ? rb_str_to_str(s) : rb_check_string_type(s);
4739reg_match_pos(VALUE re, VALUE *strp, rb_len_t pos, VALUE* set_match)
4744 rb_backref_set(Qnil);
4747 *strp = str = reg_operand(str, TRUE);
4750 VALUE l = rb_str_length(str);
4753 rb_backref_set(Qnil);
4757 pos = rb_str_offset(str, pos);
4759 return rb_reg_search_set_match(re, str, pos, 0, 1, set_match);
4764 * self =~ other -> integer or nil
4766 * Returns the integer index (in characters) of the first match
4767 * for +self+ and +other+, or +nil+ if none;
4768 * updates {Regexp-related global variables}[rdoc-ref:Regexp@Global+Variables].
4770 * /at/ =~ 'input data' # => 7
4771 * $~ # => #<MatchData "at
">
4772 * /ax/ =~ 'input data' # => nil
4775 * Assigns named captures to local variables of the same names
4776 * if and only if +self+:
4778 * - Is a regexp literal;
4779 * see {Regexp Literals}[rdoc-ref:syntax/literals.rdoc@Regexp+Literals].
4780 * - Does not contain interpolations;
4781 * see {Regexp interpolation}[rdoc-ref:Regexp@Interpolation+Mode].
4782 * - Is at the left of the expression.
4786 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ ' x = y '
4790 * Assigns +nil+ if not matched:
4792 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ ' x = '
4796 * Does not make local variable assignments if +self+ is not a regexp literal:
4798 * r = /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
4800 * p foo # Undefined local variable
4801 * p bar # Undefined local variable
4803 * The assignment does not occur if the regexp is not at the left:
4805 * ' x = y ' =~ /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
4806 * p foo, foo # Undefined local variables
4808 * A regexp interpolation, <tt>#{}</tt>, also disables
4812 * /(?<foo>\w+)\s*=\s*#{r}/ =~ 'x = y'
4813 * p foo # Undefined local variable
4818rb_reg_match(VALUE re, VALUE str)
4820 rb_len_t pos = reg_match_pos(re, &str, 0, NULL);
4821 if (pos < 0) return Qnil;
4822 pos = rb_str_sublen(str, pos);
4823 return LEN2NUM(pos);
4828 * self === other -> true or false
4830 * Returns whether +self+ finds a match in +other+:
4832 * /^[a-z]*$/ === 'HELLO' # => false
4833 * /^[A-Z]*$/ === 'HELLO' # => true
4835 * This method is called in case statements:
4839 * when /\A[a-z]*\z/; print "Lower
case\n
"
4840 * when /\A[A-Z]*\z/; print "Upper
case\n
"
4841 * else print "Mixed
case\n
"
4842 * end # => "Upper
case"
4847rb_reg_eqq(VALUE re, VALUE str)
4851 str = reg_operand(str, FALSE);
4853 rb_backref_set(Qnil);
4856 start = rb_reg_search(re, str, 0, 0);
4857 return RBOOL(start >= 0);
4863 * ~ rxp -> integer or nil
4865 * Equivalent to <tt><i>rxp</i> =~ $_</tt>:
4873rb_reg_match2(VALUE re)
4876 VALUE line = rb_lastline_get();
4878 if (!RB_TYPE_P(line, T_STRING)) {
4879 rb_backref_set(Qnil);
4883 start = rb_reg_search(re, line, 0, 0);
4887 start = rb_str_sublen(line, start);
4888 return LEN2NUM(start);
4894 * match(string, offset = 0) -> matchdata or nil
4895 * match(string, offset = 0) {|matchdata| ... } -> object
4897 * With no block given, returns the MatchData object
4898 * that describes the match, if any, or +nil+ if none;
4899 * the search begins at the given character +offset+ in +string+:
4901 * /abra/.match('abracadabra') # => #<MatchData "abra
">
4902 * /abra/.match('abracadabra', 4) # => #<MatchData "abra
">
4903 * /abra/.match('abracadabra', 8) # => nil
4904 * /abra/.match('abracadabra', 800) # => nil
4906 * string = "\u{5d0 5d1 5e8 5d0}cadabra
"
4907 * /abra/.match(string, 7) #=> #<MatchData "abra
">
4908 * /abra/.match(string, 8) #=> nil
4909 * /abra/.match(string.b, 8) #=> #<MatchData "abra
">
4911 * With a block given, calls the block if and only if a match is found;
4912 * returns the block's value:
4914 * /abra/.match('abracadabra') {|matchdata| p matchdata }
4915 * # => #<MatchData "abra
">
4916 * /abra/.match('abracadabra', 4) {|matchdata| p matchdata }
4917 * # => #<MatchData "abra
">
4918 * /abra/.match('abracadabra', 8) {|matchdata| p matchdata }
4920 * /abra/.match('abracadabra', 8) {|marchdata| fail 'Cannot happen' }
4923 * Output (from the first two blocks above):
4925 * #<MatchData "abra
">
4926 * #<MatchData "abra
">
4928 * /(.)(.)(.)/.match("abc
")[2] # => "b
"
4929 * /(.)(.)/.match("abc
", 1)[2] # => "c
"
4934rb_reg_match_m(int argc, VALUE *argv, VALUE re)
4936 VALUE result = Qnil, str, initpos;
4939 if (rb_scan_args(argc, argv, "11
", &str, &initpos) == 2) {
4940 pos = NUM2LEN(initpos);
4946 pos = reg_match_pos(re, &str, pos, &result);
4950 rb_match_busy(result);
4951 if (!NIL_P(result) && rb_block_given_p()) {
4952 return rb_yield(result);
4959 * match?(string) -> true or false
4960 * match?(string, offset = 0) -> true or false
4962 * Returns <code>true</code> or <code>false</code> to indicate whether the
4963 * regexp is matched or not without updating $~ and other related variables.
4964 * If the second parameter is present, it specifies the position in the string
4965 * to begin the search.
4967 * /R.../.match?("Ruby
") # => true
4968 * /R.../.match?("Ruby
", 1) # => false
4969 * /P.../.match?("Ruby
") # => false
4974rb_reg_match_m_p(int argc, VALUE *argv, VALUE re)
4976 rb_len_t pos = rb_check_arity(argc, 1, 2) > 1 ? NUM2LEN(argv[1]) : 0;
4977 return rb_reg_match_p(re, argv[0], pos);
4981rb_reg_match_p(VALUE re, VALUE str, rb_len_t pos)
4983 if (NIL_P(str)) return Qfalse;
4984 str = SYMBOL_P(str) ? rb_sym2str(str) : StringValue(str);
4987 pos += NUM2LEN(rb_str_length(str));
4988 if (pos < 0) return Qfalse;
4992 const char *beg = rb_str_subpos(str, pos, &len);
4993 if (!beg) return Qfalse;
4994 pos = beg - RSTRING_PTR(str);
4998 struct reg_onig_search_args args = {
5000 .range = RSTRING_LEN(str),
5003 return rb_reg_onig_match(re, str, reg_onig_search, &args, NULL) == ONIG_MISMATCH ? Qfalse : Qtrue;
5007 * Document-method: compile
5009 * Alias for Regexp.new
5013str_to_option(VALUE str)
5018 str = rb_check_string_type(str);
5019 if (NIL_P(str)) return -1;
5020 RSTRING_GETMEM(str, ptr, len);
5021 for (rb_len_t i = 0; i < len; ++i) {
5022 int f = char_to_option(ptr[i]);
5024 rb_raise(rb_eArgError, "unknown regexp option: %
"PRIsVALUE, str);
5032set_timeout(rb_hrtime_t *hrt, VALUE timeout)
5034 double timeout_d = NIL_P(timeout) ? 0.0 : NUM2DBL(timeout);
5035 if (!NIL_P(timeout) && !(timeout_d > 0)) {
5036 rb_raise(rb_eArgError, "invalid timeout: %
"PRIsVALUE, timeout);
5038 double2hrtime(hrt, timeout_d);
5042reg_copy(VALUE copy, VALUE orig)
5045 rb_reg_initialize_check(copy);
5046 if ((r = onig_reg_copy_body(RREGEXP_PTR(copy), RREGEXP_PTR(orig))) != 0) {
5047 /* ONIGERR_MEMORY only */
5048 rb_raise(rb_eRegexpError, "%s
", onig_error_code_to_format(r));
5050 FL_SET_RAW(copy, RREGEXP_INITIALIZED);
5052 RB_OBJ_WRITE(copy, &RREGEXP(copy)->src, RREGEXP(orig)->src);
5053 RREGEXP_PTR(copy)->timelimit = RREGEXP_PTR(orig)->timelimit;
5054 rb_enc_copy(copy, orig);
5055 FL_SET_RAW(copy, FL_TEST_RAW(orig, KCODE_FIXED|REG_ENCODING_NONE));
5056 if (RBASIC_CLASS(copy) == rb_cRegexp) {
5063struct reg_init_args {
5070static VALUE reg_extract_args(int argc, VALUE *argv, struct reg_init_args *args);
5071static VALUE reg_init_args(VALUE self, VALUE str, rb_encoding *enc, int flags);
5075 * Regexp.new(string, options = 0, timeout: nil) -> regexp
5076 * Regexp.new(regexp, timeout: nil) -> regexp
5078 * With argument +string+ given, returns a new regexp with the given string
5081 * r = Regexp.new('foo') # => /foo/
5082 * r.source # => "foo
"
5085 * Passing untrusted input as +string+ is generally not recommended;
5086 * see {Untrusted Patterns}[rdoc-ref:Regexp@Untrusted+Patterns].
5088 * Optional argument +options+ is one of the following:
5090 * - A String of options:
5092 * Regexp.new('foo', 'i') # => /foo/i
5093 * Regexp.new('foo', 'im') # => /foo/im
5095 * - The bit-wise OR of one or more of the constants
5096 * Regexp::EXTENDED, Regexp::IGNORECASE, Regexp::MULTILINE, and
5097 * Regexp::NOENCODING:
5099 * Regexp.new('foo', Regexp::IGNORECASE) # => /foo/i
5100 * Regexp.new('foo', Regexp::EXTENDED) # => /foo/x
5101 * Regexp.new('foo', Regexp::MULTILINE) # => /foo/m
5102 * Regexp.new('foo', Regexp::NOENCODING) # => /foo/n
5103 * flags = Regexp::IGNORECASE | Regexp::EXTENDED | Regexp::MULTILINE
5104 * Regexp.new('foo', flags) # => /foo/mix
5106 * - +nil+ or +false+, which is ignored.
5107 * - Any other truthy value, in which case the regexp will be
5110 * If optional keyword argument +timeout+ is given,
5111 * its float value overrides the timeout interval for the class,
5113 * If +nil+ is passed as +timeout, it uses the timeout interval
5114 * for the class, Regexp.timeout.
5116 * With argument +regexp+ given, returns a new regexp. The source,
5117 * options, timeout are the same as +regexp+. +options+ and +n_flag+
5118 * arguments are ineffective. The timeout can be overridden by
5119 * +timeout+ keyword.
5121 * options = Regexp::MULTILINE
5122 * r = Regexp.new('foo', options, timeout: 1.1) # => /foo/m
5123 * r2 = Regexp.new(r) # => /foo/m
5124 * r2.timeout # => 1.1
5125 * r3 = Regexp.new(r, timeout: 3.14) # => /foo/m
5126 * r3.timeout # => 3.14
5131rb_reg_initialize_m(int argc, VALUE *argv, VALUE self)
5133 struct reg_init_args args;
5134 VALUE re = reg_extract_args(argc, argv, &args);
5137 reg_init_args(self, args.str, args.enc, args.flags);
5143 set_timeout(&RREGEXP_PTR(self)->timelimit, args.timeout);
5144 if (RBASIC_CLASS(self) == rb_cRegexp) {
5152reg_extract_args(int argc, VALUE *argv, struct reg_init_args *args)
5155 rb_encoding *enc = 0;
5156 VALUE str, src, opts = Qundef, kwargs;
5159 rb_scan_args(argc, argv, "11:
", &src, &opts, &kwargs);
5161 args->timeout = Qnil;
5162 if (!NIL_P(kwargs)) {
5163 static ID keywords[1];
5165 keywords[0] = rb_intern_const("timeout
");
5167 rb_get_kwargs(kwargs, keywords, 0, 1, &args->timeout);
5170 if (RB_TYPE_P(src, T_REGEXP)) {
5174 rb_warn("flags ignored
");
5177 flags = rb_reg_options(re);
5178 str = RREGEXP_SRC(re);
5183 if (FIXNUM_P(opts)) flags = FIX2INT(opts);
5184 else if ((f = str_to_option(opts)) >= 0) flags = f;
5185 else if (rb_bool_expected(opts, "ignorecase
", FALSE))
5186 flags = ONIG_OPTION_IGNORECASE;
5188 str = StringValue(src);
5192 args->flags = flags;
5197reg_init_args(VALUE self, VALUE str, rb_encoding *enc, int flags)
5199 if (enc && rb_enc_get(str) != enc)
5200 rb_reg_init_str_enc(self, str, enc, flags);
5202 rb_reg_init_str(self, str, flags);
5207rb_reg_quote(VALUE str)
5209 rb_encoding *enc = rb_enc_get(str);
5213 int ascii_only = rb_enc_str_asciionly_p(str);
5215 s = RSTRING_PTR(str);
5216 send = s + RSTRING_LEN(str);
5218 c = rb_enc_ascget(s, send, &clen, enc);
5220 s += mbclen(s, send, enc);
5224 case '[': case ']': case '{': case '}':
5225 case '(': case ')': case '|': case '-':
5226 case '*': case '.': case '\\':
5227 case '?': case '+': case '^': case '$':
5229 case '\t': case '\f': case '\v': case '\n': case '\r':
5234 tmp = rb_str_new3(str);
5236 rb_enc_associate(tmp, rb_usascii_encoding());
5241 tmp = rb_str_new(0, RSTRING_LEN(str)*2);
5243 rb_enc_associate(tmp, rb_usascii_encoding());
5246 rb_enc_copy(tmp, str);
5248 t = RSTRING_PTR(tmp);
5249 /* copy upto metacharacter */
5250 const char *p = RSTRING_PTR(str);
5251 memcpy(t, p, s - p);
5255 c = rb_enc_ascget(s, send, &clen, enc);
5257 int n = mbclen(s, send, enc);
5265 case '[': case ']': case '{': case '}':
5266 case '(': case ')': case '|': case '-':
5267 case '*': case '.': case '\\':
5268 case '?': case '+': case '^': case '$':
5270 t += rb_enc_mbcput('\\', t, enc);
5273 t += rb_enc_mbcput('\\', t, enc);
5274 t += rb_enc_mbcput(' ', t, enc);
5277 t += rb_enc_mbcput('\\', t, enc);
5278 t += rb_enc_mbcput('t', t, enc);
5281 t += rb_enc_mbcput('\\', t, enc);
5282 t += rb_enc_mbcput('n', t, enc);
5285 t += rb_enc_mbcput('\\', t, enc);
5286 t += rb_enc_mbcput('r', t, enc);
5289 t += rb_enc_mbcput('\\', t, enc);
5290 t += rb_enc_mbcput('f', t, enc);
5293 t += rb_enc_mbcput('\\', t, enc);
5294 t += rb_enc_mbcput('v', t, enc);
5297 t += rb_enc_mbcput(c, t, enc);
5299 rb_str_resize(tmp, t - RSTRING_PTR(tmp));
5306 * Regexp.escape(string) -> new_string
5308 * Returns a new string that escapes any characters
5309 * that have special meaning in a regular expression:
5311 * s = Regexp.escape('\*?{}.') # => "\\\\\\*\\?\\{\\}\\.
"
5313 * For any string +s+, this call returns a MatchData object:
5315 * r = Regexp.new(Regexp.escape(s)) # => /\\\\\\\*\\\?\\\{\\\}\\\./
5316 * r.match(s) # => #<MatchData "\\\\\\*\\?\\{\\}\\.
">
5321rb_reg_s_quote(VALUE c, VALUE str)
5323 return rb_reg_quote(reg_operand(str, TRUE));
5327rb_reg_options(VALUE re)
5332 options = RREGEXP_PTR(re)->options & ARG_REG_OPTION_MASK;
5333 if (RBASIC(re)->flags & KCODE_FIXED) options |= ARG_ENCODING_FIXED;
5334 if (RBASIC(re)->flags & REG_ENCODING_NONE) options |= ARG_ENCODING_NONE;
5339rb_check_regexp_type(VALUE re)
5341 return rb_check_convert_type(re, T_REGEXP, "Regexp
", "to_regexp
");
5346 * Regexp.try_convert(object) -> regexp or nil
5348 * Returns +object+ if it is a regexp:
5350 * Regexp.try_convert(/re/) # => /re/
5352 * Otherwise if +object+ responds to <tt>:to_regexp</tt>,
5353 * calls <tt>object.to_regexp</tt> and returns the result.
5355 * Returns +nil+ if +object+ does not respond to <tt>:to_regexp</tt>.
5357 * Regexp.try_convert('re') # => nil
5359 * Raises an exception unless <tt>object.to_regexp</tt> returns a regexp.
5363rb_reg_s_try_convert(VALUE dummy, VALUE re)
5365 return rb_check_regexp_type(re);
5369rb_reg_s_union(VALUE self, VALUE args0)
5371 rb_len_t argc = RARRAY_LEN(args0);
5375 args[0] = rb_str_new2("(?!)
");
5376 return rb_class_new_instance(1, args, rb_cRegexp);
5378 else if (argc == 1) {
5379 VALUE arg = rb_ary_entry(args0, 0);
5380 VALUE re = rb_check_regexp_type(arg);
5385 quoted = rb_reg_s_quote(Qnil, arg);
5386 return rb_reg_new_str(quoted, 0);
5391 VALUE source = rb_str_buf_new(0);
5392 rb_encoding *result_enc;
5394 int has_asciionly = 0;
5395 rb_encoding *has_ascii_compat_fixed = 0;
5396 rb_encoding *has_ascii_incompat = 0;
5398 for (i = 0; i < argc; i++) {
5400 VALUE e = rb_ary_entry(args0, i);
5403 rb_str_buf_cat_ascii(source, "|
");
5405 v = rb_check_regexp_type(e);
5407 rb_encoding *enc = rb_enc_get(v);
5408 if (!rb_enc_asciicompat(enc)) {
5409 if (!has_ascii_incompat)
5410 has_ascii_incompat = enc;
5411 else if (has_ascii_incompat != enc)
5412 rb_raise(rb_eArgError, "incompatible encodings: %s and %s
",
5413 rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
5415 else if (rb_reg_fixed_encoding_p(v)) {
5416 if (!has_ascii_compat_fixed)
5417 has_ascii_compat_fixed = enc;
5418 else if (has_ascii_compat_fixed != enc)
5419 rb_raise(rb_eArgError, "incompatible encodings: %s and %s
",
5420 rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
5425 v = rb_reg_str_with_term(v, -1);
5430 enc = rb_enc_get(e);
5431 if (!rb_enc_asciicompat(enc)) {
5432 if (!has_ascii_incompat)
5433 has_ascii_incompat = enc;
5434 else if (has_ascii_incompat != enc)
5435 rb_raise(rb_eArgError, "incompatible encodings: %s and %s
",
5436 rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
5438 else if (rb_enc_str_asciionly_p(e)) {
5442 if (!has_ascii_compat_fixed)
5443 has_ascii_compat_fixed = enc;
5444 else if (has_ascii_compat_fixed != enc)
5445 rb_raise(rb_eArgError, "incompatible encodings: %s and %s
",
5446 rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
5448 v = rb_reg_s_quote(Qnil, e);
5450 if (has_ascii_incompat) {
5451 if (has_asciionly) {
5452 rb_raise(rb_eArgError, "ASCII incompatible encoding: %s
",
5453 rb_enc_name(has_ascii_incompat));
5455 if (has_ascii_compat_fixed) {
5456 rb_raise(rb_eArgError, "incompatible encodings: %s and %s
",
5457 rb_enc_name(has_ascii_incompat), rb_enc_name(has_ascii_compat_fixed));
5462 rb_enc_copy(source, v);
5464 rb_str_append(source, v);
5467 if (has_ascii_incompat) {
5468 result_enc = has_ascii_incompat;
5470 else if (has_ascii_compat_fixed) {
5471 result_enc = has_ascii_compat_fixed;
5474 result_enc = rb_ascii8bit_encoding();
5477 rb_enc_associate(source, result_enc);
5478 return rb_class_new_instance(1, &source, rb_cRegexp);
5484 * Regexp.union(*patterns) -> regexp
5485 * Regexp.union(array_of_patterns) -> regexp
5487 * Returns a regexp that is the union of the given patterns:
5489 * r = Regexp.union(%w[cat dog]) # => /cat|dog/
5490 * r.match('cat') # => #<MatchData "cat
">
5491 * r.match('dog') # => #<MatchData "dog
">
5492 * r.match('cog') # => nil
5494 * Each string pattern is escaped so that it is matched literally:
5496 * Regexp.union('penzance') # => /penzance/
5497 * Regexp.union('a+b*c') # => /a\+b\*c/
5498 * Regexp.union('skiing', 'sledding') # => /skiing|sledding/
5499 * Regexp.union(['skiing', 'sledding']) # => /skiing|sledding/
5501 * For each pattern that is a regexp, it is used as is,
5502 * including its flags:
5504 * Regexp.union(/foo/i, /bar/m, /baz/x)
5505 * # => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
5506 * Regexp.union([/foo/i, /bar/m, /baz/x])
5507 * # => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
5509 * With no arguments, returns <tt>/(?!)/</tt>:
5511 * Regexp.union # => /(?!)/
5513 * If any regexp pattern contains captures, the behavior is unspecified.
5517rb_reg_s_union_m(VALUE self, VALUE args)
5520 if (RARRAY_LEN(args) == 1 &&
5521 !NIL_P(v = rb_check_array_type(rb_ary_entry(args, 0)))) {
5522 return rb_reg_s_union(self, v);
5524 return rb_reg_s_union(self, args);
5529 * Regexp.linear_time?(re)
5530 * Regexp.linear_time?(string, options = 0)
5532 * Returns +true+ if matching against <tt>re</tt> can be
5533 * done in linear time to the input string.
5535 * Regexp.linear_time?(/re/) # => true
5537 * Note that this is a property of the ruby interpreter, not of the argument
5538 * regular expression. Identical regexp can or cannot run in linear time
5539 * depending on your ruby binary. Neither forward nor backward compatibility
5540 * is guaranteed about the return value of this method. Our current algorithm
5541 * is (*1) but this is subject to change in the future. Alternative
5542 * implementations can also behave differently. They might always return
5543 * false for everything.
5545 * (*1): https://doi.org/10.1109/SP40001.2021.00032
5549rb_reg_s_linear_time_p(int argc, VALUE *argv, VALUE self)
5551 struct reg_init_args args;
5552 VALUE re = reg_extract_args(argc, argv, &args);
5555 re = reg_init_args(rb_reg_alloc(), args.str, args.enc, args.flags);
5558 return RBOOL(onig_check_linear_time(RREGEXP_PTR(re)));
5563rb_reg_init_copy(VALUE copy, VALUE re)
5565 if (!OBJ_INIT_COPY(copy, re)) return copy;
5567 return reg_copy(copy, re);
5571do_regsub(VALUE str, VALUE src, VALUE regexp, int num_regs, const OnigPosition *beg, const OnigPosition *end)
5576 rb_encoding *str_enc = rb_enc_get(str);
5577 rb_encoding *src_enc = rb_enc_get(src);
5578 int acompat = rb_enc_asciicompat(str_enc);
5580#define ASCGET(s,e,cl) (acompat ? (*(cl)=1,ISASCII((s)[0])?(s)[0]:-1) : rb_enc_ascget((s), (e), (cl), str_enc))
5582 RSTRING_GETMEM(str, s, n);
5587 int c = ASCGET(s, e, &clen);
5591 s += mbclen(s, e, str_enc);
5597 if (c != '\\' || s == e) continue;
5600 val = rb_str_buf_new(ss-p);
5602 rb_enc_str_buf_cat(val, p, ss-p, str_enc);
5604 c = ASCGET(s, e, &clen);
5606 s += mbclen(s, e, str_enc);
5607 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
5615 case '1': case '2': case '3': case '4':
5616 case '5': case '6': case '7': case '8': case '9':
5617 if (!NIL_P(regexp) && onig_noname_group_capture_is_active(RREGEXP_PTR(regexp))) {
5626 if (s < e && ASCGET(s, e, &clen) == '<') {
5627 char *name, *name_end;
5629 name_end = name = s + clen;
5630 while (name_end < e) {
5631 c = ASCGET(name_end, e, &clen);
5632 if (c == '>') break;
5633 name_end += c == -1 ? mbclen(name_end, e, str_enc) : clen;
5636 VALUE n = rb_str_subseq(str, (rb_len_t)(name - RSTRING_PTR(str)),
5637 (rb_len_t)(name_end - name));
5638 struct re_registers tmp = {
5639 .allocated = num_regs,
5640 .num_regs = num_regs,
5641 .beg = (OnigPosition *)beg,
5642 .end = (OnigPosition *)end,
5644 if ((no = NAME_TO_NUMBER(&tmp, regexp, n, name, name_end)) < 1) {
5645 name_to_backref_error(n);
5647 p = s = name_end + clen;
5651 rb_raise(rb_eRuntimeError, "invalid group name reference format
");
5655 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
5664 rb_enc_str_buf_cat(val, RSTRING_PTR(src), beg[0], src_enc);
5668 rb_enc_str_buf_cat(val, RSTRING_PTR(src)+end[0], RSTRING_LEN(src)-end[0], src_enc);
5673 while (beg[no] == -1 && no > 0) no--;
5674 if (no == 0) continue;
5678 rb_enc_str_buf_cat(val, s-clen, clen, str_enc);
5682 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
5687 if (no >= num_regs) continue;
5688 if (beg[no] == -1) continue;
5689 rb_enc_str_buf_cat(val, RSTRING_PTR(src)+beg[no], end[no]-beg[no], src_enc);
5693 if (!val) return str;
5695 rb_enc_str_buf_cat(val, p, e-p, str_enc);
5703rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp)
5705 return do_regsub(str, src, regexp, regs->num_regs, regs->beg, regs->end);
5709rb_reg_regsub_match(VALUE str, VALUE src, VALUE match)
5711 return do_regsub(str, src, RMATCH(match)->regexp,
5712 RMATCH_NREGS(match), RMATCH_BEG_PTR(match), RMATCH_END_PTR(match));
5716ignorecase_getter(ID _x, VALUE *_y)
5718 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "variable $= is no longer effective
");
5723ignorecase_setter(VALUE val, ID id, VALUE *_)
5725 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "variable $= is no longer effective; ignored
");
5731 VALUE match = rb_backref_get();
5733 if (NIL_P(match)) return Qnil;
5734 rb_match_busy(match);
5739get_LAST_MATCH_INFO(ID _x, VALUE *_y)
5741 return match_getter();
5745match_setter(VALUE val, ID _x, VALUE *_y)
5748 Check_Type(val, T_MATCH);
5751 rb_backref_set(val);
5756 * Regexp.last_match -> matchdata or nil
5757 * Regexp.last_match(n) -> string or nil
5758 * Regexp.last_match(name) -> string or nil
5760 * With no argument, returns the value of <tt>$~</tt>,
5761 * which is the result of the most recent pattern match
5762 * (see {Regexp global variables}[rdoc-ref:Regexp@Global+Variables]):
5764 * /c(.)t/ =~ 'cat' # => 0
5765 * Regexp.last_match # => #<MatchData "cat
" 1:"a
">
5766 * /a/ =~ 'foo' # => nil
5767 * Regexp.last_match # => nil
5769 * With non-negative integer argument +n+, returns the _n_th field in the
5770 * matchdata, if any, or nil if none:
5772 * /c(.)t/ =~ 'cat' # => 0
5773 * Regexp.last_match(0) # => "cat
"
5774 * Regexp.last_match(1) # => "a
"
5775 * Regexp.last_match(2) # => nil
5777 * With negative integer argument +n+, counts backwards from the last field:
5779 * Regexp.last_match(-1) # => "a
"
5781 * With string or symbol argument +name+,
5782 * returns the string value for the named capture, if any:
5784 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ 'var = val'
5785 * Regexp.last_match # => #<MatchData "var = val
" lhs:"var
"rhs:"val
">
5786 * Regexp.last_match(:lhs) # => "var
"
5787 * Regexp.last_match('rhs') # => "val
"
5788 * Regexp.last_match('foo') # Raises IndexError.
5793rb_reg_s_last_match(int argc, VALUE *argv, VALUE _)
5795 if (rb_check_arity(argc, 0, 1) == 1) {
5796 VALUE match = rb_backref_get();
5798 if (NIL_P(match)) return Qnil;
5799 n = match_backref_number(match, argv[0]);
5800 return rb_reg_nth_match(n, match);
5802 return match_getter();
5806re_warn(const char *s)
5811// This function is periodically called during regexp matching
5813rb_reg_timeout_p(regex_t *reg, void *end_time_)
5815 rb_hrtime_t *end_time = (rb_hrtime_t *)end_time_;
5817 if (*end_time == 0) {
5818 // This is the first time to check interrupts;
5819 // just measure the current time and determine the end time
5820 // if timeout is set.
5821 rb_hrtime_t timelimit = reg->timelimit;
5824 // no per-object timeout.
5825 timelimit = rb_reg_match_time_limit;
5829 *end_time = rb_hrtime_add(timelimit, rb_hrtime_now());
5832 // no timeout is set
5833 *end_time = RB_HRTIME_MAX;
5837 if (*end_time < rb_hrtime_now()) {
5838 // Timeout has exceeded
5848 * Regexp.timeout -> float or nil
5850 * It returns the current default timeout interval for Regexp matching in second.
5851 * +nil+ means no default timeout configuration.
5855rb_reg_s_timeout_get(VALUE dummy)
5857 double d = hrtime2double(rb_reg_match_time_limit);
5858 if (d == 0.0) return Qnil;
5864 * Regexp.timeout = float or nil
5866 * It sets the default timeout interval for Regexp matching in second.
5867 * +nil+ means no default timeout configuration.
5868 * This configuration is process-global. If you want to set timeout for
5869 * each Regexp, use +timeout+ keyword for <code>Regexp.new</code>.
5871 * Regexp.timeout = 1
5872 * /^a*b?a*$/ =~ "a
" * 100000 + "x
" #=> regexp match timeout (RuntimeError)
5876rb_reg_s_timeout_set(VALUE dummy, VALUE timeout)
5878 rb_ractor_ensure_main_ractor("can not access
Regexp.timeout from non-main Ractors
");
5880 set_timeout(&rb_reg_match_time_limit, timeout);
5887 * rxp.timeout -> float or nil
5889 * It returns the timeout interval for Regexp matching in second.
5890 * +nil+ means no default timeout configuration.
5892 * This configuration is per-object. The global configuration set by
5893 * Regexp.timeout= is ignored if per-object configuration is set.
5895 * re = Regexp.new("^a*b?a*$
", timeout: 1)
5896 * re.timeout #=> 1.0
5897 * re =~ "a
" * 100000 + "x
" #=> regexp match timeout (RuntimeError)
5901rb_reg_timeout_get(VALUE re)
5904 double d = hrtime2double(RREGEXP_PTR(re)->timelimit);
5905 if (d == 0.0) return Qnil;
5910 * Document-class: RegexpError
5912 * Raised when given an invalid regexp expression.
5916 * <em>raises the exception:</em>
5918 * RegexpError: target of repeat operator is not specified: /?/
5922 * Document-class: Regexp
5924 * :include: doc/_regexp.rdoc
5930 rb_eRegexpError = rb_define_class("RegexpError
", rb_eStandardError);
5932 onigenc_set_default_encoding(ONIG_ENCODING_ASCII);
5933 onig_set_warn_func(re_warn);
5934 onig_set_verb_warn_func(re_warn);
5936 rb_define_virtual_variable("$~
", get_LAST_MATCH_INFO, match_setter);
5937 rb_define_virtual_variable("$&
", last_match_getter, 0);
5938 rb_define_virtual_variable("$`
", prematch_getter, 0);
5939 rb_define_virtual_variable("$
'", postmatch_getter, 0);
5940 rb_define_virtual_variable("$+", last_paren_match_getter, 0);
5942 rb_gvar_ractor_local("$~");
5943 rb_gvar_ractor_local("$&");
5944 rb_gvar_ractor_local("$`");
5945 rb_gvar_ractor_local("$'");
5946 rb_gvar_ractor_local("$+
");
5947 rb_gvar_box_dynamic("$~
");
5948 rb_gvar_box_ready("$&
");
5949 rb_gvar_box_ready("$`
");
5950 rb_gvar_box_ready("$
'");
5951 rb_gvar_box_ready("$+");
5953 rb_define_virtual_variable("$=", ignorecase_getter, ignorecase_setter);
5955 rb_cRegexp = rb_define_class("Regexp", rb_cObject);
5956 rb_define_alloc_func(rb_cRegexp, rb_reg_s_alloc);
5957 rb_define_singleton_method(rb_cRegexp, "compile", rb_class_new_instance_pass_kw, -1);
5958 rb_define_singleton_method(rb_cRegexp, "quote", rb_reg_s_quote, 1);
5959 rb_define_singleton_method(rb_cRegexp, "escape", rb_reg_s_quote, 1);
5960 rb_define_singleton_method(rb_cRegexp, "union", rb_reg_s_union_m, -2);
5961 rb_define_singleton_method(rb_cRegexp, "last_match", rb_reg_s_last_match, -1);
5962 rb_define_singleton_method(rb_cRegexp, "try_convert", rb_reg_s_try_convert, 1);
5963 rb_define_singleton_method(rb_cRegexp, "linear_time?", rb_reg_s_linear_time_p, -1);
5965 rb_define_method(rb_cRegexp, "initialize", rb_reg_initialize_m, -1);
5966 rb_define_method(rb_cRegexp, "initialize_copy", rb_reg_init_copy, 1);
5967 rb_define_method(rb_cRegexp, "hash", rb_reg_hash, 0);
5968 rb_define_method(rb_cRegexp, "eql?", rb_reg_equal, 1);
5969 rb_define_method(rb_cRegexp, "==", rb_reg_equal, 1);
5970 rb_define_method(rb_cRegexp, "=~", rb_reg_match, 1);
5971 rb_define_method(rb_cRegexp, "===", rb_reg_eqq, 1);
5972 rb_define_method(rb_cRegexp, "~", rb_reg_match2, 0);
5973 rb_define_method(rb_cRegexp, "match", rb_reg_match_m, -1);
5974 rb_define_method(rb_cRegexp, "match?", rb_reg_match_m_p, -1);
5975 rb_define_method(rb_cRegexp, "to_s", rb_reg_to_s, 0);
5976 rb_define_method(rb_cRegexp, "inspect", rb_reg_inspect, 0);
5977 rb_define_method(rb_cRegexp, "source", rb_reg_source, 0);
5978 rb_define_method(rb_cRegexp, "casefold?", rb_reg_casefold_p, 0);
5979 rb_define_method(rb_cRegexp, "options", rb_reg_options_m, 0);
5980 rb_define_method(rb_cRegexp, "encoding", rb_obj_encoding, 0); /* in encoding.c */
5981 rb_define_method(rb_cRegexp, "fixed_encoding?", rb_reg_fixed_encoding_p, 0);
5982 rb_define_method(rb_cRegexp, "names", rb_reg_names, 0);
5983 rb_define_method(rb_cRegexp, "named_captures", rb_reg_named_captures, 0);
5984 rb_define_method(rb_cRegexp, "timeout", rb_reg_timeout_get, 0);
5986 /* Raised when regexp matching timed out. */
5987 rb_eRegexpTimeoutError = rb_define_class_under(rb_cRegexp, "TimeoutError", rb_eRegexpError);
5988 rb_define_singleton_method(rb_cRegexp, "timeout", rb_reg_s_timeout_get, 0);
5989 rb_define_singleton_method(rb_cRegexp, "timeout=", rb_reg_s_timeout_set, 1);
5991 /* see Regexp.options and Regexp.new */
5992 rb_define_const(rb_cRegexp, "IGNORECASE", INT2FIX(ONIG_OPTION_IGNORECASE));
5993 /* see Regexp.options and Regexp.new */
5994 rb_define_const(rb_cRegexp, "EXTENDED", INT2FIX(ONIG_OPTION_EXTEND));
5995 /* see Regexp.options and Regexp.new */
5996 rb_define_const(rb_cRegexp, "MULTILINE", INT2FIX(ONIG_OPTION_MULTILINE));
5997 /* see Regexp.options and Regexp.new */
5998 rb_define_const(rb_cRegexp, "FIXEDENCODING", INT2FIX(ARG_ENCODING_FIXED));
5999 /* see Regexp.options and Regexp.new */
6000 rb_define_const(rb_cRegexp, "NOENCODING", INT2FIX(ARG_ENCODING_NONE));
6002 rb_global_variable(®_cache);
6004 rb_cMatch = rb_define_class("MatchData", rb_cObject);
6005 rb_define_alloc_func(rb_cMatch, match_alloc);
6006 rb_undef_method(CLASS_OF(rb_cMatch), "new");
6007 rb_undef_method(CLASS_OF(rb_cMatch), "allocate");
6009 rb_define_method(rb_cMatch, "initialize_copy", rb_match_init_copy, 1);
6010 rb_define_method(rb_cMatch, "regexp", match_regexp, 0);
6011 rb_define_method(rb_cMatch, "names", match_names, 0);
6012 rb_define_method(rb_cMatch, "size", match_size, 0);
6013 rb_define_method(rb_cMatch, "length", match_size, 0);
6014 rb_define_method(rb_cMatch, "offset", match_offset, 1);
6015 rb_define_method(rb_cMatch, "byteoffset", match_byteoffset, 1);
6016 rb_define_method(rb_cMatch, "bytebegin", match_bytebegin, 1);
6017 rb_define_method(rb_cMatch, "byteend", match_byteend, 1);
6018 rb_define_method(rb_cMatch, "begin", match_begin, 1);
6019 rb_define_method(rb_cMatch, "end", match_end, 1);
6020 rb_define_method(rb_cMatch, "match", match_nth, 1);
6021 rb_define_method(rb_cMatch, "match_length", match_nth_length, 1);
6022 rb_define_method(rb_cMatch, "to_a", match_to_a, 0);
6023 rb_define_method(rb_cMatch, "[]", match_aref, -1);
6024 rb_define_method(rb_cMatch, "captures", match_captures, 0);
6025 rb_define_alias(rb_cMatch, "deconstruct", "captures");
6026 rb_define_method(rb_cMatch, "named_captures", match_named_captures, -1);
6027 rb_define_method(rb_cMatch, "deconstruct_keys", match_deconstruct_keys, 1);
6028 rb_define_method(rb_cMatch, "values_at", match_values_at, -1);
6029 rb_define_method(rb_cMatch, "pre_match", rb_reg_match_pre, 0);
6030 rb_define_method(rb_cMatch, "post_match", rb_reg_match_post, 0);
6031 rb_define_method(rb_cMatch, "to_s", match_to_s, 0);
6032 rb_define_method(rb_cMatch, "inspect", match_inspect, 0);
6033 rb_define_method(rb_cMatch, "string", match_string, 0);
6034 rb_define_method(rb_cMatch, "hash", match_hash, 0);
6035 rb_define_method(rb_cMatch, "eql?", match_equal, 1);
6036 rb_define_method(rb_cMatch, "==", match_equal, 1);
6037 rb_define_method(rb_cMatch, "integer_at", match_integer_at, -1);
#define RUBY_ATOMIC_PTR_LOAD(var)
Identical to RUBY_ATOMIC_LOAD, except it expects its arguments are void*.
#define RUBY_ATOMIC_PTR_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are void*.
#define ISSPACE
@old{rb_isspace}
static bool rb_enc_isprint(OnigCodePoint c, rb_encoding *enc)
Identical to rb_isprint(), except it additionally takes an encoding.
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
struct re_pattern_buffer Regexp
Old name of re_pattern_buffer.
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
#define ALLOC
Old name of RB_ALLOC.
#define T_STRING
Old name of RUBY_T_STRING.
#define ENC_CODERANGE_CLEAN_P(cr)
Old name of RB_ENC_CODERANGE_CLEAN_P.
#define INT2FIX
Old name of RB_INT2FIX.
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
#define LEN2NUM
Old name of RB_LEN2NUM.
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
#define ENC_CODERANGE_UNKNOWN
Old name of RUBY_ENC_CODERANGE_UNKNOWN.
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
#define FIX2INT
Old name of RB_FIX2INT.
#define ALLOC_N
Old name of RB_ALLOC_N.
#define rb_str_new3
Old name of rb_str_new_shared.
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
#define FL_SET
Old name of RB_FL_SET.
#define rb_exc_new3
Old name of rb_exc_new_str.
#define MBCLEN_INVALID_P(ret)
Old name of ONIGENC_MBCLEN_INVALID_P.
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
#define MBCLEN_NEEDMORE_P(ret)
Old name of ONIGENC_MBCLEN_NEEDMORE_P.
#define NUM2INT
Old name of RB_NUM2INT.
#define INT2NUM
Old name of RB_INT2NUM.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define ENC_CODERANGE_BROKEN
Old name of RUBY_ENC_CODERANGE_BROKEN.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
#define scan_hex(s, l, e)
Old name of ruby_scan_hex.
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
#define MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
#define T_MATCH
Old name of RUBY_T_MATCH.
#define FL_TEST
Old name of RB_FL_TEST.
#define FL_UNSET
Old name of RB_FL_UNSET.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define scan_oct(s, l, e)
Old name of ruby_scan_oct.
#define NUM2LEN
Old name of RB_NUM2LEN.
#define rb_ary_new2
Old name of rb_ary_new_capa.
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
#define rb_str_new4
Old name of rb_str_new_frozen.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
#define T_REGEXP
Old name of RUBY_T_REGEXP.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
VALUE rb_eRegexpError
RegexpError exception.
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
VALUE rb_eTypeError
TypeError exception.
VALUE rb_eEncCompatError
Encoding::CompatibilityError exception.
VALUE rb_eRuntimeError
RuntimeError exception.
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
VALUE rb_eIndexError
IndexError exception.
VALUE rb_obj_reveal(VALUE obj, VALUE klass)
Make a hidden object visible again.
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
VALUE rb_cMatch
MatchData class.
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
VALUE rb_cRegexp
Regexp class.
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
rb_encoding * rb_ascii8bit_encoding(void)
Queries the encoding that represents ASCII-8BIT a.k.a.
rb_encoding * rb_default_internal_encoding(void)
Queries the "default internal" encoding.
static char * rb_enc_left_char_head(const char *s, const char *p, const char *e, rb_encoding *enc)
Queries the left boundary of a character.
int rb_utf8_encindex(void)
Identical to rb_utf8_encoding(), except it returns the encoding's index instead of the encoding itsel...
int rb_ascii8bit_encindex(void)
Identical to rb_ascii8bit_encoding(), except it returns the encoding's index instead of the encoding ...
rb_encoding * rb_default_external_encoding(void)
Queries the "default external" encoding.
int rb_char_to_option_kcode(int c, int *option, int *kcode)
Converts a character option to its encoding.
static int rb_enc_mbmaxlen(rb_encoding *enc)
Queries the maximum number of bytes that the passed encoding needs to represent a character.
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
VALUE rb_enc_reg_new(const char *ptr, rb_len_t len, rb_encoding *enc, int opts)
Identical to rb_reg_new(), except it additionally takes an encoding.
rb_len_t rb_enc_strlen(const char *head, const char *tail, rb_encoding *enc)
Counts the number of characters of the passed string, according to the passed encoding.
rb_len_t rb_memsearch(const void *x, rb_len_t m, const void *y, rb_len_t n, rb_encoding *enc)
Looks for the passed string in the passed buffer.
VALUE rb_str_encode(VALUE str, VALUE to, int ecflags, VALUE ecopts)
Converts the contents of the passed string from its encoding to the passed one.
void rb_memerror(void)
Triggers out-of-memory error.
void rb_gc(void)
Triggers a GC process.
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_resize(VALUE ary, rb_len_t len)
Expands or shrinks the passed array to the passed length.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
int rb_uv_to_utf8(char buf[6], unsigned long uv)
Encodes a Unicode codepoint into its UTF-8 representation.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
VALUE rb_hash_new(void)
Creates a new, empty hash object.
VALUE rb_backref_get(void)
Queries the last match, or Regexp.last_match, or the $~.
void rb_backref_set(VALUE md)
Updates $~.
VALUE rb_range_beg_len(VALUE range, rb_len_t *begp, rb_len_t *lenp, rb_len_t len, int err)
Deconstructs a numerical range.
int rb_reg_backref_number(VALUE match, VALUE backref)
Queries the index of the given named capture.
int rb_reg_options(VALUE re)
Queries the options of the passed regular expression.
VALUE rb_reg_last_match(VALUE md)
This just returns the argument, stringified.
void rb_match_busy(VALUE md)
Asserts that the given MatchData is "occupied".
VALUE rb_reg_nth_match(int n, VALUE md)
Queries the nth captured substring.
VALUE rb_reg_match_post(VALUE md)
The portion of the original string after the given match.
VALUE rb_reg_nth_defined(int n, VALUE md)
Identical to rb_reg_nth_match(), except it just returns Boolean.
VALUE rb_reg_match_pre(VALUE md)
The portion of the original string before the given match.
VALUE rb_reg_new_str(VALUE src, int opts)
Identical to rb_reg_new(), except it takes the expression in Ruby's string instead of C's.
VALUE rb_reg_match_last(VALUE md)
The portion of the original string that captured at the very last.
VALUE rb_reg_new(const char *src, rb_len_t len, int opts)
Creates a new Regular expression.
VALUE rb_str_subseq(VALUE str, rb_len_t beg, rb_len_t len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
#define rb_hash_end(h)
Just another name of st_hash_end.
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
#define rb_str_buf_cat
Just another name of rb_str_cat.
VALUE rb_str_dup(VALUE str)
Duplicates a string.
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
st_index_t rb_memhash(const void *ptr, rb_len_t len)
This is a universal hash function.
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
void rb_thread_check_ints(void)
Checks for interrupts.
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
int capa
Designed capacity of the buffer.
int len
Length of the buffer.
rb_len_t rb_reg_search(VALUE re, VALUE str, rb_len_t pos, int dir)
Runs the passed regular expression over the passed string.
regex_t * rb_reg_prepare_re(VALUE re, VALUE str)
Exercises various checks and preprocesses so that the given regular expression can be applied to the ...
OnigPosition rb_reg_onig_match(VALUE re, VALUE str, OnigPosition(*match)(regex_t *reg, VALUE str, struct re_registers *regs, void *args), void *args, struct re_registers *regs)
Runs a regular expression match using function match.
VALUE rb_reg_regcomp(VALUE str)
Creates a new instance of rb_cRegexp.
VALUE rb_reg_quote(VALUE str)
Escapes any characters that would have special meaning in a regular expression.
int rb_reg_region_copy(struct re_registers *dst, const struct re_registers *src)
Duplicates a match data.
rb_len_t rb_reg_adjust_startpos(VALUE re, VALUE str, rb_len_t pos, int dir)
Tell us if this is a wrong idea, but it seems this function has no usage at all.
unsigned long ruby_scan_hex(const char *str, size_t len, size_t *ret)
Interprets the passed string a hexadecimal unsigned integer.
unsigned long ruby_scan_oct(const char *str, size_t len, size_t *consumed)
Interprets the passed string as an octal unsigned integer.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define RB_ALLOCV_N(type, v, n)
Allocates a memory region, possibly on stack.
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
#define RB_ALLOCV_END(v)
Polite way to declare that the given array is not used any longer.
#define RARRAY_LEN
Just another name of rb_array_len.
#define RARRAY_AREF(a, i)
References an object in an array.
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
#define RBASIC(obj)
Convenient casting macro.
#define RMATCH(obj)
Convenient casting macro.
#define RREGEXP(obj)
Convenient casting macro.
static struct re_pattern_buffer * RREGEXP_PTR(VALUE rexp)
Convenient getter function.
static VALUE RREGEXP_SRC(VALUE rexp)
Convenient getter function.
static rb_len_t RREGEXP_SRC_LEN(VALUE rexp)
Convenient getter function.
static char * RREGEXP_SRC_PTR(VALUE rexp)
Convenient getter function.
#define StringValue(v)
Ensures that the parameter object is a String.
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Ruby object's base components.
VALUE flags
Per-object flags.
Regular expression execution context.
VALUE regexp
The expression of this match.
struct rmatch_offset * char_offset
Capture group offsets, in C array.
union RMatch::@357327212031205367147161324375004050200256000107 as
"Registers" of a match.
int char_offset_num_allocated
Number of rmatch_offset that rmatch::char_offset holds.
int num_regs
Number of capture-group registers.
int capa
Capacity of as.embed, in OnigPosition slots.
VALUE str
The target string that the match was made against.
Ruby's regular expression.
struct rb_regexp_variant * variants
Compiled variants for other encodings.
struct RBasic basic
Basic part, including flags and class.
const VALUE src
Source code of this expression.
Represents the region of a capture group.
rb_len_t end
End of a group.
rb_len_t beg
Beginning of a group.
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
uintptr_t VALUE
Type that represents a Ruby object.
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.