Ruby 3.3.2p78 (2024-05-30 revision e5a195edf62fe1bf7146a191da13fa1c4fecbd71)
re.c
1/**********************************************************************
2
3 re.c -
4
5 $Author$
6 created at: Mon Aug 9 18:24:49 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <ctype.h>
15
16#include "encindex.h"
17#include "hrtime.h"
18#include "internal.h"
19#include "internal/encoding.h"
20#include "internal/hash.h"
21#include "internal/imemo.h"
22#include "internal/re.h"
23#include "internal/string.h"
24#include "internal/object.h"
25#include "internal/ractor.h"
26#include "internal/variable.h"
27#include "regint.h"
28#include "ruby/encoding.h"
29#include "ruby/re.h"
30#include "ruby/util.h"
31
32VALUE rb_eRegexpError, rb_eRegexpTimeoutError;
33
34typedef char onig_errmsg_buffer[ONIG_MAX_ERROR_MESSAGE_LEN];
35#define errcpy(err, msg) strlcpy((err), (msg), ONIG_MAX_ERROR_MESSAGE_LEN)
36
37#define BEG(no) (regs->beg[(no)])
38#define END(no) (regs->end[(no)])
39
40#if 'a' == 97 /* it's ascii */
41static const char casetable[] = {
42 '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
43 '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
44 '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
45 '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
46 /* ' ' '!' '"' '#' '$' '%' '&' ''' */
47 '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
48 /* '(' ')' '*' '+' ',' '-' '.' '/' */
49 '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
50 /* '0' '1' '2' '3' '4' '5' '6' '7' */
51 '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
52 /* '8' '9' ':' ';' '<' '=' '>' '?' */
53 '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
54 /* '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' */
55 '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
56 /* 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' */
57 '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
58 /* 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' */
59 '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
60 /* 'X' 'Y' 'Z' '[' '\' ']' '^' '_' */
61 '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
62 /* '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' */
63 '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
64 /* 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' */
65 '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
66 /* 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' */
67 '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
68 /* 'x' 'y' 'z' '{' '|' '}' '~' */
69 '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
70 '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
71 '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
72 '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
73 '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
74 '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
75 '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
76 '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
77 '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
78 '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
79 '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
80 '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
81 '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
82 '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
83 '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
84 '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
85 '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
86};
87#else
88# error >>> "You lose. You will need a translation table for your character set." <<<
89#endif
90
91// The process-global timeout for regexp matching
92rb_hrtime_t rb_reg_match_time_limit = 0;
93
94int
95rb_memcicmp(const void *x, const void *y, long len)
96{
97 const unsigned char *p1 = x, *p2 = y;
98 int tmp;
99
100 while (len--) {
101 if ((tmp = casetable[(unsigned)*p1++] - casetable[(unsigned)*p2++]))
102 return tmp;
103 }
104 return 0;
105}
106
107#ifdef HAVE_MEMMEM
108static inline long
109rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n)
110{
111 const unsigned char *y;
112
113 if ((y = memmem(ys, n, xs, m)) != NULL)
114 return y - ys;
115 else
116 return -1;
117}
118#else
119static inline long
120rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n)
121{
122 const unsigned char *x = xs, *xe = xs + m;
123 const unsigned char *y = ys, *ye = ys + n;
124#define VALUE_MAX ((VALUE)~(VALUE)0)
125 VALUE hx, hy, mask = VALUE_MAX >> ((SIZEOF_VALUE - m) * CHAR_BIT);
126
127 if (m > SIZEOF_VALUE)
128 rb_bug("!!too long pattern string!!");
129
130 if (!(y = memchr(y, *x, n - m + 1)))
131 return -1;
132
133 /* Prepare hash value */
134 for (hx = *x++, hy = *y++; x < xe; ++x, ++y) {
135 hx <<= CHAR_BIT;
136 hy <<= CHAR_BIT;
137 hx |= *x;
138 hy |= *y;
139 }
140 /* Searching */
141 while (hx != hy) {
142 if (y == ye)
143 return -1;
144 hy <<= CHAR_BIT;
145 hy |= *y;
146 hy &= mask;
147 y++;
148 }
149 return y - ys - m;
150}
151#endif
152
153static inline long
154rb_memsearch_qs(const unsigned char *xs, long m, const unsigned char *ys, long n)
155{
156 const unsigned char *x = xs, *xe = xs + m;
157 const unsigned char *y = ys;
158 VALUE i, qstable[256];
159
160 /* Preprocessing */
161 for (i = 0; i < 256; ++i)
162 qstable[i] = m + 1;
163 for (; x < xe; ++x)
164 qstable[*x] = xe - x;
165 /* Searching */
166 for (; y + m <= ys + n; y += *(qstable + y[m])) {
167 if (*xs == *y && memcmp(xs, y, m) == 0)
168 return y - ys;
169 }
170 return -1;
171}
172
173static inline unsigned int
174rb_memsearch_qs_utf8_hash(const unsigned char *x)
175{
176 register const unsigned int mix = 8353;
177 register unsigned int h = *x;
178 if (h < 0xC0) {
179 return h + 256;
180 }
181 else if (h < 0xE0) {
182 h *= mix;
183 h += x[1];
184 }
185 else if (h < 0xF0) {
186 h *= mix;
187 h += x[1];
188 h *= mix;
189 h += x[2];
190 }
191 else if (h < 0xF5) {
192 h *= mix;
193 h += x[1];
194 h *= mix;
195 h += x[2];
196 h *= mix;
197 h += x[3];
198 }
199 else {
200 return h + 256;
201 }
202 return (unsigned char)h;
203}
204
205static inline long
206rb_memsearch_qs_utf8(const unsigned char *xs, long m, const unsigned char *ys, long n)
207{
208 const unsigned char *x = xs, *xe = xs + m;
209 const unsigned char *y = ys;
210 VALUE i, qstable[512];
211
212 /* Preprocessing */
213 for (i = 0; i < 512; ++i) {
214 qstable[i] = m + 1;
215 }
216 for (; x < xe; ++x) {
217 qstable[rb_memsearch_qs_utf8_hash(x)] = xe - x;
218 }
219 /* Searching */
220 for (; y + m <= ys + n; y += qstable[rb_memsearch_qs_utf8_hash(y+m)]) {
221 if (*xs == *y && memcmp(xs, y, m) == 0)
222 return y - ys;
223 }
224 return -1;
225}
226
227static inline long
228rb_memsearch_with_char_size(const unsigned char *xs, long m, const unsigned char *ys, long n, int char_size)
229{
230 const unsigned char *x = xs, x0 = *xs, *y = ys;
231
232 for (n -= m; n >= 0; n -= char_size, y += char_size) {
233 if (x0 == *y && memcmp(x+1, y+1, m-1) == 0)
234 return y - ys;
235 }
236 return -1;
237}
238
239static inline long
240rb_memsearch_wchar(const unsigned char *xs, long m, const unsigned char *ys, long n)
241{
242 return rb_memsearch_with_char_size(xs, m, ys, n, 2);
243}
244
245static inline long
246rb_memsearch_qchar(const unsigned char *xs, long m, const unsigned char *ys, long n)
247{
248 return rb_memsearch_with_char_size(xs, m, ys, n, 4);
249}
250
251long
252rb_memsearch(const void *x0, long m, const void *y0, long n, rb_encoding *enc)
253{
254 const unsigned char *x = x0, *y = y0;
255
256 if (m > n) return -1;
257 else if (m == n) {
258 return memcmp(x0, y0, m) == 0 ? 0 : -1;
259 }
260 else if (m < 1) {
261 return 0;
262 }
263 else if (m == 1) {
264 const unsigned char *ys = memchr(y, *x, n);
265
266 if (ys)
267 return ys - y;
268 else
269 return -1;
270 }
271 else if (LIKELY(rb_enc_mbminlen(enc) == 1)) {
272 if (m <= SIZEOF_VALUE) {
273 return rb_memsearch_ss(x0, m, y0, n);
274 }
275 else if (enc == rb_utf8_encoding()){
276 return rb_memsearch_qs_utf8(x0, m, y0, n);
277 }
278 }
279 else if (LIKELY(rb_enc_mbminlen(enc) == 2)) {
280 return rb_memsearch_wchar(x0, m, y0, n);
281 }
282 else if (LIKELY(rb_enc_mbminlen(enc) == 4)) {
283 return rb_memsearch_qchar(x0, m, y0, n);
284 }
285 return rb_memsearch_qs(x0, m, y0, n);
286}
287
288#define REG_ENCODING_NONE FL_USER6
289
290#define KCODE_FIXED FL_USER4
291
292#define ARG_REG_OPTION_MASK \
293 (ONIG_OPTION_IGNORECASE|ONIG_OPTION_MULTILINE|ONIG_OPTION_EXTEND)
294#define ARG_ENCODING_FIXED 16
295#define ARG_ENCODING_NONE 32
296
297static int
298char_to_option(int c)
299{
300 int val;
301
302 switch (c) {
303 case 'i':
304 val = ONIG_OPTION_IGNORECASE;
305 break;
306 case 'x':
307 val = ONIG_OPTION_EXTEND;
308 break;
309 case 'm':
310 val = ONIG_OPTION_MULTILINE;
311 break;
312 default:
313 val = 0;
314 break;
315 }
316 return val;
317}
318
319enum { OPTBUF_SIZE = 4 };
320
321static char *
322option_to_str(char str[OPTBUF_SIZE], int options)
323{
324 char *p = str;
325 if (options & ONIG_OPTION_MULTILINE) *p++ = 'm';
326 if (options & ONIG_OPTION_IGNORECASE) *p++ = 'i';
327 if (options & ONIG_OPTION_EXTEND) *p++ = 'x';
328 *p = 0;
329 return str;
330}
331
332extern int
333rb_char_to_option_kcode(int c, int *option, int *kcode)
334{
335 *option = 0;
336
337 switch (c) {
338 case 'n':
339 *kcode = rb_ascii8bit_encindex();
340 return (*option = ARG_ENCODING_NONE);
341 case 'e':
342 *kcode = ENCINDEX_EUC_JP;
343 break;
344 case 's':
345 *kcode = ENCINDEX_Windows_31J;
346 break;
347 case 'u':
348 *kcode = rb_utf8_encindex();
349 break;
350 default:
351 *kcode = -1;
352 return (*option = char_to_option(c));
353 }
354 *option = ARG_ENCODING_FIXED;
355 return 1;
356}
357
358static void
359rb_reg_check(VALUE re)
360{
361 if (!RREGEXP_PTR(re) || !RREGEXP_SRC(re) || !RREGEXP_SRC_PTR(re)) {
362 rb_raise(rb_eTypeError, "uninitialized Regexp");
363 }
364}
365
366static void
367rb_reg_expr_str(VALUE str, const char *s, long len,
368 rb_encoding *enc, rb_encoding *resenc, int term)
369{
370 const char *p, *pend;
371 int cr = ENC_CODERANGE_UNKNOWN;
372 int need_escape = 0;
373 int c, clen;
374
375 p = s; pend = p + len;
376 rb_str_coderange_scan_restartable(p, pend, enc, &cr);
377 if (rb_enc_asciicompat(enc) && ENC_CODERANGE_CLEAN_P(cr)) {
378 while (p < pend) {
379 c = rb_enc_ascget(p, pend, &clen, enc);
380 if (c == -1) {
381 if (enc == resenc) {
382 p += mbclen(p, pend, enc);
383 }
384 else {
385 need_escape = 1;
386 break;
387 }
388 }
389 else if (c != term && rb_enc_isprint(c, enc)) {
390 p += clen;
391 }
392 else {
393 need_escape = 1;
394 break;
395 }
396 }
397 }
398 else {
399 need_escape = 1;
400 }
401
402 if (!need_escape) {
403 rb_str_buf_cat(str, s, len);
404 }
405 else {
406 int unicode_p = rb_enc_unicode_p(enc);
407 p = s;
408 while (p<pend) {
409 c = rb_enc_ascget(p, pend, &clen, enc);
410 if (c == '\\' && p+clen < pend) {
411 int n = clen + mbclen(p+clen, pend, enc);
412 rb_str_buf_cat(str, p, n);
413 p += n;
414 continue;
415 }
416 else if (c == -1) {
417 clen = rb_enc_precise_mbclen(p, pend, enc);
418 if (!MBCLEN_CHARFOUND_P(clen)) {
419 c = (unsigned char)*p;
420 clen = 1;
421 goto hex;
422 }
423 if (resenc) {
424 unsigned int c = rb_enc_mbc_to_codepoint(p, pend, enc);
425 rb_str_buf_cat_escaped_char(str, c, unicode_p);
426 }
427 else {
428 clen = MBCLEN_CHARFOUND_LEN(clen);
429 rb_str_buf_cat(str, p, clen);
430 }
431 }
432 else if (c == term) {
433 char c = '\\';
434 rb_str_buf_cat(str, &c, 1);
435 rb_str_buf_cat(str, p, clen);
436 }
437 else if (rb_enc_isprint(c, enc)) {
438 rb_str_buf_cat(str, p, clen);
439 }
440 else if (!rb_enc_isspace(c, enc)) {
441 char b[8];
442
443 hex:
444 snprintf(b, sizeof(b), "\\x%02X", c);
445 rb_str_buf_cat(str, b, 4);
446 }
447 else {
448 rb_str_buf_cat(str, p, clen);
449 }
450 p += clen;
451 }
452 }
453}
454
455static VALUE
456rb_reg_desc(VALUE re)
457{
458 rb_encoding *enc = rb_enc_get(re);
459 VALUE str = rb_str_buf_new2("/");
460 rb_encoding *resenc = rb_default_internal_encoding();
461 if (resenc == NULL) resenc = rb_default_external_encoding();
462
463 if (re && rb_enc_asciicompat(enc)) {
464 rb_enc_copy(str, re);
465 }
466 else {
467 rb_enc_associate(str, rb_usascii_encoding());
468 }
469
470 VALUE src_str = RREGEXP_SRC(re);
471 rb_reg_expr_str(str, RSTRING_PTR(src_str), RSTRING_LEN(src_str), enc, resenc, '/');
472 RB_GC_GUARD(src_str);
473
474 rb_str_buf_cat2(str, "/");
475 if (re) {
476 char opts[OPTBUF_SIZE];
477 rb_reg_check(re);
478 if (*option_to_str(opts, RREGEXP_PTR(re)->options))
479 rb_str_buf_cat2(str, opts);
480 if (RBASIC(re)->flags & REG_ENCODING_NONE)
481 rb_str_buf_cat2(str, "n");
482 }
483 return str;
484}
485
486
487/*
488 * call-seq:
489 * source -> string
490 *
491 * Returns the original string of +self+:
492 *
493 * /ab+c/ix.source # => "ab+c"
494 *
495 * Regexp escape sequences are retained:
496 *
497 * /\x20\+/.source # => "\\x20\\+"
498 *
499 * Lexer escape characters are not retained:
500 *
501 * /\//.source # => "/"
502 *
503 */
504
505static VALUE
506rb_reg_source(VALUE re)
507{
508 VALUE str;
509
510 rb_reg_check(re);
511 str = rb_str_dup(RREGEXP_SRC(re));
512 return str;
513}
514
515/*
516 * call-seq:
517 * inspect -> string
518 *
519 * Returns a nicely-formatted string representation of +self+:
520 *
521 * /ab+c/ix.inspect # => "/ab+c/ix"
522 *
523 * Related: Regexp#to_s.
524 */
525
526static VALUE
527rb_reg_inspect(VALUE re)
528{
529 if (!RREGEXP_PTR(re) || !RREGEXP_SRC(re) || !RREGEXP_SRC_PTR(re)) {
530 return rb_any_to_s(re);
531 }
532 return rb_reg_desc(re);
533}
534
535static VALUE rb_reg_str_with_term(VALUE re, int term);
536
537/*
538 * call-seq:
539 * to_s -> string
540 *
541 * Returns a string showing the options and string of +self+:
542 *
543 * r0 = /ab+c/ix
544 * s0 = r0.to_s # => "(?ix-m:ab+c)"
545 *
546 * The returned string may be used as an argument to Regexp.new,
547 * or as interpolated text for a
548 * {Regexp interpolation}[rdoc-ref:Regexp@Interpolation+Mode]:
549 *
550 * r1 = Regexp.new(s0) # => /(?ix-m:ab+c)/
551 * r2 = /#{s0}/ # => /(?ix-m:ab+c)/
552 *
553 * Note that +r1+ and +r2+ are not equal to +r0+
554 * because their original strings are different:
555 *
556 * r0 == r1 # => false
557 * r0.source # => "ab+c"
558 * r1.source # => "(?ix-m:ab+c)"
559 *
560 * Related: Regexp#inspect.
561 *
562 */
563
564static VALUE
565rb_reg_to_s(VALUE re)
566{
567 return rb_reg_str_with_term(re, '/');
568}
569
570static VALUE
571rb_reg_str_with_term(VALUE re, int term)
572{
573 int options, opt;
574 const int embeddable = ONIG_OPTION_MULTILINE|ONIG_OPTION_IGNORECASE|ONIG_OPTION_EXTEND;
575 VALUE str = rb_str_buf_new2("(?");
576 char optbuf[OPTBUF_SIZE + 1]; /* for '-' */
577 rb_encoding *enc = rb_enc_get(re);
578
579 rb_reg_check(re);
580
581 rb_enc_copy(str, re);
582 options = RREGEXP_PTR(re)->options;
583 VALUE src_str = RREGEXP_SRC(re);
584 const UChar *ptr = (UChar *)RSTRING_PTR(src_str);
585 long len = RSTRING_LEN(src_str);
586 again:
587 if (len >= 4 && ptr[0] == '(' && ptr[1] == '?') {
588 int err = 1;
589 ptr += 2;
590 if ((len -= 2) > 0) {
591 do {
592 opt = char_to_option((int )*ptr);
593 if (opt != 0) {
594 options |= opt;
595 }
596 else {
597 break;
598 }
599 ++ptr;
600 } while (--len > 0);
601 }
602 if (len > 1 && *ptr == '-') {
603 ++ptr;
604 --len;
605 do {
606 opt = char_to_option((int )*ptr);
607 if (opt != 0) {
608 options &= ~opt;
609 }
610 else {
611 break;
612 }
613 ++ptr;
614 } while (--len > 0);
615 }
616 if (*ptr == ')') {
617 --len;
618 ++ptr;
619 goto again;
620 }
621 if (*ptr == ':' && ptr[len-1] == ')') {
622 Regexp *rp;
623 VALUE verbose = ruby_verbose;
625
626 ++ptr;
627 len -= 2;
628 err = onig_new(&rp, ptr, ptr + len, options,
629 enc, OnigDefaultSyntax, NULL);
630 onig_free(rp);
631 ruby_verbose = verbose;
632 }
633 if (err) {
634 options = RREGEXP_PTR(re)->options;
635 ptr = (UChar*)RREGEXP_SRC_PTR(re);
636 len = RREGEXP_SRC_LEN(re);
637 }
638 }
639
640 if (*option_to_str(optbuf, options)) rb_str_buf_cat2(str, optbuf);
641
642 if ((options & embeddable) != embeddable) {
643 optbuf[0] = '-';
644 option_to_str(optbuf + 1, ~options);
645 rb_str_buf_cat2(str, optbuf);
646 }
647
648 rb_str_buf_cat2(str, ":");
649 if (rb_enc_asciicompat(enc)) {
650 rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term);
651 rb_str_buf_cat2(str, ")");
652 }
653 else {
654 const char *s, *e;
655 char *paren;
656 ptrdiff_t n;
657 rb_str_buf_cat2(str, ")");
658 rb_enc_associate(str, rb_usascii_encoding());
659 str = rb_str_encode(str, rb_enc_from_encoding(enc), 0, Qnil);
660
661 /* backup encoded ")" to paren */
662 s = RSTRING_PTR(str);
663 e = RSTRING_END(str);
664 s = rb_enc_left_char_head(s, e-1, e, enc);
665 n = e - s;
666 paren = ALLOCA_N(char, n);
667 memcpy(paren, s, n);
668 rb_str_resize(str, RSTRING_LEN(str) - n);
669
670 rb_reg_expr_str(str, (char*)ptr, len, enc, NULL, term);
671 rb_str_buf_cat(str, paren, n);
672 }
673 rb_enc_copy(str, re);
674
675 RB_GC_GUARD(src_str);
676
677 return str;
678}
679
680NORETURN(static void rb_reg_raise(const char *err, VALUE re));
681
682static void
683rb_reg_raise(const char *err, VALUE re)
684{
685 VALUE desc = rb_reg_desc(re);
686
687 rb_raise(rb_eRegexpError, "%s: %"PRIsVALUE, err, desc);
688}
689
690static VALUE
691rb_enc_reg_error_desc(const char *s, long len, rb_encoding *enc, int options, const char *err)
692{
693 char opts[OPTBUF_SIZE + 1]; /* for '/' */
694 VALUE desc = rb_str_buf_new2(err);
695 rb_encoding *resenc = rb_default_internal_encoding();
696 if (resenc == NULL) resenc = rb_default_external_encoding();
697
698 rb_enc_associate(desc, enc);
699 rb_str_buf_cat2(desc, ": /");
700 rb_reg_expr_str(desc, s, len, enc, resenc, '/');
701 opts[0] = '/';
702 option_to_str(opts + 1, options);
703 rb_str_buf_cat2(desc, opts);
704 return rb_exc_new3(rb_eRegexpError, desc);
705}
706
707NORETURN(static void rb_enc_reg_raise(const char *s, long len, rb_encoding *enc, int options, const char *err));
708
709static void
710rb_enc_reg_raise(const char *s, long len, rb_encoding *enc, int options, const char *err)
711{
712 rb_exc_raise(rb_enc_reg_error_desc(s, len, enc, options, err));
713}
714
715static VALUE
716rb_reg_error_desc(VALUE str, int options, const char *err)
717{
718 return rb_enc_reg_error_desc(RSTRING_PTR(str), RSTRING_LEN(str),
719 rb_enc_get(str), options, err);
720}
721
722NORETURN(static void rb_reg_raise_str(VALUE str, int options, const char *err));
723
724static void
725rb_reg_raise_str(VALUE str, int options, const char *err)
726{
727 rb_exc_raise(rb_reg_error_desc(str, options, err));
728}
729
730
731/*
732 * call-seq:
733 * casefold?-> true or false
734 *
735 * Returns +true+ if the case-insensitivity flag in +self+ is set,
736 * +false+ otherwise:
737 *
738 * /a/.casefold? # => false
739 * /a/i.casefold? # => true
740 * /(?i:a)/.casefold? # => false
741 *
742 */
743
744static VALUE
745rb_reg_casefold_p(VALUE re)
746{
747 rb_reg_check(re);
748 return RBOOL(RREGEXP_PTR(re)->options & ONIG_OPTION_IGNORECASE);
749}
750
751
752/*
753 * call-seq:
754 * options -> integer
755 *
756 * Returns an integer whose bits show the options set in +self+.
757 *
758 * The option bits are:
759 *
760 * Regexp::IGNORECASE # => 1
761 * Regexp::EXTENDED # => 2
762 * Regexp::MULTILINE # => 4
763 *
764 * Examples:
765 *
766 * /foo/.options # => 0
767 * /foo/i.options # => 1
768 * /foo/x.options # => 2
769 * /foo/m.options # => 4
770 * /foo/mix.options # => 7
771 *
772 * Note that additional bits may be set in the returned integer;
773 * these are maintained internally in +self+, are ignored if passed
774 * to Regexp.new, and may be ignored by the caller:
775 *
776 * Returns the set of bits corresponding to the options used when
777 * creating this regexp (see Regexp::new for details). Note that
778 * additional bits may be set in the returned options: these are used
779 * internally by the regular expression code. These extra bits are
780 * ignored if the options are passed to Regexp::new:
781 *
782 * r = /\xa1\xa2/e # => /\xa1\xa2/
783 * r.source # => "\\xa1\\xa2"
784 * r.options # => 16
785 * Regexp.new(r.source, r.options) # => /\xa1\xa2/
786 *
787 */
788
789static VALUE
790rb_reg_options_m(VALUE re)
791{
792 int options = rb_reg_options(re);
793 return INT2NUM(options);
794}
795
796static int
797reg_names_iter(const OnigUChar *name, const OnigUChar *name_end,
798 int back_num, int *back_refs, OnigRegex regex, void *arg)
799{
800 VALUE ary = (VALUE)arg;
801 rb_ary_push(ary, rb_enc_str_new((const char *)name, name_end-name, regex->enc));
802 return 0;
803}
804
805/*
806 * call-seq:
807 * names -> array_of_names
808 *
809 * Returns an array of names of captures
810 * (see {Named Captures}[rdoc-ref:Regexp@Named+Captures]):
811 *
812 * /(?<foo>.)(?<bar>.)(?<baz>.)/.names # => ["foo", "bar", "baz"]
813 * /(?<foo>.)(?<foo>.)/.names # => ["foo"]
814 * /(.)(.)/.names # => []
815 *
816 */
817
818static VALUE
819rb_reg_names(VALUE re)
820{
821 VALUE ary;
822 rb_reg_check(re);
823 ary = rb_ary_new_capa(onig_number_of_names(RREGEXP_PTR(re)));
824 onig_foreach_name(RREGEXP_PTR(re), reg_names_iter, (void*)ary);
825 return ary;
826}
827
828static int
829reg_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end,
830 int back_num, int *back_refs, OnigRegex regex, void *arg)
831{
832 VALUE hash = (VALUE)arg;
833 VALUE ary = rb_ary_new2(back_num);
834 int i;
835
836 for (i = 0; i < back_num; i++)
837 rb_ary_store(ary, i, INT2NUM(back_refs[i]));
838
839 rb_hash_aset(hash, rb_str_new((const char*)name, name_end-name),ary);
840
841 return 0;
842}
843
844/*
845 * call-seq:
846 * named_captures -> hash
847 *
848 * Returns a hash representing named captures of +self+
849 * (see {Named Captures}[rdoc-ref:Regexp@Named+Captures]):
850 *
851 * - Each key is the name of a named capture.
852 * - Each value is an array of integer indexes for that named capture.
853 *
854 * Examples:
855 *
856 * /(?<foo>.)(?<bar>.)/.named_captures # => {"foo"=>[1], "bar"=>[2]}
857 * /(?<foo>.)(?<foo>.)/.named_captures # => {"foo"=>[1, 2]}
858 * /(.)(.)/.named_captures # => {}
859 *
860 */
861
862static VALUE
863rb_reg_named_captures(VALUE re)
864{
865 regex_t *reg = (rb_reg_check(re), RREGEXP_PTR(re));
866 VALUE hash = rb_hash_new_with_size(onig_number_of_names(reg));
867 onig_foreach_name(reg, reg_named_captures_iter, (void*)hash);
868 return hash;
869}
870
871static int
872onig_new_with_source(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
873 OnigOptionType option, OnigEncoding enc, const OnigSyntaxType* syntax,
874 OnigErrorInfo* einfo, const char *sourcefile, int sourceline)
875{
876 int r;
877
878 *reg = (regex_t* )malloc(sizeof(regex_t));
879 if (IS_NULL(*reg)) return ONIGERR_MEMORY;
880
881 r = onig_reg_init(*reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
882 if (r) goto err;
883
884 r = onig_compile_ruby(*reg, pattern, pattern_end, einfo, sourcefile, sourceline);
885 if (r) {
886 err:
887 onig_free(*reg);
888 *reg = NULL;
889 }
890 return r;
891}
892
893static Regexp*
894make_regexp(const char *s, long len, rb_encoding *enc, int flags, onig_errmsg_buffer err,
895 const char *sourcefile, int sourceline)
896{
897 Regexp *rp;
898 int r;
899 OnigErrorInfo einfo;
900
901 /* Handle escaped characters first. */
902
903 /* Build a copy of the string (in dest) with the
904 escaped characters translated, and generate the regex
905 from that.
906 */
907
908 r = onig_new_with_source(&rp, (UChar*)s, (UChar*)(s + len), flags,
909 enc, OnigDefaultSyntax, &einfo, sourcefile, sourceline);
910 if (r) {
911 onig_error_code_to_str((UChar*)err, r, &einfo);
912 return 0;
913 }
914 return rp;
915}
916
917
918/*
919 * Document-class: MatchData
920 *
921 * MatchData encapsulates the result of matching a Regexp against
922 * string. It is returned by Regexp#match and String#match, and also
923 * stored in a global variable returned by Regexp.last_match.
924 *
925 * Usage:
926 *
927 * url = 'https://docs.ruby-lang.org/en/2.5.0/MatchData.html'
928 * m = url.match(/(\d\.?)+/) # => #<MatchData "2.5.0" 1:"0">
929 * m.string # => "https://docs.ruby-lang.org/en/2.5.0/MatchData.html"
930 * m.regexp # => /(\d\.?)+/
931 * # entire matched substring:
932 * m[0] # => "2.5.0"
933 *
934 * # Working with unnamed captures
935 * m = url.match(%r{([^/]+)/([^/]+)\.html$})
936 * m.captures # => ["2.5.0", "MatchData"]
937 * m[1] # => "2.5.0"
938 * m.values_at(1, 2) # => ["2.5.0", "MatchData"]
939 *
940 * # Working with named captures
941 * m = url.match(%r{(?<version>[^/]+)/(?<module>[^/]+)\.html$})
942 * m.captures # => ["2.5.0", "MatchData"]
943 * m.named_captures # => {"version"=>"2.5.0", "module"=>"MatchData"}
944 * m[:version] # => "2.5.0"
945 * m.values_at(:version, :module)
946 * # => ["2.5.0", "MatchData"]
947 * # Numerical indexes are working, too
948 * m[1] # => "2.5.0"
949 * m.values_at(1, 2) # => ["2.5.0", "MatchData"]
950 *
951 * == Global variables equivalence
952 *
953 * Parts of last MatchData (returned by Regexp.last_match) are also
954 * aliased as global variables:
955 *
956 * * <code>$~</code> is Regexp.last_match;
957 * * <code>$&</code> is Regexp.last_match<code>[ 0 ]</code>;
958 * * <code>$1</code>, <code>$2</code>, and so on are
959 * Regexp.last_match<code>[ i ]</code> (captures by number);
960 * * <code>$`</code> is Regexp.last_match<code>.pre_match</code>;
961 * * <code>$'</code> is Regexp.last_match<code>.post_match</code>;
962 * * <code>$+</code> is Regexp.last_match<code>[ -1 ]</code> (the last capture).
963 *
964 * See also "Special global variables" section in Regexp documentation.
965 */
966
968
969static VALUE
970match_alloc(VALUE klass)
971{
972 size_t alloc_size = sizeof(struct RMatch) + sizeof(rb_matchext_t);
974 NEWOBJ_OF(match, struct RMatch, klass, flags, alloc_size, 0);
975
976 match->str = Qfalse;
977 match->regexp = Qfalse;
978 memset(RMATCH_EXT(match), 0, sizeof(rb_matchext_t));
979
980 return (VALUE)match;
981}
982
983int
984rb_reg_region_copy(struct re_registers *to, const struct re_registers *from)
985{
986 onig_region_copy(to, (OnigRegion *)from);
987 if (to->allocated) return 0;
988 rb_gc();
989 onig_region_copy(to, (OnigRegion *)from);
990 if (to->allocated) return 0;
991 return ONIGERR_MEMORY;
992}
993
994typedef struct {
995 long byte_pos;
996 long char_pos;
997} pair_t;
998
999static int
1000pair_byte_cmp(const void *pair1, const void *pair2)
1001{
1002 long diff = ((pair_t*)pair1)->byte_pos - ((pair_t*)pair2)->byte_pos;
1003#if SIZEOF_LONG > SIZEOF_INT
1004 return diff ? diff > 0 ? 1 : -1 : 0;
1005#else
1006 return (int)diff;
1007#endif
1008}
1009
1010static void
1011update_char_offset(VALUE match)
1012{
1013 rb_matchext_t *rm = RMATCH_EXT(match);
1014 struct re_registers *regs;
1015 int i, num_regs, num_pos;
1016 long c;
1017 char *s, *p, *q;
1018 rb_encoding *enc;
1019 pair_t *pairs;
1020
1022 return;
1023
1024 regs = &rm->regs;
1025 num_regs = rm->regs.num_regs;
1026
1027 if (rm->char_offset_num_allocated < num_regs) {
1028 REALLOC_N(rm->char_offset, struct rmatch_offset, num_regs);
1029 rm->char_offset_num_allocated = num_regs;
1030 }
1031
1032 enc = rb_enc_get(RMATCH(match)->str);
1033 if (rb_enc_mbmaxlen(enc) == 1) {
1034 for (i = 0; i < num_regs; i++) {
1035 rm->char_offset[i].beg = BEG(i);
1036 rm->char_offset[i].end = END(i);
1037 }
1038 return;
1039 }
1040
1041 pairs = ALLOCA_N(pair_t, num_regs*2);
1042 num_pos = 0;
1043 for (i = 0; i < num_regs; i++) {
1044 if (BEG(i) < 0)
1045 continue;
1046 pairs[num_pos++].byte_pos = BEG(i);
1047 pairs[num_pos++].byte_pos = END(i);
1048 }
1049 qsort(pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1050
1051 s = p = RSTRING_PTR(RMATCH(match)->str);
1052 c = 0;
1053 for (i = 0; i < num_pos; i++) {
1054 q = s + pairs[i].byte_pos;
1055 c += rb_enc_strlen(p, q, enc);
1056 pairs[i].char_pos = c;
1057 p = q;
1058 }
1059
1060 for (i = 0; i < num_regs; i++) {
1061 pair_t key, *found;
1062 if (BEG(i) < 0) {
1063 rm->char_offset[i].beg = -1;
1064 rm->char_offset[i].end = -1;
1065 continue;
1066 }
1067
1068 key.byte_pos = BEG(i);
1069 found = bsearch(&key, pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1070 rm->char_offset[i].beg = found->char_pos;
1071
1072 key.byte_pos = END(i);
1073 found = bsearch(&key, pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
1074 rm->char_offset[i].end = found->char_pos;
1075 }
1076}
1077
1078static VALUE
1079match_check(VALUE match)
1080{
1081 if (!RMATCH(match)->regexp) {
1082 rb_raise(rb_eTypeError, "uninitialized MatchData");
1083 }
1084 return match;
1085}
1086
1087/* :nodoc: */
1088static VALUE
1089match_init_copy(VALUE obj, VALUE orig)
1090{
1091 rb_matchext_t *rm;
1092
1093 if (!OBJ_INIT_COPY(obj, orig)) return obj;
1094
1095 RB_OBJ_WRITE(obj, &RMATCH(obj)->str, RMATCH(orig)->str);
1096 RB_OBJ_WRITE(obj, &RMATCH(obj)->regexp, RMATCH(orig)->regexp);
1097
1098 rm = RMATCH_EXT(obj);
1099 if (rb_reg_region_copy(&rm->regs, RMATCH_REGS(orig)))
1100 rb_memerror();
1101
1102 if (RMATCH_EXT(orig)->char_offset_num_allocated) {
1103 if (rm->char_offset_num_allocated < rm->regs.num_regs) {
1104 REALLOC_N(rm->char_offset, struct rmatch_offset, rm->regs.num_regs);
1105 rm->char_offset_num_allocated = rm->regs.num_regs;
1106 }
1107 MEMCPY(rm->char_offset, RMATCH_EXT(orig)->char_offset,
1108 struct rmatch_offset, rm->regs.num_regs);
1109 RB_GC_GUARD(orig);
1110 }
1111
1112 return obj;
1113}
1114
1115
1116/*
1117 * call-seq:
1118 * regexp -> regexp
1119 *
1120 * Returns the regexp that produced the match:
1121 *
1122 * m = /a.*b/.match("abc") # => #<MatchData "ab">
1123 * m.regexp # => /a.*b/
1124 *
1125 */
1126
1127static VALUE
1128match_regexp(VALUE match)
1129{
1130 VALUE regexp;
1131 match_check(match);
1132 regexp = RMATCH(match)->regexp;
1133 if (NIL_P(regexp)) {
1134 VALUE str = rb_reg_nth_match(0, match);
1135 regexp = rb_reg_regcomp(rb_reg_quote(str));
1136 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, regexp);
1137 }
1138 return regexp;
1139}
1140
1141/*
1142 * call-seq:
1143 * names -> array_of_names
1144 *
1145 * Returns an array of the capture names
1146 * (see {Named Captures}[rdoc-ref:Regexp@Named+Captures]):
1147 *
1148 * m = /(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge")
1149 * # => #<MatchData "hog" foo:"h" bar:"o" baz:"g">
1150 * m.names # => ["foo", "bar", "baz"]
1151 *
1152 * m = /foo/.match('foo') # => #<MatchData "foo">
1153 * m.names # => [] # No named captures.
1154 *
1155 * Equivalent to:
1156 *
1157 * m = /(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge")
1158 * m.regexp.names # => ["foo", "bar", "baz"]
1159 *
1160 */
1161
1162static VALUE
1163match_names(VALUE match)
1164{
1165 match_check(match);
1166 if (NIL_P(RMATCH(match)->regexp))
1167 return rb_ary_new_capa(0);
1168 return rb_reg_names(RMATCH(match)->regexp);
1169}
1170
1171/*
1172 * call-seq:
1173 * size -> integer
1174 *
1175 * Returns size of the match array:
1176 *
1177 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1178 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
1179 * m.size # => 5
1180 *
1181 */
1182
1183static VALUE
1184match_size(VALUE match)
1185{
1186 match_check(match);
1187 return INT2FIX(RMATCH_REGS(match)->num_regs);
1188}
1189
1190static int name_to_backref_number(struct re_registers *, VALUE, const char*, const char*);
1191NORETURN(static void name_to_backref_error(VALUE name));
1192
1193static void
1194name_to_backref_error(VALUE name)
1195{
1196 rb_raise(rb_eIndexError, "undefined group name reference: % "PRIsVALUE,
1197 name);
1198}
1199
1200static void
1201backref_number_check(struct re_registers *regs, int i)
1202{
1203 if (i < 0 || regs->num_regs <= i)
1204 rb_raise(rb_eIndexError, "index %d out of matches", i);
1205}
1206
1207static int
1208match_backref_number(VALUE match, VALUE backref)
1209{
1210 const char *name;
1211 int num;
1212
1213 struct re_registers *regs = RMATCH_REGS(match);
1214 VALUE regexp = RMATCH(match)->regexp;
1215
1216 match_check(match);
1217 if (SYMBOL_P(backref)) {
1218 backref = rb_sym2str(backref);
1219 }
1220 else if (!RB_TYPE_P(backref, T_STRING)) {
1221 return NUM2INT(backref);
1222 }
1223 name = StringValueCStr(backref);
1224
1225 num = name_to_backref_number(regs, regexp, name, name + RSTRING_LEN(backref));
1226
1227 if (num < 1) {
1228 name_to_backref_error(backref);
1229 }
1230
1231 return num;
1232}
1233
1234int
1236{
1237 return match_backref_number(match, backref);
1238}
1239
1240/*
1241 * call-seq:
1242 * offset(n) -> [start_offset, end_offset]
1243 * offset(name) -> [start_offset, end_offset]
1244 *
1245 * :include: doc/matchdata/offset.rdoc
1246 *
1247 */
1248
1249static VALUE
1250match_offset(VALUE match, VALUE n)
1251{
1252 int i = match_backref_number(match, n);
1253 struct re_registers *regs = RMATCH_REGS(match);
1254
1255 match_check(match);
1256 backref_number_check(regs, i);
1257
1258 if (BEG(i) < 0)
1259 return rb_assoc_new(Qnil, Qnil);
1260
1261 update_char_offset(match);
1262 return rb_assoc_new(LONG2NUM(RMATCH_EXT(match)->char_offset[i].beg),
1263 LONG2NUM(RMATCH_EXT(match)->char_offset[i].end));
1264}
1265
1266/*
1267 * call-seq:
1268 * mtch.byteoffset(n) -> array
1269 *
1270 * Returns a two-element array containing the beginning and ending byte-based offsets of
1271 * the <em>n</em>th match.
1272 * <em>n</em> can be a string or symbol to reference a named capture.
1273 *
1274 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1275 * m.byteoffset(0) #=> [1, 7]
1276 * m.byteoffset(4) #=> [6, 7]
1277 *
1278 * m = /(?<foo>.)(.)(?<bar>.)/.match("hoge")
1279 * p m.byteoffset(:foo) #=> [0, 1]
1280 * p m.byteoffset(:bar) #=> [2, 3]
1281 *
1282 */
1283
1284static VALUE
1285match_byteoffset(VALUE match, VALUE n)
1286{
1287 int i = match_backref_number(match, n);
1288 struct re_registers *regs = RMATCH_REGS(match);
1289
1290 match_check(match);
1291 backref_number_check(regs, i);
1292
1293 if (BEG(i) < 0)
1294 return rb_assoc_new(Qnil, Qnil);
1295 return rb_assoc_new(LONG2NUM(BEG(i)), LONG2NUM(END(i)));
1296}
1297
1298
1299/*
1300 * call-seq:
1301 * begin(n) -> integer
1302 * begin(name) -> integer
1303 *
1304 * :include: doc/matchdata/begin.rdoc
1305 *
1306 */
1307
1308static VALUE
1309match_begin(VALUE match, VALUE n)
1310{
1311 int i = match_backref_number(match, n);
1312 struct re_registers *regs = RMATCH_REGS(match);
1313
1314 match_check(match);
1315 backref_number_check(regs, i);
1316
1317 if (BEG(i) < 0)
1318 return Qnil;
1319
1320 update_char_offset(match);
1321 return LONG2NUM(RMATCH_EXT(match)->char_offset[i].beg);
1322}
1323
1324
1325/*
1326 * call-seq:
1327 * end(n) -> integer
1328 * end(name) -> integer
1329 *
1330 * :include: doc/matchdata/end.rdoc
1331 *
1332 */
1333
1334static VALUE
1335match_end(VALUE match, VALUE n)
1336{
1337 int i = match_backref_number(match, n);
1338 struct re_registers *regs = RMATCH_REGS(match);
1339
1340 match_check(match);
1341 backref_number_check(regs, i);
1342
1343 if (BEG(i) < 0)
1344 return Qnil;
1345
1346 update_char_offset(match);
1347 return LONG2NUM(RMATCH_EXT(match)->char_offset[i].end);
1348}
1349
1350/*
1351 * call-seq:
1352 * match(n) -> string or nil
1353 * match(name) -> string or nil
1354 *
1355 * Returns the matched substring corresponding to the given argument.
1356 *
1357 * When non-negative argument +n+ is given,
1358 * returns the matched substring for the <tt>n</tt>th match:
1359 *
1360 * m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.")
1361 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8" 5:nil>
1362 * m.match(0) # => "HX1138"
1363 * m.match(4) # => "8"
1364 * m.match(5) # => nil
1365 *
1366 * When string or symbol argument +name+ is given,
1367 * returns the matched substring for the given name:
1368 *
1369 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
1370 * # => #<MatchData "hoge" foo:"h" bar:"ge">
1371 * m.match('foo') # => "h"
1372 * m.match(:bar) # => "ge"
1373 *
1374 */
1375
1376static VALUE
1377match_nth(VALUE match, VALUE n)
1378{
1379 int i = match_backref_number(match, n);
1380 struct re_registers *regs = RMATCH_REGS(match);
1381
1382 backref_number_check(regs, i);
1383
1384 long start = BEG(i), end = END(i);
1385 if (start < 0)
1386 return Qnil;
1387
1388 return rb_str_subseq(RMATCH(match)->str, start, end - start);
1389}
1390
1391/*
1392 * call-seq:
1393 * match_length(n) -> integer or nil
1394 * match_length(name) -> integer or nil
1395 *
1396 * Returns the length (in characters) of the matched substring
1397 * corresponding to the given argument.
1398 *
1399 * When non-negative argument +n+ is given,
1400 * returns the length of the matched substring
1401 * for the <tt>n</tt>th match:
1402 *
1403 * m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.")
1404 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8" 5:nil>
1405 * m.match_length(0) # => 6
1406 * m.match_length(4) # => 1
1407 * m.match_length(5) # => nil
1408 *
1409 * When string or symbol argument +name+ is given,
1410 * returns the length of the matched substring
1411 * for the named match:
1412 *
1413 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
1414 * # => #<MatchData "hoge" foo:"h" bar:"ge">
1415 * m.match_length('foo') # => 1
1416 * m.match_length(:bar) # => 2
1417 *
1418 */
1419
1420static VALUE
1421match_nth_length(VALUE match, VALUE n)
1422{
1423 int i = match_backref_number(match, n);
1424 struct re_registers *regs = RMATCH_REGS(match);
1425
1426 match_check(match);
1427 backref_number_check(regs, i);
1428
1429 if (BEG(i) < 0)
1430 return Qnil;
1431
1432 update_char_offset(match);
1433 const struct rmatch_offset *const ofs =
1434 &RMATCH_EXT(match)->char_offset[i];
1435 return LONG2NUM(ofs->end - ofs->beg);
1436}
1437
1438#define MATCH_BUSY FL_USER2
1439
1440void
1442{
1443 FL_SET(match, MATCH_BUSY);
1444}
1445
1446void
1447rb_match_unbusy(VALUE match)
1448{
1449 FL_UNSET(match, MATCH_BUSY);
1450}
1451
1452int
1453rb_match_count(VALUE match)
1454{
1455 struct re_registers *regs;
1456 if (NIL_P(match)) return -1;
1457 regs = RMATCH_REGS(match);
1458 if (!regs) return -1;
1459 return regs->num_regs;
1460}
1461
1462static void
1463match_set_string(VALUE m, VALUE string, long pos, long len)
1464{
1465 struct RMatch *match = (struct RMatch *)m;
1466 rb_matchext_t *rmatch = RMATCH_EXT(match);
1467
1468 RB_OBJ_WRITE(match, &RMATCH(match)->str, string);
1469 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, Qnil);
1470 int err = onig_region_resize(&rmatch->regs, 1);
1471 if (err) rb_memerror();
1472 rmatch->regs.beg[0] = pos;
1473 rmatch->regs.end[0] = pos + len;
1474}
1475
1476void
1477rb_backref_set_string(VALUE string, long pos, long len)
1478{
1479 VALUE match = rb_backref_get();
1480 if (NIL_P(match) || FL_TEST(match, MATCH_BUSY)) {
1481 match = match_alloc(rb_cMatch);
1482 }
1483 match_set_string(match, string, pos, len);
1484 rb_backref_set(match);
1485}
1486
1487/*
1488 * call-seq:
1489 * fixed_encoding? -> true or false
1490 *
1491 * Returns +false+ if +self+ is applicable to
1492 * a string with any ASCII-compatible encoding;
1493 * otherwise returns +true+:
1494 *
1495 * r = /a/ # => /a/
1496 * r.fixed_encoding? # => false
1497 * r.match?("\u{6666} a") # => true
1498 * r.match?("\xa1\xa2 a".force_encoding("euc-jp")) # => true
1499 * r.match?("abc".force_encoding("euc-jp")) # => true
1500 *
1501 * r = /a/u # => /a/
1502 * r.fixed_encoding? # => true
1503 * r.match?("\u{6666} a") # => true
1504 * r.match?("\xa1\xa2".force_encoding("euc-jp")) # Raises exception.
1505 * r.match?("abc".force_encoding("euc-jp")) # => true
1506 *
1507 * r = /\u{6666}/ # => /\u{6666}/
1508 * r.fixed_encoding? # => true
1509 * r.encoding # => #<Encoding:UTF-8>
1510 * r.match?("\u{6666} a") # => true
1511 * r.match?("\xa1\xa2".force_encoding("euc-jp")) # Raises exception.
1512 * r.match?("abc".force_encoding("euc-jp")) # => false
1513 *
1514 */
1515
1516static VALUE
1517rb_reg_fixed_encoding_p(VALUE re)
1518{
1519 return RBOOL(FL_TEST(re, KCODE_FIXED));
1520}
1521
1522static VALUE
1523rb_reg_preprocess(const char *p, const char *end, rb_encoding *enc,
1524 rb_encoding **fixed_enc, onig_errmsg_buffer err, int options);
1525
1526NORETURN(static void reg_enc_error(VALUE re, VALUE str));
1527
1528static void
1529reg_enc_error(VALUE re, VALUE str)
1530{
1531 rb_raise(rb_eEncCompatError,
1532 "incompatible encoding regexp match (%s regexp with %s string)",
1533 rb_enc_name(rb_enc_get(re)),
1534 rb_enc_name(rb_enc_get(str)));
1535}
1536
1537static inline int
1538str_coderange(VALUE str)
1539{
1540 int cr = ENC_CODERANGE(str);
1541 if (cr == ENC_CODERANGE_UNKNOWN) {
1543 }
1544 return cr;
1545}
1546
1547static rb_encoding*
1548rb_reg_prepare_enc(VALUE re, VALUE str, int warn)
1549{
1550 rb_encoding *enc = 0;
1551 int cr = str_coderange(str);
1552
1553 if (cr == ENC_CODERANGE_BROKEN) {
1554 rb_raise(rb_eArgError,
1555 "invalid byte sequence in %s",
1556 rb_enc_name(rb_enc_get(str)));
1557 }
1558
1559 rb_reg_check(re);
1560 enc = rb_enc_get(str);
1561 if (RREGEXP_PTR(re)->enc == enc) {
1562 }
1563 else if (cr == ENC_CODERANGE_7BIT &&
1564 RREGEXP_PTR(re)->enc == rb_usascii_encoding()) {
1565 enc = RREGEXP_PTR(re)->enc;
1566 }
1567 else if (!rb_enc_asciicompat(enc)) {
1568 reg_enc_error(re, str);
1569 }
1570 else if (rb_reg_fixed_encoding_p(re)) {
1571 if ((!rb_enc_asciicompat(RREGEXP_PTR(re)->enc) ||
1572 cr != ENC_CODERANGE_7BIT)) {
1573 reg_enc_error(re, str);
1574 }
1575 enc = RREGEXP_PTR(re)->enc;
1576 }
1577 else if (warn && (RBASIC(re)->flags & REG_ENCODING_NONE) &&
1578 enc != rb_ascii8bit_encoding() &&
1579 cr != ENC_CODERANGE_7BIT) {
1580 rb_warn("historical binary regexp match /.../n against %s string",
1581 rb_enc_name(enc));
1582 }
1583 return enc;
1584}
1585
1586regex_t *
1588{
1589 int r;
1590 OnigErrorInfo einfo;
1591 VALUE unescaped;
1592 rb_encoding *fixed_enc = 0;
1593 rb_encoding *enc = rb_reg_prepare_enc(re, str, 1);
1594
1595 regex_t *reg = RREGEXP_PTR(re);
1596 if (reg->enc == enc) return reg;
1597
1598 rb_reg_check(re);
1599
1600 VALUE src_str = RREGEXP_SRC(re);
1601 const char *pattern = RSTRING_PTR(src_str);
1602
1603 onig_errmsg_buffer err = "";
1604 unescaped = rb_reg_preprocess(
1605 pattern, pattern + RSTRING_LEN(src_str), enc,
1606 &fixed_enc, err, 0);
1607
1608 if (NIL_P(unescaped)) {
1609 rb_raise(rb_eArgError, "regexp preprocess failed: %s", err);
1610 }
1611
1612 // inherit the timeout settings
1613 rb_hrtime_t timelimit = reg->timelimit;
1614
1615 const char *ptr;
1616 long len;
1617 RSTRING_GETMEM(unescaped, ptr, len);
1618
1619 /* If there are no other users of this regex, then we can directly overwrite it. */
1620 if (RREGEXP(re)->usecnt == 0) {
1621 regex_t tmp_reg;
1622 r = onig_new_without_alloc(&tmp_reg, (UChar *)ptr, (UChar *)(ptr + len),
1623 reg->options, enc,
1624 OnigDefaultSyntax, &einfo);
1625
1626 if (r) {
1627 /* There was an error so perform cleanups. */
1628 onig_free_body(&tmp_reg);
1629 }
1630 else {
1631 onig_free_body(reg);
1632 /* There are no errors so set reg to tmp_reg. */
1633 *reg = tmp_reg;
1634 }
1635 }
1636 else {
1637 r = onig_new(&reg, (UChar *)ptr, (UChar *)(ptr + len),
1638 reg->options, enc,
1639 OnigDefaultSyntax, &einfo);
1640 }
1641
1642 if (r) {
1643 onig_error_code_to_str((UChar*)err, r, &einfo);
1644 rb_reg_raise(err, re);
1645 }
1646
1647 reg->timelimit = timelimit;
1648
1649 RB_GC_GUARD(unescaped);
1650 RB_GC_GUARD(src_str);
1651 return reg;
1652}
1653
1654OnigPosition
1656 OnigPosition (*match)(regex_t *reg, VALUE str, struct re_registers *regs, void *args),
1657 void *args, struct re_registers *regs)
1658{
1659 regex_t *reg = rb_reg_prepare_re(re, str);
1660
1661 bool tmpreg = reg != RREGEXP_PTR(re);
1662 if (!tmpreg) RREGEXP(re)->usecnt++;
1663
1664 OnigPosition result = match(reg, str, regs, args);
1665
1666 if (!tmpreg) RREGEXP(re)->usecnt--;
1667 if (tmpreg) {
1668 onig_free(reg);
1669 }
1670
1671 if (result < 0) {
1672 onig_region_free(regs, 0);
1673
1674 if (result != ONIG_MISMATCH) {
1675 onig_errmsg_buffer err = "";
1676 onig_error_code_to_str((UChar*)err, (int)result);
1677 rb_reg_raise(err, re);
1678 }
1679 }
1680
1681 return result;
1682}
1683
1684long
1685rb_reg_adjust_startpos(VALUE re, VALUE str, long pos, int reverse)
1686{
1687 long range;
1688 rb_encoding *enc;
1689 UChar *p, *string;
1690
1691 enc = rb_reg_prepare_enc(re, str, 0);
1692
1693 if (reverse) {
1694 range = -pos;
1695 }
1696 else {
1697 range = RSTRING_LEN(str) - pos;
1698 }
1699
1700 if (pos > 0 && ONIGENC_MBC_MAXLEN(enc) != 1 && pos < RSTRING_LEN(str)) {
1701 string = (UChar*)RSTRING_PTR(str);
1702
1703 if (range > 0) {
1704 p = onigenc_get_right_adjust_char_head(enc, string, string + pos, string + RSTRING_LEN(str));
1705 }
1706 else {
1707 p = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, string, string + pos, string + RSTRING_LEN(str));
1708 }
1709 return p - string;
1710 }
1711
1712 return pos;
1713}
1714
1716 long pos;
1717 long range;
1718};
1719
1720static OnigPosition
1721reg_onig_search(regex_t *reg, VALUE str, struct re_registers *regs, void *args_ptr)
1722{
1723 struct reg_onig_search_args *args = (struct reg_onig_search_args *)args_ptr;
1724 const char *ptr;
1725 long len;
1726 RSTRING_GETMEM(str, ptr, len);
1727
1728 return onig_search(
1729 reg,
1730 (UChar *)ptr,
1731 (UChar *)(ptr + len),
1732 (UChar *)(ptr + args->pos),
1733 (UChar *)(ptr + args->range),
1734 regs,
1735 ONIG_OPTION_NONE);
1736}
1737
1739 VALUE re;
1740 VALUE str;
1741 struct reg_onig_search_args args;
1742 struct re_registers regs;
1743
1744 OnigPosition result;
1745};
1746
1747static VALUE
1748rb_reg_onig_match_try(VALUE value_args)
1749{
1750 struct rb_reg_onig_match_args *args = (struct rb_reg_onig_match_args *)value_args;
1751 args->result = rb_reg_onig_match(args->re, args->str, reg_onig_search, &args->args, &args->regs);
1752 return Qnil;
1753}
1754
1755/* returns byte offset */
1756static long
1757rb_reg_search_set_match(VALUE re, VALUE str, long pos, int reverse, int set_backref_str, VALUE *set_match)
1758{
1759 long len = RSTRING_LEN(str);
1760 if (pos > len || pos < 0) {
1762 return -1;
1763 }
1764
1765 struct rb_reg_onig_match_args args = {
1766 .re = re,
1767 .str = str,
1768 .args = {
1769 .pos = pos,
1770 .range = reverse ? 0 : len,
1771 },
1772 .regs = {0}
1773 };
1774
1775 /* If there is a timeout set, then rb_reg_onig_match could raise a
1776 * Regexp::TimeoutError so we want to protect it from leaking memory. */
1777 if (rb_reg_match_time_limit) {
1778 int state;
1779 rb_protect(rb_reg_onig_match_try, (VALUE)&args, &state);
1780 if (state) {
1781 onig_region_free(&args.regs, false);
1782 rb_jump_tag(state);
1783 }
1784 }
1785 else {
1786 rb_reg_onig_match_try((VALUE)&args);
1787 }
1788
1789 if (args.result == ONIG_MISMATCH) {
1791 return ONIG_MISMATCH;
1792 }
1793
1794 VALUE match = match_alloc(rb_cMatch);
1795 rb_matchext_t *rm = RMATCH_EXT(match);
1796 rm->regs = args.regs;
1797
1798 if (set_backref_str) {
1799 RB_OBJ_WRITE(match, &RMATCH(match)->str, rb_str_new4(str));
1800 }
1801 else {
1802 /* Note that a MatchData object with RMATCH(match)->str == 0 is incomplete!
1803 * We need to hide the object from ObjectSpace.each_object.
1804 * https://bugs.ruby-lang.org/issues/19159
1805 */
1806 rb_obj_hide(match);
1807 }
1808
1809 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, re);
1810 rb_backref_set(match);
1811 if (set_match) *set_match = match;
1812
1813 return args.result;
1814}
1815
1816long
1817rb_reg_search0(VALUE re, VALUE str, long pos, int reverse, int set_backref_str)
1818{
1819 return rb_reg_search_set_match(re, str, pos, reverse, set_backref_str, NULL);
1820}
1821
1822long
1823rb_reg_search(VALUE re, VALUE str, long pos, int reverse)
1824{
1825 return rb_reg_search0(re, str, pos, reverse, 1);
1826}
1827
1828static OnigPosition
1829reg_onig_match(regex_t *reg, VALUE str, struct re_registers *regs, void *_)
1830{
1831 const char *ptr;
1832 long len;
1833 RSTRING_GETMEM(str, ptr, len);
1834
1835 return onig_match(
1836 reg,
1837 (UChar *)ptr,
1838 (UChar *)(ptr + len),
1839 (UChar *)ptr,
1840 regs,
1841 ONIG_OPTION_NONE);
1842}
1843
1844bool
1845rb_reg_start_with_p(VALUE re, VALUE str)
1846{
1847 VALUE match = rb_backref_get();
1848 if (NIL_P(match) || FL_TEST(match, MATCH_BUSY)) {
1849 match = match_alloc(rb_cMatch);
1850 }
1851
1852 struct re_registers *regs = RMATCH_REGS(match);
1853
1854 if (rb_reg_onig_match(re, str, reg_onig_match, NULL, regs) == ONIG_MISMATCH) {
1856 return false;
1857 }
1858
1859 RB_OBJ_WRITE(match, &RMATCH(match)->str, rb_str_new4(str));
1860 RB_OBJ_WRITE(match, &RMATCH(match)->regexp, re);
1861 rb_backref_set(match);
1862
1863 return true;
1864}
1865
1866VALUE
1868{
1869 struct re_registers *regs;
1870 if (NIL_P(match)) return Qnil;
1871 match_check(match);
1872 regs = RMATCH_REGS(match);
1873 if (nth >= regs->num_regs) {
1874 return Qnil;
1875 }
1876 if (nth < 0) {
1877 nth += regs->num_regs;
1878 if (nth <= 0) return Qnil;
1879 }
1880 return RBOOL(BEG(nth) != -1);
1881}
1882
1883VALUE
1885{
1886 VALUE str;
1887 long start, end, len;
1888 struct re_registers *regs;
1889
1890 if (NIL_P(match)) return Qnil;
1891 match_check(match);
1892 regs = RMATCH_REGS(match);
1893 if (nth >= regs->num_regs) {
1894 return Qnil;
1895 }
1896 if (nth < 0) {
1897 nth += regs->num_regs;
1898 if (nth <= 0) return Qnil;
1899 }
1900 start = BEG(nth);
1901 if (start == -1) return Qnil;
1902 end = END(nth);
1903 len = end - start;
1904 str = rb_str_subseq(RMATCH(match)->str, start, len);
1905 return str;
1906}
1907
1908VALUE
1910{
1911 return rb_reg_nth_match(0, match);
1912}
1913
1914
1915/*
1916 * call-seq:
1917 * pre_match -> string
1918 *
1919 * Returns the substring of the target string from its beginning
1920 * up to the first match in +self+ (that is, <tt>self[0]</tt>);
1921 * equivalent to regexp global variable <tt>$`</tt>:
1922 *
1923 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1924 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
1925 * m[0] # => "HX1138"
1926 * m.pre_match # => "T"
1927 *
1928 * Related: MatchData#post_match.
1929 *
1930 */
1931
1932VALUE
1934{
1935 VALUE str;
1936 struct re_registers *regs;
1937
1938 if (NIL_P(match)) return Qnil;
1939 match_check(match);
1940 regs = RMATCH_REGS(match);
1941 if (BEG(0) == -1) return Qnil;
1942 str = rb_str_subseq(RMATCH(match)->str, 0, BEG(0));
1943 return str;
1944}
1945
1946
1947/*
1948 * call-seq:
1949 * post_match -> str
1950 *
1951 * Returns the substring of the target string from
1952 * the end of the first match in +self+ (that is, <tt>self[0]</tt>)
1953 * to the end of the string;
1954 * equivalent to regexp global variable <tt>$'</tt>:
1955 *
1956 * m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
1957 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
1958 * m[0] # => "HX1138"
1959 * m.post_match # => ": The Movie"\
1960 *
1961 * Related: MatchData.pre_match.
1962 *
1963 */
1964
1965VALUE
1967{
1968 VALUE str;
1969 long pos;
1970 struct re_registers *regs;
1971
1972 if (NIL_P(match)) return Qnil;
1973 match_check(match);
1974 regs = RMATCH_REGS(match);
1975 if (BEG(0) == -1) return Qnil;
1976 str = RMATCH(match)->str;
1977 pos = END(0);
1978 str = rb_str_subseq(str, pos, RSTRING_LEN(str) - pos);
1979 return str;
1980}
1981
1982static int
1983match_last_index(VALUE match)
1984{
1985 int i;
1986 struct re_registers *regs;
1987
1988 if (NIL_P(match)) return -1;
1989 match_check(match);
1990 regs = RMATCH_REGS(match);
1991 if (BEG(0) == -1) return -1;
1992
1993 for (i=regs->num_regs-1; BEG(i) == -1 && i > 0; i--)
1994 ;
1995 return i;
1996}
1997
1998VALUE
2000{
2001 int i = match_last_index(match);
2002 if (i <= 0) return Qnil;
2003 struct re_registers *regs = RMATCH_REGS(match);
2004 return rb_str_subseq(RMATCH(match)->str, BEG(i), END(i) - BEG(i));
2005}
2006
2007VALUE
2008rb_reg_last_defined(VALUE match)
2009{
2010 int i = match_last_index(match);
2011 if (i < 0) return Qnil;
2012 return RBOOL(i);
2013}
2014
2015static VALUE
2016last_match_getter(ID _x, VALUE *_y)
2017{
2019}
2020
2021static VALUE
2022prematch_getter(ID _x, VALUE *_y)
2023{
2025}
2026
2027static VALUE
2028postmatch_getter(ID _x, VALUE *_y)
2029{
2031}
2032
2033static VALUE
2034last_paren_match_getter(ID _x, VALUE *_y)
2035{
2037}
2038
2039static VALUE
2040match_array(VALUE match, int start)
2041{
2042 struct re_registers *regs;
2043 VALUE ary;
2044 VALUE target;
2045 int i;
2046
2047 match_check(match);
2048 regs = RMATCH_REGS(match);
2049 ary = rb_ary_new2(regs->num_regs);
2050 target = RMATCH(match)->str;
2051
2052 for (i=start; i<regs->num_regs; i++) {
2053 if (regs->beg[i] == -1) {
2054 rb_ary_push(ary, Qnil);
2055 }
2056 else {
2057 VALUE str = rb_str_subseq(target, regs->beg[i], regs->end[i]-regs->beg[i]);
2058 rb_ary_push(ary, str);
2059 }
2060 }
2061 return ary;
2062}
2063
2064
2065/*
2066 * call-seq:
2067 * to_a -> array
2068 *
2069 * Returns the array of matches:
2070 *
2071 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2072 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2073 * m.to_a # => ["HX1138", "H", "X", "113", "8"]
2074 *
2075 * Related: MatchData#captures.
2076 *
2077 */
2078
2079static VALUE
2080match_to_a(VALUE match)
2081{
2082 return match_array(match, 0);
2083}
2084
2085
2086/*
2087 * call-seq:
2088 * captures -> array
2089 *
2090 * Returns the array of captures,
2091 * which are all matches except <tt>m[0]</tt>:
2092 *
2093 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2094 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2095 * m[0] # => "HX1138"
2096 * m.captures # => ["H", "X", "113", "8"]
2097 *
2098 * Related: MatchData.to_a.
2099 *
2100 */
2101static VALUE
2102match_captures(VALUE match)
2103{
2104 return match_array(match, 1);
2105}
2106
2107static int
2108name_to_backref_number(struct re_registers *regs, VALUE regexp, const char* name, const char* name_end)
2109{
2110 if (NIL_P(regexp)) return -1;
2111 return onig_name_to_backref_number(RREGEXP_PTR(regexp),
2112 (const unsigned char *)name, (const unsigned char *)name_end, regs);
2113}
2114
2115#define NAME_TO_NUMBER(regs, re, name, name_ptr, name_end) \
2116 (NIL_P(re) ? 0 : \
2117 !rb_enc_compatible(RREGEXP_SRC(re), (name)) ? 0 : \
2118 name_to_backref_number((regs), (re), (name_ptr), (name_end)))
2119
2120static int
2121namev_to_backref_number(struct re_registers *regs, VALUE re, VALUE name)
2122{
2123 int num;
2124
2125 if (SYMBOL_P(name)) {
2126 name = rb_sym2str(name);
2127 }
2128 else if (!RB_TYPE_P(name, T_STRING)) {
2129 return -1;
2130 }
2131 num = NAME_TO_NUMBER(regs, re, name,
2132 RSTRING_PTR(name), RSTRING_END(name));
2133 if (num < 1) {
2134 name_to_backref_error(name);
2135 }
2136 return num;
2137}
2138
2139static VALUE
2140match_ary_subseq(VALUE match, long beg, long len, VALUE result)
2141{
2142 long olen = RMATCH_REGS(match)->num_regs;
2143 long j, end = olen < beg+len ? olen : beg+len;
2144 if (NIL_P(result)) result = rb_ary_new_capa(len);
2145 if (len == 0) return result;
2146
2147 for (j = beg; j < end; j++) {
2148 rb_ary_push(result, rb_reg_nth_match((int)j, match));
2149 }
2150 if (beg + len > j) {
2151 rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j);
2152 }
2153 return result;
2154}
2155
2156static VALUE
2157match_ary_aref(VALUE match, VALUE idx, VALUE result)
2158{
2159 long beg, len;
2160 int num_regs = RMATCH_REGS(match)->num_regs;
2161
2162 /* check if idx is Range */
2163 switch (rb_range_beg_len(idx, &beg, &len, (long)num_regs, !NIL_P(result))) {
2164 case Qfalse:
2165 if (NIL_P(result)) return rb_reg_nth_match(NUM2INT(idx), match);
2166 rb_ary_push(result, rb_reg_nth_match(NUM2INT(idx), match));
2167 return result;
2168 case Qnil:
2169 return Qnil;
2170 default:
2171 return match_ary_subseq(match, beg, len, result);
2172 }
2173}
2174
2175/*
2176 * call-seq:
2177 * matchdata[index] -> string or nil
2178 * matchdata[start, length] -> array
2179 * matchdata[range] -> array
2180 * matchdata[name] -> string or nil
2181 *
2182 * When arguments +index+, +start and +length+, or +range+ are given,
2183 * returns match and captures in the style of Array#[]:
2184 *
2185 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2186 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2187 * m[0] # => "HX1138"
2188 * m[1, 2] # => ["H", "X"]
2189 * m[1..3] # => ["H", "X", "113"]
2190 * m[-3, 2] # => ["X", "113"]
2191 *
2192 * When string or symbol argument +name+ is given,
2193 * returns the matched substring for the given name:
2194 *
2195 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
2196 * # => #<MatchData "hoge" foo:"h" bar:"ge">
2197 * m['foo'] # => "h"
2198 * m[:bar] # => "ge"
2199 *
2200 * If multiple captures have the same name, returns the last matched
2201 * substring.
2202 *
2203 * m = /(?<foo>.)(?<foo>.+)/.match("hoge")
2204 * # => #<MatchData "hoge" foo:"h" foo:"oge">
2205 * m[:foo] #=> "oge"
2206 *
2207 * m = /\W(?<foo>.+)|\w(?<foo>.+)|(?<foo>.+)/.match("hoge")
2208 * #<MatchData "hoge" foo:nil foo:"oge" foo:nil>
2209 * m[:foo] #=> "oge"
2210 *
2211 */
2212
2213static VALUE
2214match_aref(int argc, VALUE *argv, VALUE match)
2215{
2216 VALUE idx, length;
2217
2218 match_check(match);
2219 rb_scan_args(argc, argv, "11", &idx, &length);
2220
2221 if (NIL_P(length)) {
2222 if (FIXNUM_P(idx)) {
2223 return rb_reg_nth_match(FIX2INT(idx), match);
2224 }
2225 else {
2226 int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, idx);
2227 if (num >= 0) {
2228 return rb_reg_nth_match(num, match);
2229 }
2230 else {
2231 return match_ary_aref(match, idx, Qnil);
2232 }
2233 }
2234 }
2235 else {
2236 long beg = NUM2LONG(idx);
2237 long len = NUM2LONG(length);
2238 long num_regs = RMATCH_REGS(match)->num_regs;
2239 if (len < 0) {
2240 return Qnil;
2241 }
2242 if (beg < 0) {
2243 beg += num_regs;
2244 if (beg < 0) return Qnil;
2245 }
2246 else if (beg > num_regs) {
2247 return Qnil;
2248 }
2249 if (beg+len > num_regs) {
2250 len = num_regs - beg;
2251 }
2252 return match_ary_subseq(match, beg, len, Qnil);
2253 }
2254}
2255
2256/*
2257 * call-seq:
2258 * values_at(*indexes) -> array
2259 *
2260 * Returns match and captures at the given +indexes+,
2261 * which may include any mixture of:
2262 *
2263 * - Integers.
2264 * - Ranges.
2265 * - Names (strings and symbols).
2266 *
2267 *
2268 * Examples:
2269 *
2270 * m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
2271 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2272 * m.values_at(0, 2, -2) # => ["HX1138", "X", "113"]
2273 * m.values_at(1..2, -1) # => ["H", "X", "8"]
2274 *
2275 * m = /(?<a>\d+) *(?<op>[+\-*\/]) *(?<b>\d+)/.match("1 + 2")
2276 * # => #<MatchData "1 + 2" a:"1" op:"+" b:"2">
2277 * m.values_at(0, 1..2, :a, :b, :op)
2278 * # => ["1 + 2", "1", "+", "1", "2", "+"]
2279 *
2280 */
2281
2282static VALUE
2283match_values_at(int argc, VALUE *argv, VALUE match)
2284{
2285 VALUE result;
2286 int i;
2287
2288 match_check(match);
2289 result = rb_ary_new2(argc);
2290
2291 for (i=0; i<argc; i++) {
2292 if (FIXNUM_P(argv[i])) {
2293 rb_ary_push(result, rb_reg_nth_match(FIX2INT(argv[i]), match));
2294 }
2295 else {
2296 int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, argv[i]);
2297 if (num >= 0) {
2298 rb_ary_push(result, rb_reg_nth_match(num, match));
2299 }
2300 else {
2301 match_ary_aref(match, argv[i], result);
2302 }
2303 }
2304 }
2305 return result;
2306}
2307
2308
2309/*
2310 * call-seq:
2311 * to_s -> string
2312 *
2313 * Returns the matched string:
2314 *
2315 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2316 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2317 * m.to_s # => "HX1138"
2318 *
2319 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
2320 * # => #<MatchData "hoge" foo:"h" bar:"ge">
2321 * m.to_s # => "hoge"
2322 *
2323 * Related: MatchData.inspect.
2324 *
2325 */
2326
2327static VALUE
2328match_to_s(VALUE match)
2329{
2330 VALUE str = rb_reg_last_match(match_check(match));
2331
2332 if (NIL_P(str)) str = rb_str_new(0,0);
2333 return str;
2334}
2335
2336static int
2337match_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end,
2338 int back_num, int *back_refs, OnigRegex regex, void *arg)
2339{
2340 struct MEMO *memo = MEMO_CAST(arg);
2341 VALUE hash = memo->v1;
2342 VALUE match = memo->v2;
2343 long symbolize = memo->u3.state;
2344
2345 VALUE key = rb_enc_str_new((const char *)name, name_end-name, regex->enc);
2346
2347 if (symbolize > 0) {
2348 key = rb_str_intern(key);
2349 }
2350
2351 VALUE value;
2352
2353 int i;
2354 int found = 0;
2355
2356 for (i = 0; i < back_num; i++) {
2357 value = rb_reg_nth_match(back_refs[i], match);
2358 if (RTEST(value)) {
2359 rb_hash_aset(hash, key, value);
2360 found = 1;
2361 }
2362 }
2363
2364 if (found == 0) {
2365 rb_hash_aset(hash, key, Qnil);
2366 }
2367
2368 return 0;
2369}
2370
2371/*
2372 * call-seq:
2373 * named_captures(symbolize_names: false) -> hash
2374 *
2375 * Returns a hash of the named captures;
2376 * each key is a capture name; each value is its captured string or +nil+:
2377 *
2378 * m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
2379 * # => #<MatchData "hoge" foo:"h" bar:"ge">
2380 * m.named_captures # => {"foo"=>"h", "bar"=>"ge"}
2381 *
2382 * m = /(?<a>.)(?<b>.)/.match("01")
2383 * # => #<MatchData "01" a:"0" b:"1">
2384 * m.named_captures #=> {"a" => "0", "b" => "1"}
2385 *
2386 * m = /(?<a>.)(?<b>.)?/.match("0")
2387 * # => #<MatchData "0" a:"0" b:nil>
2388 * m.named_captures #=> {"a" => "0", "b" => nil}
2389 *
2390 * m = /(?<a>.)(?<a>.)/.match("01")
2391 * # => #<MatchData "01" a:"0" a:"1">
2392 * m.named_captures #=> {"a" => "1"}
2393 *
2394 * If keyword argument +symbolize_names+ is given
2395 * a true value, the keys in the resulting hash are Symbols:
2396 *
2397 * m = /(?<a>.)(?<a>.)/.match("01")
2398 * # => #<MatchData "01" a:"0" a:"1">
2399 * m.named_captures(symbolize_names: true) #=> {:a => "1"}
2400 *
2401 */
2402
2403static VALUE
2404match_named_captures(int argc, VALUE *argv, VALUE match)
2405{
2406 VALUE hash;
2407 struct MEMO *memo;
2408
2409 match_check(match);
2410 if (NIL_P(RMATCH(match)->regexp))
2411 return rb_hash_new();
2412
2413 VALUE opt;
2414 VALUE symbolize_names = 0;
2415
2416 rb_scan_args(argc, argv, "0:", &opt);
2417
2418 if (!NIL_P(opt)) {
2419 static ID keyword_ids[1];
2420
2421 VALUE symbolize_names_val;
2422
2423 if (!keyword_ids[0]) {
2424 keyword_ids[0] = rb_intern_const("symbolize_names");
2425 }
2426 rb_get_kwargs(opt, keyword_ids, 0, 1, &symbolize_names_val);
2427 if (!UNDEF_P(symbolize_names_val) && RTEST(symbolize_names_val)) {
2428 symbolize_names = 1;
2429 }
2430 }
2431
2432 hash = rb_hash_new();
2433 memo = MEMO_NEW(hash, match, symbolize_names);
2434
2435 onig_foreach_name(RREGEXP(RMATCH(match)->regexp)->ptr, match_named_captures_iter, (void*)memo);
2436
2437 return hash;
2438}
2439
2440/*
2441 * call-seq:
2442 * deconstruct_keys(array_of_names) -> hash
2443 *
2444 * Returns a hash of the named captures for the given names.
2445 *
2446 * m = /(?<hours>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})/.match("18:37:22")
2447 * m.deconstruct_keys([:hours, :minutes]) # => {:hours => "18", :minutes => "37"}
2448 * m.deconstruct_keys(nil) # => {:hours => "18", :minutes => "37", :seconds => "22"}
2449 *
2450 * Returns an empty hash if no named captures were defined:
2451 *
2452 * m = /(\d{2}):(\d{2}):(\d{2})/.match("18:37:22")
2453 * m.deconstruct_keys(nil) # => {}
2454 *
2455 */
2456static VALUE
2457match_deconstruct_keys(VALUE match, VALUE keys)
2458{
2459 VALUE h;
2460 long i;
2461
2462 match_check(match);
2463
2464 if (NIL_P(RMATCH(match)->regexp)) {
2465 return rb_hash_new_with_size(0);
2466 }
2467
2468 if (NIL_P(keys)) {
2469 h = rb_hash_new_with_size(onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)));
2470
2471 struct MEMO *memo;
2472 memo = MEMO_NEW(h, match, 1);
2473
2474 onig_foreach_name(RREGEXP_PTR(RMATCH(match)->regexp), match_named_captures_iter, (void*)memo);
2475
2476 return h;
2477 }
2478
2479 Check_Type(keys, T_ARRAY);
2480
2481 if (onig_number_of_names(RREGEXP_PTR(RMATCH(match)->regexp)) < RARRAY_LEN(keys)) {
2482 return rb_hash_new_with_size(0);
2483 }
2484
2485 h = rb_hash_new_with_size(RARRAY_LEN(keys));
2486
2487 for (i=0; i<RARRAY_LEN(keys); i++) {
2488 VALUE key = RARRAY_AREF(keys, i);
2489 VALUE name;
2490
2491 Check_Type(key, T_SYMBOL);
2492
2493 name = rb_sym2str(key);
2494
2495 int num = NAME_TO_NUMBER(RMATCH_REGS(match), RMATCH(match)->regexp, RMATCH(match)->regexp,
2496 RSTRING_PTR(name), RSTRING_END(name));
2497
2498 if (num >= 0) {
2499 rb_hash_aset(h, key, rb_reg_nth_match(num, match));
2500 }
2501 else {
2502 return h;
2503 }
2504 }
2505
2506 return h;
2507}
2508
2509/*
2510 * call-seq:
2511 * string -> string
2512 *
2513 * Returns the target string if it was frozen;
2514 * otherwise, returns a frozen copy of the target string:
2515 *
2516 * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2517 * # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
2518 * m.string # => "THX1138."
2519 *
2520 */
2521
2522static VALUE
2523match_string(VALUE match)
2524{
2525 match_check(match);
2526 return RMATCH(match)->str; /* str is frozen */
2527}
2528
2530 const UChar *name;
2531 long len;
2532};
2533
2534static int
2535match_inspect_name_iter(const OnigUChar *name, const OnigUChar *name_end,
2536 int back_num, int *back_refs, OnigRegex regex, void *arg0)
2537{
2538 struct backref_name_tag *arg = (struct backref_name_tag *)arg0;
2539 int i;
2540
2541 for (i = 0; i < back_num; i++) {
2542 arg[back_refs[i]].name = name;
2543 arg[back_refs[i]].len = name_end - name;
2544 }
2545 return 0;
2546}
2547
2548/*
2549 * call-seq:
2550 * inspect -> string
2551 *
2552 * Returns a string representation of +self+:
2553 *
2554 * m = /.$/.match("foo")
2555 * # => #<MatchData "o">
2556 * m.inspect # => "#<MatchData \"o\">"
2557 *
2558 * m = /(.)(.)(.)/.match("foo")
2559 * # => #<MatchData "foo" 1:"f" 2:"o" 3:"o">
2560 * m.inspect # => "#<MatchData \"foo\" 1:\"f\" 2:\"o\
2561 *
2562 * m = /(.)(.)?(.)/.match("fo")
2563 * # => #<MatchData "fo" 1:"f" 2:nil 3:"o">
2564 * m.inspect # => "#<MatchData \"fo\" 1:\"f\" 2:nil 3:\"o\">"
2565 *
2566 * Related: MatchData#to_s.
2567 */
2568
2569static VALUE
2570match_inspect(VALUE match)
2571{
2572 VALUE cname = rb_class_path(rb_obj_class(match));
2573 VALUE str;
2574 int i;
2575 struct re_registers *regs = RMATCH_REGS(match);
2576 int num_regs = regs->num_regs;
2577 struct backref_name_tag *names;
2578 VALUE regexp = RMATCH(match)->regexp;
2579
2580 if (regexp == 0) {
2581 return rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)match);
2582 }
2583 else if (NIL_P(regexp)) {
2584 return rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE">",
2585 cname, rb_reg_nth_match(0, match));
2586 }
2587
2588 names = ALLOCA_N(struct backref_name_tag, num_regs);
2589 MEMZERO(names, struct backref_name_tag, num_regs);
2590
2591 onig_foreach_name(RREGEXP_PTR(regexp),
2592 match_inspect_name_iter, names);
2593
2594 str = rb_str_buf_new2("#<");
2595 rb_str_append(str, cname);
2596
2597 for (i = 0; i < num_regs; i++) {
2598 VALUE v;
2599 rb_str_buf_cat2(str, " ");
2600 if (0 < i) {
2601 if (names[i].name)
2602 rb_str_buf_cat(str, (const char *)names[i].name, names[i].len);
2603 else {
2604 rb_str_catf(str, "%d", i);
2605 }
2606 rb_str_buf_cat2(str, ":");
2607 }
2608 v = rb_reg_nth_match(i, match);
2609 if (NIL_P(v))
2610 rb_str_buf_cat2(str, "nil");
2611 else
2612 rb_str_buf_append(str, rb_str_inspect(v));
2613 }
2614 rb_str_buf_cat2(str, ">");
2615
2616 return str;
2617}
2618
2620
2621static int
2622read_escaped_byte(const char **pp, const char *end, onig_errmsg_buffer err)
2623{
2624 const char *p = *pp;
2625 int code;
2626 int meta_prefix = 0, ctrl_prefix = 0;
2627 size_t len;
2628
2629 if (p == end || *p++ != '\\') {
2630 errcpy(err, "too short escaped multibyte character");
2631 return -1;
2632 }
2633
2634again:
2635 if (p == end) {
2636 errcpy(err, "too short escape sequence");
2637 return -1;
2638 }
2639 switch (*p++) {
2640 case '\\': code = '\\'; break;
2641 case 'n': code = '\n'; break;
2642 case 't': code = '\t'; break;
2643 case 'r': code = '\r'; break;
2644 case 'f': code = '\f'; break;
2645 case 'v': code = '\013'; break;
2646 case 'a': code = '\007'; break;
2647 case 'e': code = '\033'; break;
2648
2649 /* \OOO */
2650 case '0': case '1': case '2': case '3':
2651 case '4': case '5': case '6': case '7':
2652 p--;
2653 code = scan_oct(p, end < p+3 ? end-p : 3, &len);
2654 p += len;
2655 break;
2656
2657 case 'x': /* \xHH */
2658 code = scan_hex(p, end < p+2 ? end-p : 2, &len);
2659 if (len < 1) {
2660 errcpy(err, "invalid hex escape");
2661 return -1;
2662 }
2663 p += len;
2664 break;
2665
2666 case 'M': /* \M-X, \M-\C-X, \M-\cX */
2667 if (meta_prefix) {
2668 errcpy(err, "duplicate meta escape");
2669 return -1;
2670 }
2671 meta_prefix = 1;
2672 if (p+1 < end && *p++ == '-' && (*p & 0x80) == 0) {
2673 if (*p == '\\') {
2674 p++;
2675 goto again;
2676 }
2677 else {
2678 code = *p++;
2679 break;
2680 }
2681 }
2682 errcpy(err, "too short meta escape");
2683 return -1;
2684
2685 case 'C': /* \C-X, \C-\M-X */
2686 if (p == end || *p++ != '-') {
2687 errcpy(err, "too short control escape");
2688 return -1;
2689 }
2690 case 'c': /* \cX, \c\M-X */
2691 if (ctrl_prefix) {
2692 errcpy(err, "duplicate control escape");
2693 return -1;
2694 }
2695 ctrl_prefix = 1;
2696 if (p < end && (*p & 0x80) == 0) {
2697 if (*p == '\\') {
2698 p++;
2699 goto again;
2700 }
2701 else {
2702 code = *p++;
2703 break;
2704 }
2705 }
2706 errcpy(err, "too short control escape");
2707 return -1;
2708
2709 default:
2710 errcpy(err, "unexpected escape sequence");
2711 return -1;
2712 }
2713 if (code < 0 || 0xff < code) {
2714 errcpy(err, "invalid escape code");
2715 return -1;
2716 }
2717
2718 if (ctrl_prefix)
2719 code &= 0x1f;
2720 if (meta_prefix)
2721 code |= 0x80;
2722
2723 *pp = p;
2724 return code;
2725}
2726
2727static int
2728unescape_escaped_nonascii(const char **pp, const char *end, rb_encoding *enc,
2729 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
2730{
2731 const char *p = *pp;
2732 int chmaxlen = rb_enc_mbmaxlen(enc);
2733 unsigned char *area = ALLOCA_N(unsigned char, chmaxlen);
2734 char *chbuf = (char *)area;
2735 int chlen = 0;
2736 int byte;
2737 int l;
2738
2739 memset(chbuf, 0, chmaxlen);
2740
2741 byte = read_escaped_byte(&p, end, err);
2742 if (byte == -1) {
2743 return -1;
2744 }
2745
2746 area[chlen++] = byte;
2747 while (chlen < chmaxlen &&
2748 MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc))) {
2749 byte = read_escaped_byte(&p, end, err);
2750 if (byte == -1) {
2751 return -1;
2752 }
2753 area[chlen++] = byte;
2754 }
2755
2756 l = rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc);
2757 if (MBCLEN_INVALID_P(l)) {
2758 errcpy(err, "invalid multibyte escape");
2759 return -1;
2760 }
2761 if (1 < chlen || (area[0] & 0x80)) {
2762 rb_str_buf_cat(buf, chbuf, chlen);
2763
2764 if (*encp == 0)
2765 *encp = enc;
2766 else if (*encp != enc) {
2767 errcpy(err, "escaped non ASCII character in UTF-8 regexp");
2768 return -1;
2769 }
2770 }
2771 else {
2772 char escbuf[5];
2773 snprintf(escbuf, sizeof(escbuf), "\\x%02X", area[0]&0xff);
2774 rb_str_buf_cat(buf, escbuf, 4);
2775 }
2776 *pp = p;
2777 return 0;
2778}
2779
2780static int
2781check_unicode_range(unsigned long code, onig_errmsg_buffer err)
2782{
2783 if ((0xd800 <= code && code <= 0xdfff) || /* Surrogates */
2784 0x10ffff < code) {
2785 errcpy(err, "invalid Unicode range");
2786 return -1;
2787 }
2788 return 0;
2789}
2790
2791static int
2792append_utf8(unsigned long uv,
2793 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
2794{
2795 if (check_unicode_range(uv, err) != 0)
2796 return -1;
2797 if (uv < 0x80) {
2798 char escbuf[5];
2799 snprintf(escbuf, sizeof(escbuf), "\\x%02X", (int)uv);
2800 rb_str_buf_cat(buf, escbuf, 4);
2801 }
2802 else {
2803 int len;
2804 char utf8buf[6];
2805 len = rb_uv_to_utf8(utf8buf, uv);
2806 rb_str_buf_cat(buf, utf8buf, len);
2807
2808 if (*encp == 0)
2809 *encp = rb_utf8_encoding();
2810 else if (*encp != rb_utf8_encoding()) {
2811 errcpy(err, "UTF-8 character in non UTF-8 regexp");
2812 return -1;
2813 }
2814 }
2815 return 0;
2816}
2817
2818static int
2819unescape_unicode_list(const char **pp, const char *end,
2820 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
2821{
2822 const char *p = *pp;
2823 int has_unicode = 0;
2824 unsigned long code;
2825 size_t len;
2826
2827 while (p < end && ISSPACE(*p)) p++;
2828
2829 while (1) {
2830 code = ruby_scan_hex(p, end-p, &len);
2831 if (len == 0)
2832 break;
2833 if (6 < len) { /* max 10FFFF */
2834 errcpy(err, "invalid Unicode range");
2835 return -1;
2836 }
2837 p += len;
2838 if (append_utf8(code, buf, encp, err) != 0)
2839 return -1;
2840 has_unicode = 1;
2841
2842 while (p < end && ISSPACE(*p)) p++;
2843 }
2844
2845 if (has_unicode == 0) {
2846 errcpy(err, "invalid Unicode list");
2847 return -1;
2848 }
2849
2850 *pp = p;
2851
2852 return 0;
2853}
2854
2855static int
2856unescape_unicode_bmp(const char **pp, const char *end,
2857 VALUE buf, rb_encoding **encp, onig_errmsg_buffer err)
2858{
2859 const char *p = *pp;
2860 size_t len;
2861 unsigned long code;
2862
2863 if (end < p+4) {
2864 errcpy(err, "invalid Unicode escape");
2865 return -1;
2866 }
2867 code = ruby_scan_hex(p, 4, &len);
2868 if (len != 4) {
2869 errcpy(err, "invalid Unicode escape");
2870 return -1;
2871 }
2872 if (append_utf8(code, buf, encp, err) != 0)
2873 return -1;
2874 *pp = p + 4;
2875 return 0;
2876}
2877
2878static int
2879unescape_nonascii0(const char **pp, const char *end, rb_encoding *enc,
2880 VALUE buf, rb_encoding **encp, int *has_property,
2881 onig_errmsg_buffer err, int options, int recurse)
2882{
2883 const char *p = *pp;
2884 unsigned char c;
2885 char smallbuf[2];
2886 int in_char_class = 0;
2887 int parens = 1; /* ignored unless recurse is true */
2888 int extended_mode = options & ONIG_OPTION_EXTEND;
2889
2890begin_scan:
2891 while (p < end) {
2892 int chlen = rb_enc_precise_mbclen(p, end, enc);
2893 if (!MBCLEN_CHARFOUND_P(chlen)) {
2894 invalid_multibyte:
2895 errcpy(err, "invalid multibyte character");
2896 return -1;
2897 }
2898 chlen = MBCLEN_CHARFOUND_LEN(chlen);
2899 if (1 < chlen || (*p & 0x80)) {
2900 multibyte:
2901 rb_str_buf_cat(buf, p, chlen);
2902 p += chlen;
2903 if (*encp == 0)
2904 *encp = enc;
2905 else if (*encp != enc) {
2906 errcpy(err, "non ASCII character in UTF-8 regexp");
2907 return -1;
2908 }
2909 continue;
2910 }
2911
2912 switch (c = *p++) {
2913 case '\\':
2914 if (p == end) {
2915 errcpy(err, "too short escape sequence");
2916 return -1;
2917 }
2918 chlen = rb_enc_precise_mbclen(p, end, enc);
2919 if (!MBCLEN_CHARFOUND_P(chlen)) {
2920 goto invalid_multibyte;
2921 }
2922 if ((chlen = MBCLEN_CHARFOUND_LEN(chlen)) > 1) {
2923 /* include the previous backslash */
2924 --p;
2925 ++chlen;
2926 goto multibyte;
2927 }
2928 switch (c = *p++) {
2929 case '1': case '2': case '3':
2930 case '4': case '5': case '6': case '7': /* \O, \OO, \OOO or backref */
2931 {
2932 size_t len = end-(p-1), octlen;
2933 if (ruby_scan_oct(p-1, len < 3 ? len : 3, &octlen) <= 0177) {
2934 /* backref or 7bit octal.
2935 no need to unescape anyway.
2936 re-escaping may break backref */
2937 goto escape_asis;
2938 }
2939 }
2940 /* xxx: How about more than 199 subexpressions? */
2941
2942 case '0': /* \0, \0O, \0OO */
2943
2944 case 'x': /* \xHH */
2945 case 'c': /* \cX, \c\M-X */
2946 case 'C': /* \C-X, \C-\M-X */
2947 case 'M': /* \M-X, \M-\C-X, \M-\cX */
2948 p = p-2;
2949 if (rb_is_usascii_enc(enc)) {
2950 const char *pbeg = p;
2951 int byte = read_escaped_byte(&p, end, err);
2952 if (byte == -1) return -1;
2953 c = byte;
2954 rb_str_buf_cat(buf, pbeg, p-pbeg);
2955 }
2956 else {
2957 if (unescape_escaped_nonascii(&p, end, enc, buf, encp, err) != 0)
2958 return -1;
2959 }
2960 break;
2961
2962 case 'u':
2963 if (p == end) {
2964 errcpy(err, "too short escape sequence");
2965 return -1;
2966 }
2967 if (*p == '{') {
2968 /* \u{H HH HHH HHHH HHHHH HHHHHH ...} */
2969 p++;
2970 if (unescape_unicode_list(&p, end, buf, encp, err) != 0)
2971 return -1;
2972 if (p == end || *p++ != '}') {
2973 errcpy(err, "invalid Unicode list");
2974 return -1;
2975 }
2976 break;
2977 }
2978 else {
2979 /* \uHHHH */
2980 if (unescape_unicode_bmp(&p, end, buf, encp, err) != 0)
2981 return -1;
2982 break;
2983 }
2984
2985 case 'p': /* \p{Hiragana} */
2986 case 'P':
2987 if (!*encp) {
2988 *has_property = 1;
2989 }
2990 goto escape_asis;
2991
2992 default: /* \n, \\, \d, \9, etc. */
2993escape_asis:
2994 smallbuf[0] = '\\';
2995 smallbuf[1] = c;
2996 rb_str_buf_cat(buf, smallbuf, 2);
2997 break;
2998 }
2999 break;
3000
3001 case '#':
3002 if (extended_mode && !in_char_class) {
3003 /* consume and ignore comment in extended regexp */
3004 while ((p < end) && ((c = *p++) != '\n')) {
3005 if ((c & 0x80) && !*encp && enc == rb_utf8_encoding()) {
3006 *encp = enc;
3007 }
3008 }
3009 break;
3010 }
3011 rb_str_buf_cat(buf, (char *)&c, 1);
3012 break;
3013 case '[':
3014 in_char_class++;
3015 rb_str_buf_cat(buf, (char *)&c, 1);
3016 break;
3017 case ']':
3018 if (in_char_class) {
3019 in_char_class--;
3020 }
3021 rb_str_buf_cat(buf, (char *)&c, 1);
3022 break;
3023 case ')':
3024 rb_str_buf_cat(buf, (char *)&c, 1);
3025 if (!in_char_class && recurse) {
3026 if (--parens == 0) {
3027 *pp = p;
3028 return 0;
3029 }
3030 }
3031 break;
3032 case '(':
3033 if (!in_char_class && p + 1 < end && *p == '?') {
3034 if (*(p+1) == '#') {
3035 /* (?# is comment inside any regexp, and content inside should be ignored */
3036 const char *orig_p = p;
3037 int cont = 1;
3038
3039 while (cont && (p < end)) {
3040 switch (c = *p++) {
3041 default:
3042 if (!(c & 0x80)) break;
3043 if (!*encp && enc == rb_utf8_encoding()) {
3044 *encp = enc;
3045 }
3046 --p;
3047 /* fallthrough */
3048 case '\\':
3049 chlen = rb_enc_precise_mbclen(p, end, enc);
3050 if (!MBCLEN_CHARFOUND_P(chlen)) {
3051 goto invalid_multibyte;
3052 }
3053 p += MBCLEN_CHARFOUND_LEN(chlen);
3054 break;
3055 case ')':
3056 cont = 0;
3057 break;
3058 }
3059 }
3060
3061 if (cont) {
3062 /* unterminated (?#, rewind so it is syntax error */
3063 p = orig_p;
3064 c = '(';
3065 rb_str_buf_cat(buf, (char *)&c, 1);
3066 }
3067 break;
3068 }
3069 else {
3070 /* potential change of extended option */
3071 int invert = 0;
3072 int local_extend = 0;
3073 const char *s;
3074
3075 if (recurse) {
3076 parens++;
3077 }
3078
3079 for(s = p+1; s < end; s++) {
3080 switch(*s) {
3081 case 'x':
3082 local_extend = invert ? -1 : 1;
3083 break;
3084 case '-':
3085 invert = 1;
3086 break;
3087 case ':':
3088 case ')':
3089 if (local_extend == 0 ||
3090 (local_extend == -1 && !extended_mode) ||
3091 (local_extend == 1 && extended_mode)) {
3092 /* no changes to extended flag */
3093 goto fallthrough;
3094 }
3095
3096 if (*s == ':') {
3097 /* change extended flag until ')' */
3098 int local_options = options;
3099 if (local_extend == 1) {
3100 local_options |= ONIG_OPTION_EXTEND;
3101 }
3102 else {
3103 local_options &= ~ONIG_OPTION_EXTEND;
3104 }
3105
3106 rb_str_buf_cat(buf, (char *)&c, 1);
3107 int ret = unescape_nonascii0(&p, end, enc, buf, encp,
3108 has_property, err,
3109 local_options, 1);
3110 if (ret < 0) return ret;
3111 goto begin_scan;
3112 }
3113 else {
3114 /* change extended flag for rest of expression */
3115 extended_mode = local_extend == 1;
3116 goto fallthrough;
3117 }
3118 case 'i':
3119 case 'm':
3120 case 'a':
3121 case 'd':
3122 case 'u':
3123 /* other option flags, ignored during scanning */
3124 break;
3125 default:
3126 /* other character, no extended flag change*/
3127 goto fallthrough;
3128 }
3129 }
3130 }
3131 }
3132 else if (!in_char_class && recurse) {
3133 parens++;
3134 }
3135 /* FALLTHROUGH */
3136 default:
3137fallthrough:
3138 rb_str_buf_cat(buf, (char *)&c, 1);
3139 break;
3140 }
3141 }
3142
3143 if (recurse) {
3144 *pp = p;
3145 }
3146 return 0;
3147}
3148
3149static int
3150unescape_nonascii(const char *p, const char *end, rb_encoding *enc,
3151 VALUE buf, rb_encoding **encp, int *has_property,
3152 onig_errmsg_buffer err, int options)
3153{
3154 return unescape_nonascii0(&p, end, enc, buf, encp, has_property,
3155 err, options, 0);
3156}
3157
3158static VALUE
3159rb_reg_preprocess(const char *p, const char *end, rb_encoding *enc,
3160 rb_encoding **fixed_enc, onig_errmsg_buffer err, int options)
3161{
3162 VALUE buf;
3163 int has_property = 0;
3164
3165 buf = rb_str_buf_new(0);
3166
3167 if (rb_enc_asciicompat(enc))
3168 *fixed_enc = 0;
3169 else {
3170 *fixed_enc = enc;
3171 rb_enc_associate(buf, enc);
3172 }
3173
3174 if (unescape_nonascii(p, end, enc, buf, fixed_enc, &has_property, err, options) != 0)
3175 return Qnil;
3176
3177 if (has_property && !*fixed_enc) {
3178 *fixed_enc = enc;
3179 }
3180
3181 if (*fixed_enc) {
3182 rb_enc_associate(buf, *fixed_enc);
3183 }
3184
3185 return buf;
3186}
3187
3188VALUE
3189rb_reg_check_preprocess(VALUE str)
3190{
3191 rb_encoding *fixed_enc = 0;
3192 onig_errmsg_buffer err = "";
3193 VALUE buf;
3194 char *p, *end;
3195 rb_encoding *enc;
3196
3197 StringValue(str);
3198 p = RSTRING_PTR(str);
3199 end = p + RSTRING_LEN(str);
3200 enc = rb_enc_get(str);
3201
3202 buf = rb_reg_preprocess(p, end, enc, &fixed_enc, err, 0);
3203 RB_GC_GUARD(str);
3204
3205 if (NIL_P(buf)) {
3206 return rb_reg_error_desc(str, 0, err);
3207 }
3208 return Qnil;
3209}
3210
3211static VALUE
3212rb_reg_preprocess_dregexp(VALUE ary, int options)
3213{
3214 rb_encoding *fixed_enc = 0;
3215 rb_encoding *regexp_enc = 0;
3216 onig_errmsg_buffer err = "";
3217 int i;
3218 VALUE result = 0;
3219 rb_encoding *ascii8bit = rb_ascii8bit_encoding();
3220
3221 if (RARRAY_LEN(ary) == 0) {
3222 rb_raise(rb_eArgError, "no arguments given");
3223 }
3224
3225 for (i = 0; i < RARRAY_LEN(ary); i++) {
3226 VALUE str = RARRAY_AREF(ary, i);
3227 VALUE buf;
3228 char *p, *end;
3229 rb_encoding *src_enc;
3230
3231 src_enc = rb_enc_get(str);
3232 if (options & ARG_ENCODING_NONE &&
3233 src_enc != ascii8bit) {
3234 if (str_coderange(str) != ENC_CODERANGE_7BIT)
3235 rb_raise(rb_eRegexpError, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
3236 else
3237 src_enc = ascii8bit;
3238 }
3239
3240 StringValue(str);
3241 p = RSTRING_PTR(str);
3242 end = p + RSTRING_LEN(str);
3243
3244 buf = rb_reg_preprocess(p, end, src_enc, &fixed_enc, err, options);
3245
3246 if (NIL_P(buf))
3247 rb_raise(rb_eArgError, "%s", err);
3248
3249 if (fixed_enc != 0) {
3250 if (regexp_enc != 0 && regexp_enc != fixed_enc) {
3251 rb_raise(rb_eRegexpError, "encoding mismatch in dynamic regexp : %s and %s",
3252 rb_enc_name(regexp_enc), rb_enc_name(fixed_enc));
3253 }
3254 regexp_enc = fixed_enc;
3255 }
3256
3257 if (!result)
3258 result = rb_str_new3(str);
3259 else
3260 rb_str_buf_append(result, str);
3261 }
3262 if (regexp_enc) {
3263 rb_enc_associate(result, regexp_enc);
3264 }
3265
3266 return result;
3267}
3268
3269static void
3270rb_reg_initialize_check(VALUE obj)
3271{
3272 rb_check_frozen(obj);
3273 if (RREGEXP_PTR(obj)) {
3274 rb_raise(rb_eTypeError, "already initialized regexp");
3275 }
3276}
3277
3278static int
3279rb_reg_initialize(VALUE obj, const char *s, long len, rb_encoding *enc,
3280 int options, onig_errmsg_buffer err,
3281 const char *sourcefile, int sourceline)
3282{
3283 struct RRegexp *re = RREGEXP(obj);
3284 VALUE unescaped;
3285 rb_encoding *fixed_enc = 0;
3286 rb_encoding *a_enc = rb_ascii8bit_encoding();
3287
3288 rb_reg_initialize_check(obj);
3289
3290 if (rb_enc_dummy_p(enc)) {
3291 errcpy(err, "can't make regexp with dummy encoding");
3292 return -1;
3293 }
3294
3295 unescaped = rb_reg_preprocess(s, s+len, enc, &fixed_enc, err, options);
3296 if (NIL_P(unescaped))
3297 return -1;
3298
3299 if (fixed_enc) {
3300 if ((fixed_enc != enc && (options & ARG_ENCODING_FIXED)) ||
3301 (fixed_enc != a_enc && (options & ARG_ENCODING_NONE))) {
3302 errcpy(err, "incompatible character encoding");
3303 return -1;
3304 }
3305 if (fixed_enc != a_enc) {
3306 options |= ARG_ENCODING_FIXED;
3307 enc = fixed_enc;
3308 }
3309 }
3310 else if (!(options & ARG_ENCODING_FIXED)) {
3311 enc = rb_usascii_encoding();
3312 }
3313
3314 rb_enc_associate((VALUE)re, enc);
3315 if ((options & ARG_ENCODING_FIXED) || fixed_enc) {
3316 re->basic.flags |= KCODE_FIXED;
3317 }
3318 if (options & ARG_ENCODING_NONE) {
3319 re->basic.flags |= REG_ENCODING_NONE;
3320 }
3321
3322 re->ptr = make_regexp(RSTRING_PTR(unescaped), RSTRING_LEN(unescaped), enc,
3323 options & ARG_REG_OPTION_MASK, err,
3324 sourcefile, sourceline);
3325 if (!re->ptr) return -1;
3326 RB_GC_GUARD(unescaped);
3327 return 0;
3328}
3329
3330static void
3331reg_set_source(VALUE reg, VALUE str, rb_encoding *enc)
3332{
3333 rb_encoding *regenc = rb_enc_get(reg);
3334 if (regenc != enc) {
3335 str = rb_enc_associate(rb_str_dup(str), enc = regenc);
3336 }
3337 RB_OBJ_WRITE(reg, &RREGEXP(reg)->src, rb_fstring(str));
3338}
3339
3340static int
3341rb_reg_initialize_str(VALUE obj, VALUE str, int options, onig_errmsg_buffer err,
3342 const char *sourcefile, int sourceline)
3343{
3344 int ret;
3345 rb_encoding *str_enc = rb_enc_get(str), *enc = str_enc;
3346 if (options & ARG_ENCODING_NONE) {
3347 rb_encoding *ascii8bit = rb_ascii8bit_encoding();
3348 if (enc != ascii8bit) {
3349 if (str_coderange(str) != ENC_CODERANGE_7BIT) {
3350 errcpy(err, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
3351 return -1;
3352 }
3353 enc = ascii8bit;
3354 }
3355 }
3356 ret = rb_reg_initialize(obj, RSTRING_PTR(str), RSTRING_LEN(str), enc,
3357 options, err, sourcefile, sourceline);
3358 if (ret == 0) reg_set_source(obj, str, str_enc);
3359 return ret;
3360}
3361
3362static VALUE
3363rb_reg_s_alloc(VALUE klass)
3364{
3365 NEWOBJ_OF(re, struct RRegexp, klass, T_REGEXP | (RGENGC_WB_PROTECTED_REGEXP ? FL_WB_PROTECTED : 0), sizeof(struct RRegexp), 0);
3366
3367 re->ptr = 0;
3368 RB_OBJ_WRITE(re, &re->src, 0);
3369 re->usecnt = 0;
3370
3371 return (VALUE)re;
3372}
3373
3374VALUE
3375rb_reg_alloc(void)
3376{
3377 return rb_reg_s_alloc(rb_cRegexp);
3378}
3379
3380VALUE
3381rb_reg_new_str(VALUE s, int options)
3382{
3383 return rb_reg_init_str(rb_reg_alloc(), s, options);
3384}
3385
3386VALUE
3387rb_reg_init_str(VALUE re, VALUE s, int options)
3388{
3389 onig_errmsg_buffer err = "";
3390
3391 if (rb_reg_initialize_str(re, s, options, err, NULL, 0) != 0) {
3392 rb_reg_raise_str(s, options, err);
3393 }
3394
3395 return re;
3396}
3397
3398static VALUE
3399rb_reg_init_str_enc(VALUE re, VALUE s, rb_encoding *enc, int options)
3400{
3401 onig_errmsg_buffer err = "";
3402
3403 if (rb_reg_initialize(re, RSTRING_PTR(s), RSTRING_LEN(s),
3404 enc, options, err, NULL, 0) != 0) {
3405 rb_reg_raise_str(s, options, err);
3406 }
3407 reg_set_source(re, s, enc);
3408
3409 return re;
3410}
3411
3412VALUE
3413rb_reg_new_ary(VALUE ary, int opt)
3414{
3415 VALUE re = rb_reg_new_str(rb_reg_preprocess_dregexp(ary, opt), opt);
3416 rb_obj_freeze(re);
3417 return re;
3418}
3419
3420VALUE
3421rb_enc_reg_new(const char *s, long len, rb_encoding *enc, int options)
3422{
3423 VALUE re = rb_reg_alloc();
3424 onig_errmsg_buffer err = "";
3425
3426 if (rb_reg_initialize(re, s, len, enc, options, err, NULL, 0) != 0) {
3427 rb_enc_reg_raise(s, len, enc, options, err);
3428 }
3429 RB_OBJ_WRITE(re, &RREGEXP(re)->src, rb_fstring(rb_enc_str_new(s, len, enc)));
3430
3431 return re;
3432}
3433
3434VALUE
3435rb_reg_new(const char *s, long len, int options)
3436{
3437 return rb_enc_reg_new(s, len, rb_ascii8bit_encoding(), options);
3438}
3439
3440VALUE
3441rb_reg_compile(VALUE str, int options, const char *sourcefile, int sourceline)
3442{
3443 VALUE re = rb_reg_alloc();
3444 onig_errmsg_buffer err = "";
3445
3446 if (!str) str = rb_str_new(0,0);
3447 if (rb_reg_initialize_str(re, str, options, err, sourcefile, sourceline) != 0) {
3448 rb_set_errinfo(rb_reg_error_desc(str, options, err));
3449 return Qnil;
3450 }
3451 rb_obj_freeze(re);
3452 return re;
3453}
3454
3455static VALUE reg_cache;
3456
3457VALUE
3459{
3460 if (reg_cache && RREGEXP_SRC_LEN(reg_cache) == RSTRING_LEN(str)
3461 && ENCODING_GET(reg_cache) == ENCODING_GET(str)
3462 && memcmp(RREGEXP_SRC_PTR(reg_cache), RSTRING_PTR(str), RSTRING_LEN(str)) == 0)
3463 return reg_cache;
3464
3465 return reg_cache = rb_reg_new_str(str, 0);
3466}
3467
3468static st_index_t reg_hash(VALUE re);
3469/*
3470 * call-seq:
3471 * hash -> integer
3472 *
3473 * Returns the integer hash value for +self+.
3474 *
3475 * Related: Object#hash.
3476 *
3477 */
3478
3479VALUE
3480rb_reg_hash(VALUE re)
3481{
3482 st_index_t hashval = reg_hash(re);
3483 return ST2FIX(hashval);
3484}
3485
3486static st_index_t
3487reg_hash(VALUE re)
3488{
3489 st_index_t hashval;
3490
3491 rb_reg_check(re);
3492 hashval = RREGEXP_PTR(re)->options;
3493 hashval = rb_hash_uint(hashval, rb_memhash(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re)));
3494 return rb_hash_end(hashval);
3495}
3496
3497
3498/*
3499 * call-seq:
3500 * regexp == object -> true or false
3501 *
3502 * Returns +true+ if +object+ is another \Regexp whose pattern,
3503 * flags, and encoding are the same as +self+, +false+ otherwise:
3504 *
3505 * /foo/ == Regexp.new('foo') # => true
3506 * /foo/ == /foo/i # => false
3507 * /foo/ == Regexp.new('food') # => false
3508 * /foo/ == Regexp.new("abc".force_encoding("euc-jp")) # => false
3509 *
3510 */
3511
3512VALUE
3513rb_reg_equal(VALUE re1, VALUE re2)
3514{
3515 if (re1 == re2) return Qtrue;
3516 if (!RB_TYPE_P(re2, T_REGEXP)) return Qfalse;
3517 rb_reg_check(re1); rb_reg_check(re2);
3518 if (FL_TEST(re1, KCODE_FIXED) != FL_TEST(re2, KCODE_FIXED)) return Qfalse;
3519 if (RREGEXP_PTR(re1)->options != RREGEXP_PTR(re2)->options) return Qfalse;
3520 if (RREGEXP_SRC_LEN(re1) != RREGEXP_SRC_LEN(re2)) return Qfalse;
3521 if (ENCODING_GET(re1) != ENCODING_GET(re2)) return Qfalse;
3522 return RBOOL(memcmp(RREGEXP_SRC_PTR(re1), RREGEXP_SRC_PTR(re2), RREGEXP_SRC_LEN(re1)) == 0);
3523}
3524
3525/*
3526 * call-seq:
3527 * hash -> integer
3528 *
3529 * Returns the integer hash value for +self+,
3530 * based on the target string, regexp, match, and captures.
3531 *
3532 * See also Object#hash.
3533 *
3534 */
3535
3536static VALUE
3537match_hash(VALUE match)
3538{
3539 const struct re_registers *regs;
3540 st_index_t hashval;
3541
3542 match_check(match);
3543 hashval = rb_hash_start(rb_str_hash(RMATCH(match)->str));
3544 hashval = rb_hash_uint(hashval, reg_hash(match_regexp(match)));
3545 regs = RMATCH_REGS(match);
3546 hashval = rb_hash_uint(hashval, regs->num_regs);
3547 hashval = rb_hash_uint(hashval, rb_memhash(regs->beg, regs->num_regs * sizeof(*regs->beg)));
3548 hashval = rb_hash_uint(hashval, rb_memhash(regs->end, regs->num_regs * sizeof(*regs->end)));
3549 hashval = rb_hash_end(hashval);
3550 return ST2FIX(hashval);
3551}
3552
3553/*
3554 * call-seq:
3555 * matchdata == object -> true or false
3556 *
3557 * Returns +true+ if +object+ is another \MatchData object
3558 * whose target string, regexp, match, and captures
3559 * are the same as +self+, +false+ otherwise.
3560 */
3561
3562static VALUE
3563match_equal(VALUE match1, VALUE match2)
3564{
3565 const struct re_registers *regs1, *regs2;
3566
3567 if (match1 == match2) return Qtrue;
3568 if (!RB_TYPE_P(match2, T_MATCH)) return Qfalse;
3569 if (!RMATCH(match1)->regexp || !RMATCH(match2)->regexp) return Qfalse;
3570 if (!rb_str_equal(RMATCH(match1)->str, RMATCH(match2)->str)) return Qfalse;
3571 if (!rb_reg_equal(match_regexp(match1), match_regexp(match2))) return Qfalse;
3572 regs1 = RMATCH_REGS(match1);
3573 regs2 = RMATCH_REGS(match2);
3574 if (regs1->num_regs != regs2->num_regs) return Qfalse;
3575 if (memcmp(regs1->beg, regs2->beg, regs1->num_regs * sizeof(*regs1->beg))) return Qfalse;
3576 if (memcmp(regs1->end, regs2->end, regs1->num_regs * sizeof(*regs1->end))) return Qfalse;
3577 return Qtrue;
3578}
3579
3580static VALUE
3581reg_operand(VALUE s, int check)
3582{
3583 if (SYMBOL_P(s)) {
3584 return rb_sym2str(s);
3585 }
3586 else if (RB_TYPE_P(s, T_STRING)) {
3587 return s;
3588 }
3589 else {
3590 return check ? rb_str_to_str(s) : rb_check_string_type(s);
3591 }
3592}
3593
3594static long
3595reg_match_pos(VALUE re, VALUE *strp, long pos, VALUE* set_match)
3596{
3597 VALUE str = *strp;
3598
3599 if (NIL_P(str)) {
3601 return -1;
3602 }
3603 *strp = str = reg_operand(str, TRUE);
3604 if (pos != 0) {
3605 if (pos < 0) {
3606 VALUE l = rb_str_length(str);
3607 pos += NUM2INT(l);
3608 if (pos < 0) {
3609 return pos;
3610 }
3611 }
3612 pos = rb_str_offset(str, pos);
3613 }
3614 return rb_reg_search_set_match(re, str, pos, 0, 1, set_match);
3615}
3616
3617/*
3618 * call-seq:
3619 * regexp =~ string -> integer or nil
3620 *
3621 * Returns the integer index (in characters) of the first match
3622 * for +self+ and +string+, or +nil+ if none;
3623 * also sets the
3624 * {rdoc-ref:Regexp global variables}[rdoc-ref:Regexp@Global+Variables]:
3625 *
3626 * /at/ =~ 'input data' # => 7
3627 * $~ # => #<MatchData "at">
3628 * /ax/ =~ 'input data' # => nil
3629 * $~ # => nil
3630 *
3631 * Assigns named captures to local variables of the same names
3632 * if and only if +self+:
3633 *
3634 * - Is a regexp literal;
3635 * see {Regexp Literals}[rdoc-ref:literals.rdoc@Regexp+Literals].
3636 * - Does not contain interpolations;
3637 * see {Regexp interpolation}[rdoc-ref:Regexp@Interpolation+Mode].
3638 * - Is at the left of the expression.
3639 *
3640 * Example:
3641 *
3642 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ ' x = y '
3643 * p lhs # => "x"
3644 * p rhs # => "y"
3645 *
3646 * Assigns +nil+ if not matched:
3647 *
3648 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ ' x = '
3649 * p lhs # => nil
3650 * p rhs # => nil
3651 *
3652 * Does not make local variable assignments if +self+ is not a regexp literal:
3653 *
3654 * r = /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
3655 * r =~ ' x = y '
3656 * p foo # Undefined local variable
3657 * p bar # Undefined local variable
3658 *
3659 * The assignment does not occur if the regexp is not at the left:
3660 *
3661 * ' x = y ' =~ /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
3662 * p foo, foo # Undefined local variables
3663 *
3664 * A regexp interpolation, <tt>#{}</tt>, also disables
3665 * the assignment:
3666 *
3667 * r = /(?<foo>\w+)/
3668 * /(?<foo>\w+)\s*=\s*#{r}/ =~ 'x = y'
3669 * p foo # Undefined local variable
3670 *
3671 */
3672
3673VALUE
3675{
3676 long pos = reg_match_pos(re, &str, 0, NULL);
3677 if (pos < 0) return Qnil;
3678 pos = rb_str_sublen(str, pos);
3679 return LONG2FIX(pos);
3680}
3681
3682/*
3683 * call-seq:
3684 * regexp === string -> true or false
3685 *
3686 * Returns +true+ if +self+ finds a match in +string+:
3687 *
3688 * /^[a-z]*$/ === 'HELLO' # => false
3689 * /^[A-Z]*$/ === 'HELLO' # => true
3690 *
3691 * This method is called in case statements:
3692 *
3693 * s = 'HELLO'
3694 * case s
3695 * when /\A[a-z]*\z/; print "Lower case\n"
3696 * when /\A[A-Z]*\z/; print "Upper case\n"
3697 * else print "Mixed case\n"
3698 * end # => "Upper case"
3699 *
3700 */
3701
3702static VALUE
3703rb_reg_eqq(VALUE re, VALUE str)
3704{
3705 long start;
3706
3707 str = reg_operand(str, FALSE);
3708 if (NIL_P(str)) {
3710 return Qfalse;
3711 }
3712 start = rb_reg_search(re, str, 0, 0);
3713 return RBOOL(start >= 0);
3714}
3715
3716
3717/*
3718 * call-seq:
3719 * ~ rxp -> integer or nil
3720 *
3721 * Equivalent to <tt><i>rxp</i> =~ $_</tt>:
3722 *
3723 * $_ = "input data"
3724 * ~ /at/ # => 7
3725 *
3726 */
3727
3728VALUE
3730{
3731 long start;
3732 VALUE line = rb_lastline_get();
3733
3734 if (!RB_TYPE_P(line, T_STRING)) {
3736 return Qnil;
3737 }
3738
3739 start = rb_reg_search(re, line, 0, 0);
3740 if (start < 0) {
3741 return Qnil;
3742 }
3743 start = rb_str_sublen(line, start);
3744 return LONG2FIX(start);
3745}
3746
3747
3748/*
3749 * call-seq:
3750 * match(string, offset = 0) -> matchdata or nil
3751 * match(string, offset = 0) {|matchdata| ... } -> object
3752 *
3753 * With no block given, returns the MatchData object
3754 * that describes the match, if any, or +nil+ if none;
3755 * the search begins at the given character +offset+ in +string+:
3756 *
3757 * /abra/.match('abracadabra') # => #<MatchData "abra">
3758 * /abra/.match('abracadabra', 4) # => #<MatchData "abra">
3759 * /abra/.match('abracadabra', 8) # => nil
3760 * /abra/.match('abracadabra', 800) # => nil
3761 *
3762 * string = "\u{5d0 5d1 5e8 5d0}cadabra"
3763 * /abra/.match(string, 7) #=> #<MatchData "abra">
3764 * /abra/.match(string, 8) #=> nil
3765 * /abra/.match(string.b, 8) #=> #<MatchData "abra">
3766 *
3767 * With a block given, calls the block if and only if a match is found;
3768 * returns the block's value:
3769 *
3770 * /abra/.match('abracadabra') {|matchdata| p matchdata }
3771 * # => #<MatchData "abra">
3772 * /abra/.match('abracadabra', 4) {|matchdata| p matchdata }
3773 * # => #<MatchData "abra">
3774 * /abra/.match('abracadabra', 8) {|matchdata| p matchdata }
3775 * # => nil
3776 * /abra/.match('abracadabra', 8) {|marchdata| fail 'Cannot happen' }
3777 * # => nil
3778 *
3779 * Output (from the first two blocks above):
3780 *
3781 * #<MatchData "abra">
3782 * #<MatchData "abra">
3783 *
3784 * /(.)(.)(.)/.match("abc")[2] # => "b"
3785 * /(.)(.)/.match("abc", 1)[2] # => "c"
3786 *
3787 */
3788
3789static VALUE
3790rb_reg_match_m(int argc, VALUE *argv, VALUE re)
3791{
3792 VALUE result = Qnil, str, initpos;
3793 long pos;
3794
3795 if (rb_scan_args(argc, argv, "11", &str, &initpos) == 2) {
3796 pos = NUM2LONG(initpos);
3797 }
3798 else {
3799 pos = 0;
3800 }
3801
3802 pos = reg_match_pos(re, &str, pos, &result);
3803 if (pos < 0) {
3805 return Qnil;
3806 }
3807 rb_match_busy(result);
3808 if (!NIL_P(result) && rb_block_given_p()) {
3809 return rb_yield(result);
3810 }
3811 return result;
3812}
3813
3814/*
3815 * call-seq:
3816 * match?(string) -> true or false
3817 * match?(string, offset = 0) -> true or false
3818 *
3819 * Returns <code>true</code> or <code>false</code> to indicate whether the
3820 * regexp is matched or not without updating $~ and other related variables.
3821 * If the second parameter is present, it specifies the position in the string
3822 * to begin the search.
3823 *
3824 * /R.../.match?("Ruby") # => true
3825 * /R.../.match?("Ruby", 1) # => false
3826 * /P.../.match?("Ruby") # => false
3827 * $& # => nil
3828 */
3829
3830static VALUE
3831rb_reg_match_m_p(int argc, VALUE *argv, VALUE re)
3832{
3833 long pos = rb_check_arity(argc, 1, 2) > 1 ? NUM2LONG(argv[1]) : 0;
3834 return rb_reg_match_p(re, argv[0], pos);
3835}
3836
3837VALUE
3838rb_reg_match_p(VALUE re, VALUE str, long pos)
3839{
3840 if (NIL_P(str)) return Qfalse;
3841 str = SYMBOL_P(str) ? rb_sym2str(str) : StringValue(str);
3842 if (pos) {
3843 if (pos < 0) {
3844 pos += NUM2LONG(rb_str_length(str));
3845 if (pos < 0) return Qfalse;
3846 }
3847 if (pos > 0) {
3848 long len = 1;
3849 const char *beg = rb_str_subpos(str, pos, &len);
3850 if (!beg) return Qfalse;
3851 pos = beg - RSTRING_PTR(str);
3852 }
3853 }
3854
3855 struct reg_onig_search_args args = {
3856 .pos = pos,
3857 .range = RSTRING_LEN(str),
3858 };
3859
3860 return rb_reg_onig_match(re, str, reg_onig_search, &args, NULL) == ONIG_MISMATCH ? Qfalse : Qtrue;
3861}
3862
3863/*
3864 * Document-method: compile
3865 *
3866 * Alias for Regexp.new
3867 */
3868
3869static int
3870str_to_option(VALUE str)
3871{
3872 int flag = 0;
3873 const char *ptr;
3874 long len;
3875 str = rb_check_string_type(str);
3876 if (NIL_P(str)) return -1;
3877 RSTRING_GETMEM(str, ptr, len);
3878 for (long i = 0; i < len; ++i) {
3879 int f = char_to_option(ptr[i]);
3880 if (!f) {
3881 rb_raise(rb_eArgError, "unknown regexp option: %"PRIsVALUE, str);
3882 }
3883 flag |= f;
3884 }
3885 return flag;
3886}
3887
3888static void
3889set_timeout(rb_hrtime_t *hrt, VALUE timeout)
3890{
3891 double timeout_d = NIL_P(timeout) ? 0.0 : NUM2DBL(timeout);
3892 if (!NIL_P(timeout) && timeout_d <= 0) {
3893 rb_raise(rb_eArgError, "invalid timeout: %"PRIsVALUE, timeout);
3894 }
3895 double2hrtime(hrt, timeout_d);
3896}
3897
3898static VALUE
3899reg_copy(VALUE copy, VALUE orig)
3900{
3901 int r;
3902 regex_t *re;
3903
3904 rb_reg_initialize_check(copy);
3905 if ((r = onig_reg_copy(&re, RREGEXP_PTR(orig))) != 0) {
3906 /* ONIGERR_MEMORY only */
3907 rb_raise(rb_eRegexpError, "%s", onig_error_code_to_format(r));
3908 }
3909 RREGEXP_PTR(copy) = re;
3910 RB_OBJ_WRITE(copy, &RREGEXP(copy)->src, RREGEXP(orig)->src);
3911 RREGEXP_PTR(copy)->timelimit = RREGEXP_PTR(orig)->timelimit;
3912 rb_enc_copy(copy, orig);
3913 FL_SET_RAW(copy, FL_TEST_RAW(orig, KCODE_FIXED|REG_ENCODING_NONE));
3914
3915 return copy;
3916}
3917
3919 VALUE str;
3920 VALUE timeout;
3921 rb_encoding *enc;
3922 int flags;
3923};
3924
3925static VALUE reg_extract_args(int argc, VALUE *argv, struct reg_init_args *args);
3926static VALUE reg_init_args(VALUE self, VALUE str, rb_encoding *enc, int flags);
3927void rb_warn_deprecated_to_remove(const char *removal, const char *fmt, const char *suggest, ...);
3928
3929/*
3930 * call-seq:
3931 * Regexp.new(string, options = 0, timeout: nil) -> regexp
3932 * Regexp.new(regexp, timeout: nil) -> regexp
3933 *
3934 * With argument +string+ given, returns a new regexp with the given string
3935 * and options:
3936 *
3937 * r = Regexp.new('foo') # => /foo/
3938 * r.source # => "foo"
3939 * r.options # => 0
3940 *
3941 * Optional argument +options+ is one of the following:
3942 *
3943 * - A String of options:
3944 *
3945 * Regexp.new('foo', 'i') # => /foo/i
3946 * Regexp.new('foo', 'im') # => /foo/im
3947 *
3948 * - The bit-wise OR of one or more of the constants
3949 * Regexp::EXTENDED, Regexp::IGNORECASE, Regexp::MULTILINE, and
3950 * Regexp::NOENCODING:
3951 *
3952 * Regexp.new('foo', Regexp::IGNORECASE) # => /foo/i
3953 * Regexp.new('foo', Regexp::EXTENDED) # => /foo/x
3954 * Regexp.new('foo', Regexp::MULTILINE) # => /foo/m
3955 * Regexp.new('foo', Regexp::NOENCODING) # => /foo/n
3956 * flags = Regexp::IGNORECASE | Regexp::EXTENDED | Regexp::MULTILINE
3957 * Regexp.new('foo', flags) # => /foo/mix
3958 *
3959 * - +nil+ or +false+, which is ignored.
3960 * - Any other truthy value, in which case the regexp will be
3961 * case-insensitive.
3962 *
3963 * If optional keyword argument +timeout+ is given,
3964 * its float value overrides the timeout interval for the class,
3965 * Regexp.timeout.
3966 * If +nil+ is passed as +timeout, it uses the timeout interval
3967 * for the class, Regexp.timeout.
3968 *
3969 * With argument +regexp+ given, returns a new regexp. The source,
3970 * options, timeout are the same as +regexp+. +options+ and +n_flag+
3971 * arguments are ineffective. The timeout can be overridden by
3972 * +timeout+ keyword.
3973 *
3974 * options = Regexp::MULTILINE
3975 * r = Regexp.new('foo', options, timeout: 1.1) # => /foo/m
3976 * r2 = Regexp.new(r) # => /foo/m
3977 * r2.timeout # => 1.1
3978 * r3 = Regexp.new(r, timeout: 3.14) # => /foo/m
3979 * r3.timeout # => 3.14
3980 *
3981 */
3982
3983static VALUE
3984rb_reg_initialize_m(int argc, VALUE *argv, VALUE self)
3985{
3986 struct reg_init_args args;
3987 VALUE re = reg_extract_args(argc, argv, &args);
3988
3989 if (NIL_P(re)) {
3990 reg_init_args(self, args.str, args.enc, args.flags);
3991 }
3992 else {
3993 reg_copy(self, re);
3994 }
3995
3996 set_timeout(&RREGEXP_PTR(self)->timelimit, args.timeout);
3997
3998 return self;
3999}
4000
4001static VALUE
4002reg_extract_args(int argc, VALUE *argv, struct reg_init_args *args)
4003{
4004 int flags = 0;
4005 rb_encoding *enc = 0;
4006 VALUE str, src, opts = Qundef, kwargs;
4007 VALUE re = Qnil;
4008
4009 rb_scan_args(argc, argv, "11:", &src, &opts, &kwargs);
4010
4011 args->timeout = Qnil;
4012 if (!NIL_P(kwargs)) {
4013 static ID keywords[1];
4014 if (!keywords[0]) {
4015 keywords[0] = rb_intern_const("timeout");
4016 }
4017 rb_get_kwargs(kwargs, keywords, 0, 1, &args->timeout);
4018 }
4019
4020 if (RB_TYPE_P(src, T_REGEXP)) {
4021 re = src;
4022
4023 if (!NIL_P(opts)) {
4024 rb_warn("flags ignored");
4025 }
4026 rb_reg_check(re);
4027 flags = rb_reg_options(re);
4028 str = RREGEXP_SRC(re);
4029 }
4030 else {
4031 if (!NIL_P(opts)) {
4032 int f;
4033 if (FIXNUM_P(opts)) flags = FIX2INT(opts);
4034 else if ((f = str_to_option(opts)) >= 0) flags = f;
4035 else if (rb_bool_expected(opts, "ignorecase", FALSE))
4036 flags = ONIG_OPTION_IGNORECASE;
4037 }
4038 str = StringValue(src);
4039 }
4040 args->str = str;
4041 args->enc = enc;
4042 args->flags = flags;
4043 return re;
4044}
4045
4046static VALUE
4047reg_init_args(VALUE self, VALUE str, rb_encoding *enc, int flags)
4048{
4049 if (enc && rb_enc_get(str) != enc)
4050 rb_reg_init_str_enc(self, str, enc, flags);
4051 else
4052 rb_reg_init_str(self, str, flags);
4053 return self;
4054}
4055
4056VALUE
4058{
4059 rb_encoding *enc = rb_enc_get(str);
4060 char *s, *send, *t;
4061 VALUE tmp;
4062 int c, clen;
4063 int ascii_only = rb_enc_str_asciionly_p(str);
4064
4065 s = RSTRING_PTR(str);
4066 send = s + RSTRING_LEN(str);
4067 while (s < send) {
4068 c = rb_enc_ascget(s, send, &clen, enc);
4069 if (c == -1) {
4070 s += mbclen(s, send, enc);
4071 continue;
4072 }
4073 switch (c) {
4074 case '[': case ']': case '{': case '}':
4075 case '(': case ')': case '|': case '-':
4076 case '*': case '.': case '\\':
4077 case '?': case '+': case '^': case '$':
4078 case ' ': case '#':
4079 case '\t': case '\f': case '\v': case '\n': case '\r':
4080 goto meta_found;
4081 }
4082 s += clen;
4083 }
4084 tmp = rb_str_new3(str);
4085 if (ascii_only) {
4086 rb_enc_associate(tmp, rb_usascii_encoding());
4087 }
4088 return tmp;
4089
4090 meta_found:
4091 tmp = rb_str_new(0, RSTRING_LEN(str)*2);
4092 if (ascii_only) {
4093 rb_enc_associate(tmp, rb_usascii_encoding());
4094 }
4095 else {
4096 rb_enc_copy(tmp, str);
4097 }
4098 t = RSTRING_PTR(tmp);
4099 /* copy upto metacharacter */
4100 const char *p = RSTRING_PTR(str);
4101 memcpy(t, p, s - p);
4102 t += s - p;
4103
4104 while (s < send) {
4105 c = rb_enc_ascget(s, send, &clen, enc);
4106 if (c == -1) {
4107 int n = mbclen(s, send, enc);
4108
4109 while (n--)
4110 *t++ = *s++;
4111 continue;
4112 }
4113 s += clen;
4114 switch (c) {
4115 case '[': case ']': case '{': case '}':
4116 case '(': case ')': case '|': case '-':
4117 case '*': case '.': case '\\':
4118 case '?': case '+': case '^': case '$':
4119 case '#':
4120 t += rb_enc_mbcput('\\', t, enc);
4121 break;
4122 case ' ':
4123 t += rb_enc_mbcput('\\', t, enc);
4124 t += rb_enc_mbcput(' ', t, enc);
4125 continue;
4126 case '\t':
4127 t += rb_enc_mbcput('\\', t, enc);
4128 t += rb_enc_mbcput('t', t, enc);
4129 continue;
4130 case '\n':
4131 t += rb_enc_mbcput('\\', t, enc);
4132 t += rb_enc_mbcput('n', t, enc);
4133 continue;
4134 case '\r':
4135 t += rb_enc_mbcput('\\', t, enc);
4136 t += rb_enc_mbcput('r', t, enc);
4137 continue;
4138 case '\f':
4139 t += rb_enc_mbcput('\\', t, enc);
4140 t += rb_enc_mbcput('f', t, enc);
4141 continue;
4142 case '\v':
4143 t += rb_enc_mbcput('\\', t, enc);
4144 t += rb_enc_mbcput('v', t, enc);
4145 continue;
4146 }
4147 t += rb_enc_mbcput(c, t, enc);
4148 }
4149 rb_str_resize(tmp, t - RSTRING_PTR(tmp));
4150 return tmp;
4151}
4152
4153
4154/*
4155 * call-seq:
4156 * Regexp.escape(string) -> new_string
4157 *
4158 * Returns a new string that escapes any characters
4159 * that have special meaning in a regular expression:
4160 *
4161 * s = Regexp.escape('\*?{}.') # => "\\\\\\*\\?\\{\\}\\."
4162 *
4163 * For any string +s+, this call returns a MatchData object:
4164 *
4165 * r = Regexp.new(Regexp.escape(s)) # => /\\\\\\\*\\\?\\\{\\\}\\\./
4166 * r.match(s) # => #<MatchData "\\\\\\*\\?\\{\\}\\.">
4167 *
4168 */
4169
4170static VALUE
4171rb_reg_s_quote(VALUE c, VALUE str)
4172{
4173 return rb_reg_quote(reg_operand(str, TRUE));
4174}
4175
4176int
4178{
4179 int options;
4180
4181 rb_reg_check(re);
4182 options = RREGEXP_PTR(re)->options & ARG_REG_OPTION_MASK;
4183 if (RBASIC(re)->flags & KCODE_FIXED) options |= ARG_ENCODING_FIXED;
4184 if (RBASIC(re)->flags & REG_ENCODING_NONE) options |= ARG_ENCODING_NONE;
4185 return options;
4186}
4187
4188static VALUE
4189rb_check_regexp_type(VALUE re)
4190{
4191 return rb_check_convert_type(re, T_REGEXP, "Regexp", "to_regexp");
4192}
4193
4194/*
4195 * call-seq:
4196 * Regexp.try_convert(object) -> regexp or nil
4197 *
4198 * Returns +object+ if it is a regexp:
4199 *
4200 * Regexp.try_convert(/re/) # => /re/
4201 *
4202 * Otherwise if +object+ responds to <tt>:to_regexp</tt>,
4203 * calls <tt>object.to_regexp</tt> and returns the result.
4204 *
4205 * Returns +nil+ if +object+ does not respond to <tt>:to_regexp</tt>.
4206 *
4207 * Regexp.try_convert('re') # => nil
4208 *
4209 * Raises an exception unless <tt>object.to_regexp</tt> returns a regexp.
4210 *
4211 */
4212static VALUE
4213rb_reg_s_try_convert(VALUE dummy, VALUE re)
4214{
4215 return rb_check_regexp_type(re);
4216}
4217
4218static VALUE
4219rb_reg_s_union(VALUE self, VALUE args0)
4220{
4221 long argc = RARRAY_LEN(args0);
4222
4223 if (argc == 0) {
4224 VALUE args[1];
4225 args[0] = rb_str_new2("(?!)");
4226 return rb_class_new_instance(1, args, rb_cRegexp);
4227 }
4228 else if (argc == 1) {
4229 VALUE arg = rb_ary_entry(args0, 0);
4230 VALUE re = rb_check_regexp_type(arg);
4231 if (!NIL_P(re))
4232 return re;
4233 else {
4234 VALUE quoted;
4235 quoted = rb_reg_s_quote(Qnil, arg);
4236 return rb_reg_new_str(quoted, 0);
4237 }
4238 }
4239 else {
4240 int i;
4241 VALUE source = rb_str_buf_new(0);
4242 rb_encoding *result_enc;
4243
4244 int has_asciionly = 0;
4245 rb_encoding *has_ascii_compat_fixed = 0;
4246 rb_encoding *has_ascii_incompat = 0;
4247
4248 for (i = 0; i < argc; i++) {
4249 volatile VALUE v;
4250 VALUE e = rb_ary_entry(args0, i);
4251
4252 if (0 < i)
4253 rb_str_buf_cat_ascii(source, "|");
4254
4255 v = rb_check_regexp_type(e);
4256 if (!NIL_P(v)) {
4257 rb_encoding *enc = rb_enc_get(v);
4258 if (!rb_enc_asciicompat(enc)) {
4259 if (!has_ascii_incompat)
4260 has_ascii_incompat = enc;
4261 else if (has_ascii_incompat != enc)
4262 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4263 rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
4264 }
4265 else if (rb_reg_fixed_encoding_p(v)) {
4266 if (!has_ascii_compat_fixed)
4267 has_ascii_compat_fixed = enc;
4268 else if (has_ascii_compat_fixed != enc)
4269 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4270 rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
4271 }
4272 else {
4273 has_asciionly = 1;
4274 }
4275 v = rb_reg_str_with_term(v, -1);
4276 }
4277 else {
4278 rb_encoding *enc;
4279 StringValue(e);
4280 enc = rb_enc_get(e);
4281 if (!rb_enc_asciicompat(enc)) {
4282 if (!has_ascii_incompat)
4283 has_ascii_incompat = enc;
4284 else if (has_ascii_incompat != enc)
4285 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4286 rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
4287 }
4288 else if (rb_enc_str_asciionly_p(e)) {
4289 has_asciionly = 1;
4290 }
4291 else {
4292 if (!has_ascii_compat_fixed)
4293 has_ascii_compat_fixed = enc;
4294 else if (has_ascii_compat_fixed != enc)
4295 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4296 rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
4297 }
4298 v = rb_reg_s_quote(Qnil, e);
4299 }
4300 if (has_ascii_incompat) {
4301 if (has_asciionly) {
4302 rb_raise(rb_eArgError, "ASCII incompatible encoding: %s",
4303 rb_enc_name(has_ascii_incompat));
4304 }
4305 if (has_ascii_compat_fixed) {
4306 rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
4307 rb_enc_name(has_ascii_incompat), rb_enc_name(has_ascii_compat_fixed));
4308 }
4309 }
4310
4311 if (i == 0) {
4312 rb_enc_copy(source, v);
4313 }
4314 rb_str_append(source, v);
4315 }
4316
4317 if (has_ascii_incompat) {
4318 result_enc = has_ascii_incompat;
4319 }
4320 else if (has_ascii_compat_fixed) {
4321 result_enc = has_ascii_compat_fixed;
4322 }
4323 else {
4324 result_enc = rb_ascii8bit_encoding();
4325 }
4326
4327 rb_enc_associate(source, result_enc);
4328 return rb_class_new_instance(1, &source, rb_cRegexp);
4329 }
4330}
4331
4332/*
4333 * call-seq:
4334 * Regexp.union(*patterns) -> regexp
4335 * Regexp.union(array_of_patterns) -> regexp
4336 *
4337 * Returns a new regexp that is the union of the given patterns:
4338 *
4339 * r = Regexp.union(%w[cat dog]) # => /cat|dog/
4340 * r.match('cat') # => #<MatchData "cat">
4341 * r.match('dog') # => #<MatchData "dog">
4342 * r.match('cog') # => nil
4343 *
4344 * For each pattern that is a string, <tt>Regexp.new(pattern)</tt> is used:
4345 *
4346 * Regexp.union('penzance') # => /penzance/
4347 * Regexp.union('a+b*c') # => /a\+b\*c/
4348 * Regexp.union('skiing', 'sledding') # => /skiing|sledding/
4349 * Regexp.union(['skiing', 'sledding']) # => /skiing|sledding/
4350 *
4351 * For each pattern that is a regexp, it is used as is,
4352 * including its flags:
4353 *
4354 * Regexp.union(/foo/i, /bar/m, /baz/x)
4355 * # => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
4356 * Regexp.union([/foo/i, /bar/m, /baz/x])
4357 * # => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
4358 *
4359 * With no arguments, returns <tt>/(?!)/</tt>:
4360 *
4361 * Regexp.union # => /(?!)/
4362 *
4363 * If any regexp pattern contains captures, the behavior is unspecified.
4364 *
4365 */
4366static VALUE
4367rb_reg_s_union_m(VALUE self, VALUE args)
4368{
4369 VALUE v;
4370 if (RARRAY_LEN(args) == 1 &&
4371 !NIL_P(v = rb_check_array_type(rb_ary_entry(args, 0)))) {
4372 return rb_reg_s_union(self, v);
4373 }
4374 return rb_reg_s_union(self, args);
4375}
4376
4377/*
4378 * call-seq:
4379 * Regexp.linear_time?(re)
4380 * Regexp.linear_time?(string, options = 0)
4381 *
4382 * Returns +true+ if matching against <tt>re</tt> can be
4383 * done in linear time to the input string.
4384 *
4385 * Regexp.linear_time?(/re/) # => true
4386 *
4387 * Note that this is a property of the ruby interpreter, not of the argument
4388 * regular expression. Identical regexp can or cannot run in linear time
4389 * depending on your ruby binary. Neither forward nor backward compatibility
4390 * is guaranteed about the return value of this method. Our current algorithm
4391 * is (*1) but this is subject to change in the future. Alternative
4392 * implementations can also behave differently. They might always return
4393 * false for everything.
4394 *
4395 * (*1): https://doi.org/10.1109/SP40001.2021.00032
4396 *
4397 */
4398static VALUE
4399rb_reg_s_linear_time_p(int argc, VALUE *argv, VALUE self)
4400{
4401 struct reg_init_args args;
4402 VALUE re = reg_extract_args(argc, argv, &args);
4403
4404 if (NIL_P(re)) {
4405 re = reg_init_args(rb_reg_alloc(), args.str, args.enc, args.flags);
4406 }
4407
4408 return RBOOL(onig_check_linear_time(RREGEXP_PTR(re)));
4409}
4410
4411/* :nodoc: */
4412static VALUE
4413rb_reg_init_copy(VALUE copy, VALUE re)
4414{
4415 if (!OBJ_INIT_COPY(copy, re)) return copy;
4416 rb_reg_check(re);
4417 return reg_copy(copy, re);
4418}
4419
4420VALUE
4421rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp)
4422{
4423 VALUE val = 0;
4424 char *p, *s, *e;
4425 int no, clen;
4426 rb_encoding *str_enc = rb_enc_get(str);
4427 rb_encoding *src_enc = rb_enc_get(src);
4428 int acompat = rb_enc_asciicompat(str_enc);
4429 long n;
4430#define ASCGET(s,e,cl) (acompat ? (*(cl)=1,ISASCII((s)[0])?(s)[0]:-1) : rb_enc_ascget((s), (e), (cl), str_enc))
4431
4432 RSTRING_GETMEM(str, s, n);
4433 p = s;
4434 e = s + n;
4435
4436 while (s < e) {
4437 int c = ASCGET(s, e, &clen);
4438 char *ss;
4439
4440 if (c == -1) {
4441 s += mbclen(s, e, str_enc);
4442 continue;
4443 }
4444 ss = s;
4445 s += clen;
4446
4447 if (c != '\\' || s == e) continue;
4448
4449 if (!val) {
4450 val = rb_str_buf_new(ss-p);
4451 }
4452 rb_enc_str_buf_cat(val, p, ss-p, str_enc);
4453
4454 c = ASCGET(s, e, &clen);
4455 if (c == -1) {
4456 s += mbclen(s, e, str_enc);
4457 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
4458 p = s;
4459 continue;
4460 }
4461 s += clen;
4462
4463 p = s;
4464 switch (c) {
4465 case '1': case '2': case '3': case '4':
4466 case '5': case '6': case '7': case '8': case '9':
4467 if (!NIL_P(regexp) && onig_noname_group_capture_is_active(RREGEXP_PTR(regexp))) {
4468 no = c - '0';
4469 }
4470 else {
4471 continue;
4472 }
4473 break;
4474
4475 case 'k':
4476 if (s < e && ASCGET(s, e, &clen) == '<') {
4477 char *name, *name_end;
4478
4479 name_end = name = s + clen;
4480 while (name_end < e) {
4481 c = ASCGET(name_end, e, &clen);
4482 if (c == '>') break;
4483 name_end += c == -1 ? mbclen(name_end, e, str_enc) : clen;
4484 }
4485 if (name_end < e) {
4486 VALUE n = rb_str_subseq(str, (long)(name - RSTRING_PTR(str)),
4487 (long)(name_end - name));
4488 if ((no = NAME_TO_NUMBER(regs, regexp, n, name, name_end)) < 1) {
4489 name_to_backref_error(n);
4490 }
4491 p = s = name_end + clen;
4492 break;
4493 }
4494 else {
4495 rb_raise(rb_eRuntimeError, "invalid group name reference format");
4496 }
4497 }
4498
4499 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
4500 continue;
4501
4502 case '0':
4503 case '&':
4504 no = 0;
4505 break;
4506
4507 case '`':
4508 rb_enc_str_buf_cat(val, RSTRING_PTR(src), BEG(0), src_enc);
4509 continue;
4510
4511 case '\'':
4512 rb_enc_str_buf_cat(val, RSTRING_PTR(src)+END(0), RSTRING_LEN(src)-END(0), src_enc);
4513 continue;
4514
4515 case '+':
4516 no = regs->num_regs-1;
4517 while (BEG(no) == -1 && no > 0) no--;
4518 if (no == 0) continue;
4519 break;
4520
4521 case '\\':
4522 rb_enc_str_buf_cat(val, s-clen, clen, str_enc);
4523 continue;
4524
4525 default:
4526 rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
4527 continue;
4528 }
4529
4530 if (no >= 0) {
4531 if (no >= regs->num_regs) continue;
4532 if (BEG(no) == -1) continue;
4533 rb_enc_str_buf_cat(val, RSTRING_PTR(src)+BEG(no), END(no)-BEG(no), src_enc);
4534 }
4535 }
4536
4537 if (!val) return str;
4538 if (p < e) {
4539 rb_enc_str_buf_cat(val, p, e-p, str_enc);
4540 }
4541
4542 return val;
4543}
4544
4545static VALUE
4546ignorecase_getter(ID _x, VALUE *_y)
4547{
4548 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "variable $= is no longer effective");
4549 return Qfalse;
4550}
4551
4552static void
4553ignorecase_setter(VALUE val, ID id, VALUE *_)
4554{
4555 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "variable $= is no longer effective; ignored");
4556}
4557
4558static VALUE
4559match_getter(void)
4560{
4561 VALUE match = rb_backref_get();
4562
4563 if (NIL_P(match)) return Qnil;
4564 rb_match_busy(match);
4565 return match;
4566}
4567
4568static VALUE
4569get_LAST_MATCH_INFO(ID _x, VALUE *_y)
4570{
4571 return match_getter();
4572}
4573
4574static void
4575match_setter(VALUE val, ID _x, VALUE *_y)
4576{
4577 if (!NIL_P(val)) {
4578 Check_Type(val, T_MATCH);
4579 }
4580 rb_backref_set(val);
4581}
4582
4583/*
4584 * call-seq:
4585 * Regexp.last_match -> matchdata or nil
4586 * Regexp.last_match(n) -> string or nil
4587 * Regexp.last_match(name) -> string or nil
4588 *
4589 * With no argument, returns the value of <tt>$!</tt>,
4590 * which is the result of the most recent pattern match
4591 * (see {Regexp global variables}[rdoc-ref:Regexp@Global+Variables]):
4592 *
4593 * /c(.)t/ =~ 'cat' # => 0
4594 * Regexp.last_match # => #<MatchData "cat" 1:"a">
4595 * /a/ =~ 'foo' # => nil
4596 * Regexp.last_match # => nil
4597 *
4598 * With non-negative integer argument +n+, returns the _n_th field in the
4599 * matchdata, if any, or nil if none:
4600 *
4601 * /c(.)t/ =~ 'cat' # => 0
4602 * Regexp.last_match(0) # => "cat"
4603 * Regexp.last_match(1) # => "a"
4604 * Regexp.last_match(2) # => nil
4605 *
4606 * With negative integer argument +n+, counts backwards from the last field:
4607 *
4608 * Regexp.last_match(-1) # => "a"
4609 *
4610 * With string or symbol argument +name+,
4611 * returns the string value for the named capture, if any:
4612 *
4613 * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ 'var = val'
4614 * Regexp.last_match # => #<MatchData "var = val" lhs:"var"rhs:"val">
4615 * Regexp.last_match(:lhs) # => "var"
4616 * Regexp.last_match('rhs') # => "val"
4617 * Regexp.last_match('foo') # Raises IndexError.
4618 *
4619 */
4620
4621static VALUE
4622rb_reg_s_last_match(int argc, VALUE *argv, VALUE _)
4623{
4624 if (rb_check_arity(argc, 0, 1) == 1) {
4625 VALUE match = rb_backref_get();
4626 int n;
4627 if (NIL_P(match)) return Qnil;
4628 n = match_backref_number(match, argv[0]);
4629 return rb_reg_nth_match(n, match);
4630 }
4631 return match_getter();
4632}
4633
4634static void
4635re_warn(const char *s)
4636{
4637 rb_warn("%s", s);
4638}
4639
4640// This function is periodically called during regexp matching
4641bool
4642rb_reg_timeout_p(regex_t *reg, void *end_time_)
4643{
4644 rb_hrtime_t *end_time = (rb_hrtime_t *)end_time_;
4645
4646 if (*end_time == 0) {
4647 // This is the first time to check interrupts;
4648 // just measure the current time and determine the end time
4649 // if timeout is set.
4650 rb_hrtime_t timelimit = reg->timelimit;
4651
4652 if (!timelimit) {
4653 // no per-object timeout.
4654 timelimit = rb_reg_match_time_limit;
4655 }
4656
4657 if (timelimit) {
4658 *end_time = rb_hrtime_add(timelimit, rb_hrtime_now());
4659 }
4660 else {
4661 // no timeout is set
4662 *end_time = RB_HRTIME_MAX;
4663 }
4664 }
4665 else {
4666 if (*end_time < rb_hrtime_now()) {
4667 // Timeout has exceeded
4668 return true;
4669 }
4670 }
4671
4672 return false;
4673}
4674
4675void
4676rb_reg_raise_timeout(void)
4677{
4678 rb_raise(rb_eRegexpTimeoutError, "regexp match timeout");
4679}
4680
4681/*
4682 * call-seq:
4683 * Regexp.timeout -> float or nil
4684 *
4685 * It returns the current default timeout interval for Regexp matching in second.
4686 * +nil+ means no default timeout configuration.
4687 */
4688
4689static VALUE
4690rb_reg_s_timeout_get(VALUE dummy)
4691{
4692 double d = hrtime2double(rb_reg_match_time_limit);
4693 if (d == 0.0) return Qnil;
4694 return DBL2NUM(d);
4695}
4696
4697/*
4698 * call-seq:
4699 * Regexp.timeout = float or nil
4700 *
4701 * It sets the default timeout interval for Regexp matching in second.
4702 * +nil+ means no default timeout configuration.
4703 * This configuration is process-global. If you want to set timeout for
4704 * each Regexp, use +timeout+ keyword for <code>Regexp.new</code>.
4705 *
4706 * Regexp.timeout = 1
4707 * /^a*b?a*$/ =~ "a" * 100000 + "x" #=> regexp match timeout (RuntimeError)
4708 */
4709
4710static VALUE
4711rb_reg_s_timeout_set(VALUE dummy, VALUE timeout)
4712{
4713 rb_ractor_ensure_main_ractor("can not access Regexp.timeout from non-main Ractors");
4714
4715 set_timeout(&rb_reg_match_time_limit, timeout);
4716
4717 return timeout;
4718}
4719
4720/*
4721 * call-seq:
4722 * rxp.timeout -> float or nil
4723 *
4724 * It returns the timeout interval for Regexp matching in second.
4725 * +nil+ means no default timeout configuration.
4726 *
4727 * This configuration is per-object. The global configuration set by
4728 * Regexp.timeout= is ignored if per-object configuration is set.
4729 *
4730 * re = Regexp.new("^a*b?a*$", timeout: 1)
4731 * re.timeout #=> 1.0
4732 * re =~ "a" * 100000 + "x" #=> regexp match timeout (RuntimeError)
4733 */
4734
4735static VALUE
4736rb_reg_timeout_get(VALUE re)
4737{
4738 rb_reg_check(re);
4739 double d = hrtime2double(RREGEXP_PTR(re)->timelimit);
4740 if (d == 0.0) return Qnil;
4741 return DBL2NUM(d);
4742}
4743
4744/*
4745 * Document-class: RegexpError
4746 *
4747 * Raised when given an invalid regexp expression.
4748 *
4749 * Regexp.new("?")
4750 *
4751 * <em>raises the exception:</em>
4752 *
4753 * RegexpError: target of repeat operator is not specified: /?/
4754 */
4755
4756/*
4757 * Document-class: Regexp
4758 *
4759 * :include: doc/_regexp.rdoc
4760 */
4761
4762void
4763Init_Regexp(void)
4764{
4766
4767 onigenc_set_default_encoding(ONIG_ENCODING_ASCII);
4768 onig_set_warn_func(re_warn);
4769 onig_set_verb_warn_func(re_warn);
4770
4771 rb_define_virtual_variable("$~", get_LAST_MATCH_INFO, match_setter);
4772 rb_define_virtual_variable("$&", last_match_getter, 0);
4773 rb_define_virtual_variable("$`", prematch_getter, 0);
4774 rb_define_virtual_variable("$'", postmatch_getter, 0);
4775 rb_define_virtual_variable("$+", last_paren_match_getter, 0);
4776
4777 rb_gvar_ractor_local("$~");
4778 rb_gvar_ractor_local("$&");
4779 rb_gvar_ractor_local("$`");
4780 rb_gvar_ractor_local("$'");
4781 rb_gvar_ractor_local("$+");
4782
4783 rb_define_virtual_variable("$=", ignorecase_getter, ignorecase_setter);
4784
4785 rb_cRegexp = rb_define_class("Regexp", rb_cObject);
4786 rb_define_alloc_func(rb_cRegexp, rb_reg_s_alloc);
4788 rb_define_singleton_method(rb_cRegexp, "quote", rb_reg_s_quote, 1);
4789 rb_define_singleton_method(rb_cRegexp, "escape", rb_reg_s_quote, 1);
4790 rb_define_singleton_method(rb_cRegexp, "union", rb_reg_s_union_m, -2);
4791 rb_define_singleton_method(rb_cRegexp, "last_match", rb_reg_s_last_match, -1);
4792 rb_define_singleton_method(rb_cRegexp, "try_convert", rb_reg_s_try_convert, 1);
4793 rb_define_singleton_method(rb_cRegexp, "linear_time?", rb_reg_s_linear_time_p, -1);
4794
4795 rb_define_method(rb_cRegexp, "initialize", rb_reg_initialize_m, -1);
4796 rb_define_method(rb_cRegexp, "initialize_copy", rb_reg_init_copy, 1);
4797 rb_define_method(rb_cRegexp, "hash", rb_reg_hash, 0);
4798 rb_define_method(rb_cRegexp, "eql?", rb_reg_equal, 1);
4799 rb_define_method(rb_cRegexp, "==", rb_reg_equal, 1);
4800 rb_define_method(rb_cRegexp, "=~", rb_reg_match, 1);
4801 rb_define_method(rb_cRegexp, "===", rb_reg_eqq, 1);
4802 rb_define_method(rb_cRegexp, "~", rb_reg_match2, 0);
4803 rb_define_method(rb_cRegexp, "match", rb_reg_match_m, -1);
4804 rb_define_method(rb_cRegexp, "match?", rb_reg_match_m_p, -1);
4805 rb_define_method(rb_cRegexp, "to_s", rb_reg_to_s, 0);
4806 rb_define_method(rb_cRegexp, "inspect", rb_reg_inspect, 0);
4807 rb_define_method(rb_cRegexp, "source", rb_reg_source, 0);
4808 rb_define_method(rb_cRegexp, "casefold?", rb_reg_casefold_p, 0);
4809 rb_define_method(rb_cRegexp, "options", rb_reg_options_m, 0);
4810 rb_define_method(rb_cRegexp, "encoding", rb_obj_encoding, 0); /* in encoding.c */
4811 rb_define_method(rb_cRegexp, "fixed_encoding?", rb_reg_fixed_encoding_p, 0);
4812 rb_define_method(rb_cRegexp, "names", rb_reg_names, 0);
4813 rb_define_method(rb_cRegexp, "named_captures", rb_reg_named_captures, 0);
4814 rb_define_method(rb_cRegexp, "timeout", rb_reg_timeout_get, 0);
4815
4816 rb_eRegexpTimeoutError = rb_define_class_under(rb_cRegexp, "TimeoutError", rb_eRegexpError);
4817 rb_define_singleton_method(rb_cRegexp, "timeout", rb_reg_s_timeout_get, 0);
4818 rb_define_singleton_method(rb_cRegexp, "timeout=", rb_reg_s_timeout_set, 1);
4819
4820 /* see Regexp.options and Regexp.new */
4821 rb_define_const(rb_cRegexp, "IGNORECASE", INT2FIX(ONIG_OPTION_IGNORECASE));
4822 /* see Regexp.options and Regexp.new */
4823 rb_define_const(rb_cRegexp, "EXTENDED", INT2FIX(ONIG_OPTION_EXTEND));
4824 /* see Regexp.options and Regexp.new */
4825 rb_define_const(rb_cRegexp, "MULTILINE", INT2FIX(ONIG_OPTION_MULTILINE));
4826 /* see Regexp.options and Regexp.new */
4827 rb_define_const(rb_cRegexp, "FIXEDENCODING", INT2FIX(ARG_ENCODING_FIXED));
4828 /* see Regexp.options and Regexp.new */
4829 rb_define_const(rb_cRegexp, "NOENCODING", INT2FIX(ARG_ENCODING_NONE));
4830
4831 rb_global_variable(&reg_cache);
4832
4833 rb_cMatch = rb_define_class("MatchData", rb_cObject);
4834 rb_define_alloc_func(rb_cMatch, match_alloc);
4836 rb_undef_method(CLASS_OF(rb_cMatch), "allocate");
4837
4838 rb_define_method(rb_cMatch, "initialize_copy", match_init_copy, 1);
4839 rb_define_method(rb_cMatch, "regexp", match_regexp, 0);
4840 rb_define_method(rb_cMatch, "names", match_names, 0);
4841 rb_define_method(rb_cMatch, "size", match_size, 0);
4842 rb_define_method(rb_cMatch, "length", match_size, 0);
4843 rb_define_method(rb_cMatch, "offset", match_offset, 1);
4844 rb_define_method(rb_cMatch, "byteoffset", match_byteoffset, 1);
4845 rb_define_method(rb_cMatch, "begin", match_begin, 1);
4846 rb_define_method(rb_cMatch, "end", match_end, 1);
4847 rb_define_method(rb_cMatch, "match", match_nth, 1);
4848 rb_define_method(rb_cMatch, "match_length", match_nth_length, 1);
4849 rb_define_method(rb_cMatch, "to_a", match_to_a, 0);
4850 rb_define_method(rb_cMatch, "[]", match_aref, -1);
4851 rb_define_method(rb_cMatch, "captures", match_captures, 0);
4852 rb_define_alias(rb_cMatch, "deconstruct", "captures");
4853 rb_define_method(rb_cMatch, "named_captures", match_named_captures, -1);
4854 rb_define_method(rb_cMatch, "deconstruct_keys", match_deconstruct_keys, 1);
4855 rb_define_method(rb_cMatch, "values_at", match_values_at, -1);
4856 rb_define_method(rb_cMatch, "pre_match", rb_reg_match_pre, 0);
4857 rb_define_method(rb_cMatch, "post_match", rb_reg_match_post, 0);
4858 rb_define_method(rb_cMatch, "to_s", match_to_s, 0);
4859 rb_define_method(rb_cMatch, "inspect", match_inspect, 0);
4860 rb_define_method(rb_cMatch, "string", match_string, 0);
4861 rb_define_method(rb_cMatch, "hash", match_hash, 0);
4862 rb_define_method(rb_cMatch, "eql?", match_equal, 1);
4863 rb_define_method(rb_cMatch, "==", match_equal, 1);
4864}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
static bool rb_enc_isprint(OnigCodePoint c, rb_encoding *enc)
Identical to rb_isprint(), except it additionally takes an encoding.
Definition ctype.h:180
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:970
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1002
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2336
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2160
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.
Definition class.c:2626
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:866
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2415
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1675
#define NEWOBJ_OF
Old name of RB_NEWOBJ_OF.
Definition newobj.h:61
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
Definition coderange.h:180
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1682
#define REALLOC_N
Old name of RB_REALLOC_N.
Definition memory.h:397
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define ISSPACE
Old name of rb_isspace.
Definition ctype.h:88
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define ENC_CODERANGE_CLEAN_P(cr)
Old name of RB_ENC_CODERANGE_CLEAN_P.
Definition coderange.h:183
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition string.h:1679
#define ENC_CODERANGE(obj)
Old name of RB_ENC_CODERANGE.
Definition coderange.h:184
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:203
#define ENC_CODERANGE_UNKNOWN
Old name of RUBY_ENC_CODERANGE_UNKNOWN.
Definition coderange.h:179
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
Definition encoding.h:108
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define rb_str_new3
Old name of rb_str_new_shared.
Definition string.h:1676
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
Definition encoding.h:516
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:132
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:129
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition error.h:38
#define MBCLEN_INVALID_P(ret)
Old name of ONIGENC_MBCLEN_INVALID_P.
Definition encoding.h:517
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define MBCLEN_NEEDMORE_P(ret)
Old name of ONIGENC_MBCLEN_NEEDMORE_P.
Definition encoding.h:518
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#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.
Definition coderange.h:182
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define scan_hex(s, l, e)
Old name of ruby_scan_hex.
Definition util.h:108
#define NIL_P
Old name of RB_NIL_P.
#define MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
Definition encoding.h:515
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define T_MATCH
Old name of RUBY_T_MATCH.
Definition value_type.h:69
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:131
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:133
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define scan_oct(s, l, e)
Old name of ruby_scan_oct.
Definition util.h:85
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:651
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:130
#define rb_str_new4
Old name of rb_str_new_frozen.
Definition string.h:1677
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define T_REGEXP
Old name of RUBY_T_REGEXP.
Definition value_type.h:77
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:433
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1341
VALUE rb_eRegexpError
RegexpError exception.
Definition re.c:32
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:471
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1344
VALUE rb_eEncCompatError
Encoding::CompatibilityError exception.
Definition error.c:1351
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1342
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:423
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1346
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_check_convert_type(VALUE val, int type, const char *name, const char *mid)
Identical to rb_convert_type(), except it returns RUBY_Qnil instead of raising exceptions,...
Definition object.c:3080
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:634
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2099
VALUE rb_cMatch
MatchData class.
Definition re.c:967
VALUE rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
Identical to rb_class_new_instance(), except it passes the passed keywords if any to the #initialize ...
Definition object.c:2076
VALUE rb_cRegexp
Regexp class.
Definition re.c:2619
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:215
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:619
Encoding relates APIs.
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.
Definition encoding.h:682
static int rb_enc_mbmaxlen(rb_encoding *enc)
Queries the maximum number of bytes that the passed encoding needs to represent a character.
Definition encoding.h:446
static OnigCodePoint rb_enc_mbc_to_codepoint(const char *p, const char *e, rb_encoding *enc)
Identical to rb_enc_codepoint(), except it assumes the passed character is not broken.
Definition encoding.h:590
static int rb_enc_mbminlen(rb_encoding *enc)
Queries the minimum number of bytes that the passed encoding needs to represent a character.
Definition encoding.h:431
VALUE rb_enc_reg_new(const char *ptr, long len, rb_encoding *enc, int opts)
Identical to rb_reg_new(), except it additionally takes an encoding.
Definition re.c:3421
int rb_enc_str_coderange(VALUE str)
Scans the passed string to collect its code range.
Definition string.c:769
long rb_memsearch(const void *x, long m, const void *y, long n, rb_encoding *enc)
Looks for the passed string in the passed buffer.
Definition re.c:252
long 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.
Definition string.c:2106
int rb_enc_str_asciionly_p(VALUE str)
Queries if the passed string is "ASCII only".
Definition string.c:781
long rb_str_coderange_scan_restartable(const char *str, const char *end, rb_encoding *enc, int *cr)
Scans the passed string until it finds something odd.
Definition string.c:653
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.
Definition transcode.c:2914
#define RGENGC_WB_PROTECTED_MATCH
This is a compile-time flag to enable/disable write barrier for struct RMatch.
Definition gc.h:528
#define RGENGC_WB_PROTECTED_REGEXP
This is a compile-time flag to enable/disable write barrier for struct RRegexp.
Definition gc.h:517
int rb_uv_to_utf8(char buf[6], unsigned long uv)
Encodes a Unicode codepoint into its UTF-8 representation.
Definition pack.c:1627
#define rb_check_frozen
Just another name of rb_check_frozen
Definition error.h:264
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:280
VALUE rb_backref_get(void)
Queries the last match, or Regexp.last_match, or the $~.
Definition vm.c:1793
VALUE rb_lastline_get(void)
Queries the last line, or the $_.
Definition vm.c:1805
void rb_backref_set(VALUE md)
Updates $~.
Definition vm.c:1799
VALUE rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
Deconstructs a numerical range.
Definition range.c:1744
int rb_reg_backref_number(VALUE match, VALUE backref)
Queries the index of the given named capture.
Definition re.c:1235
int rb_reg_options(VALUE re)
Queries the options of the passed regular expression.
Definition re.c:4177
VALUE rb_reg_last_match(VALUE md)
This just returns the argument, stringified.
Definition re.c:1909
VALUE rb_reg_match(VALUE re, VALUE str)
This is the match operator.
Definition re.c:3674
void rb_match_busy(VALUE md)
Asserts that the given MatchData is "occupied".
Definition re.c:1441
VALUE rb_reg_nth_match(int n, VALUE md)
Queries the nth captured substring.
Definition re.c:1884
VALUE rb_reg_match_post(VALUE md)
The portion of the original string after the given match.
Definition re.c:1966
VALUE rb_reg_nth_defined(int n, VALUE md)
Identical to rb_reg_nth_match(), except it just returns Boolean.
Definition re.c:1867
VALUE rb_reg_match_pre(VALUE md)
The portion of the original string before the given match.
Definition re.c:1933
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.
Definition re.c:3381
VALUE rb_reg_match_last(VALUE md)
The portion of the original string that captured at the very last.
Definition re.c:1999
VALUE rb_reg_match2(VALUE re)
Identical to rb_reg_match(), except it matches against rb_lastline_get() (or, the $_).
Definition re.c:3729
VALUE rb_reg_new(const char *src, long len, int opts)
Creates a new Regular expression.
Definition re.c:3435
#define rb_hash_uint(h, i)
Just another name of st_hash_uint
Definition string.h:942
#define rb_hash_end(h)
Just another name of st_hash_end
Definition string.h:945
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3414
long rb_str_offset(VALUE str, long pos)
"Inverse" of rb_str_sublen().
Definition string.c:2790
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
Definition random.c:1747
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1498
#define rb_str_buf_cat
Just another name of rb_str_cat
Definition string.h:1681
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
Definition string.c:3623
char * rb_str_subpos(VALUE str, long beg, long *len)
Identical to rb_str_substr(), except it returns a C's string instead of Ruby's.
Definition string.c:2895
long rb_str_sublen(VALUE str, long pos)
Byte offset to character offset conversion.
Definition string.c:2837
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
Definition string.c:3736
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1741
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:6781
VALUE rb_str_buf_cat_ascii(VALUE dst, const char *src)
Identical to rb_str_cat_cstr(), except it additionally assumes the source string be a NUL terminated ...
Definition string.c:3356
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2686
VALUE rb_str_length(VALUE)
Identical to rb_str_strlen(), except it returns the value in rb_cInteger.
Definition string.c:2209
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:283
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:276
VALUE rb_sym2str(VALUE id)
Identical to rb_id2str(), except it takes an instance of rb_cSymbol rather than an ID.
Definition symbol.c:953
void rb_define_const(VALUE klass, const char *name, VALUE val)
Defines a Ruby level constant under a namespace.
Definition variable.c:3690
int len
Length of the buffer.
Definition io.h:8
long rb_reg_search(VALUE re, VALUE str, long pos, int dir)
Runs the passed regular expression over the passed string.
Definition re.c:1823
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 ...
Definition re.c:1587
long rb_reg_adjust_startpos(VALUE re, VALUE str, long pos, int dir)
Tell us if this is a wrong idea, but it seems this function has no usage at all.
Definition re.c:1685
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.
Definition re.c:1655
VALUE rb_reg_regcomp(VALUE str)
Creates a new instance of rb_cRegexp.
Definition re.c:3458
VALUE rb_reg_quote(VALUE str)
Escapes any characters that would have special meaning in a regular expression.
Definition re.c:4057
VALUE rb_reg_regsub(VALUE repl, VALUE src, struct re_registers *regs, VALUE rexp)
Substitution.
Definition re.c:4421
int rb_reg_region_copy(struct re_registers *dst, const struct re_registers *src)
Duplicates a match data.
Definition re.c:984
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1376
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:366
#define ALLOCA_N(type, n)
Definition memory.h:286
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:354
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:161
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
#define RARRAY_LEN
Just another name of rb_array_len
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RMATCH(obj)
Convenient casting macro.
Definition rmatch.h:37
static struct re_registers * RMATCH_REGS(VALUE match)
Queries the raw re_registers.
Definition rmatch.h:138
#define RREGEXP(obj)
Convenient casting macro.
Definition rregexp.h:37
static VALUE RREGEXP_SRC(VALUE rexp)
Convenient getter function.
Definition rregexp.h:103
#define RREGEXP_PTR(obj)
Convenient accessor macro.
Definition rregexp.h:45
static long RREGEXP_SRC_LEN(VALUE rexp)
Convenient getter function.
Definition rregexp.h:144
static char * RREGEXP_SRC_PTR(VALUE rexp)
Convenient getter function.
Definition rregexp.h:125
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:488
VALUE rb_str_to_str(VALUE obj)
Identical to rb_check_string_type(), except it raises exceptions in case of conversion failures.
Definition string.c:1576
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
MEMO.
Definition imemo.h:103
VALUE flags
Per-object flags.
Definition rbasic.h:77
Regular expression execution context.
Definition rmatch.h:96
VALUE regexp
The expression of this match.
Definition rmatch.h:109
VALUE str
The target string that the match was made against.
Definition rmatch.h:104
Ruby's regular expression.
Definition rregexp.h:60
struct RBasic basic
Basic part, including flags and class.
Definition rregexp.h:63
const VALUE src
Source code of this expression.
Definition rregexp.h:74
unsigned long usecnt
Reference count.
Definition rregexp.h:90
struct re_pattern_buffer * ptr
The pattern buffer.
Definition rregexp.h:71
Definition re.c:994
Represents a match.
Definition rmatch.h:71
struct rmatch_offset * char_offset
Capture group offsets, in C array.
Definition rmatch.h:79
int char_offset_num_allocated
Number of rmatch_offset that rmatch::char_offset holds.
Definition rmatch.h:82
struct re_registers regs
"Registers" of a match.
Definition rmatch.h:76
Represents the region of a capture group.
Definition rmatch.h:65
long beg
Beginning of a group.
Definition rmatch.h:66
long end
End of a group.
Definition rmatch.h:67
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:432