Ruby  2.5.0dev(2017-10-22revision60238)
re.c
Go to the documentation of this file.
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 "internal.h"
13 #include "ruby/re.h"
14 #include "ruby/util.h"
15 #include "regint.h"
16 #include "encindex.h"
17 #include <ctype.h>
18 
20 
22 #define errcpy(err, msg) strlcpy((err), (msg), ONIG_MAX_ERROR_MESSAGE_LEN)
23 
24 #define BEG(no) (regs->beg[(no)])
25 #define END(no) (regs->end[(no)])
26 
27 #if 'a' == 97 /* it's ascii */
28 static const char casetable[] = {
29  '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
30  '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
31  '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
32  '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
33  /* ' ' '!' '"' '#' '$' '%' '&' ''' */
34  '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
35  /* '(' ')' '*' '+' ',' '-' '.' '/' */
36  '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
37  /* '0' '1' '2' '3' '4' '5' '6' '7' */
38  '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
39  /* '8' '9' ':' ';' '<' '=' '>' '?' */
40  '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
41  /* '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' */
42  '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
43  /* 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' */
44  '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
45  /* 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' */
46  '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
47  /* 'X' 'Y' 'Z' '[' '\' ']' '^' '_' */
48  '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
49  /* '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' */
50  '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
51  /* 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' */
52  '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
53  /* 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' */
54  '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
55  /* 'x' 'y' 'z' '{' '|' '}' '~' */
56  '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
57  '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
58  '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
59  '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
60  '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
61  '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
62  '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
63  '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
64  '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
65  '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
66  '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
67  '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
68  '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
69  '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
70  '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
71  '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
72  '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
73 };
74 #else
75 # error >>> "You lose. You will need a translation table for your character set." <<<
76 #endif
77 
78 int
79 rb_memcicmp(const void *x, const void *y, long len)
80 {
81  const unsigned char *p1 = x, *p2 = y;
82  int tmp;
83 
84  while (len--) {
85  if ((tmp = casetable[(unsigned)*p1++] - casetable[(unsigned)*p2++]))
86  return tmp;
87  }
88  return 0;
89 }
90 
91 #ifdef HAVE_MEMMEM
92 static inline long
93 rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n)
94 {
95  const unsigned char *y;
96 
97  if (y = memmem(ys, n, xs, m))
98  return y - ys;
99  else
100  return -1;
101 }
102 #else
103 static inline long
104 rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n)
105 {
106  const unsigned char *x = xs, *xe = xs + m;
107  const unsigned char *y = ys, *ye = ys + n;
108 #ifndef VALUE_MAX
109 # if SIZEOF_VALUE == 8
110 # define VALUE_MAX 0xFFFFFFFFFFFFFFFFULL
111 # elif SIZEOF_VALUE == 4
112 # define VALUE_MAX 0xFFFFFFFFUL
113 # endif
114 #endif
115  VALUE hx, hy, mask = VALUE_MAX >> ((SIZEOF_VALUE - m) * CHAR_BIT);
116 
117  if (m > SIZEOF_VALUE)
118  rb_bug("!!too long pattern string!!");
119 
120  if (!(y = memchr(y, *x, n - m + 1)))
121  return -1;
122 
123  /* Prepare hash value */
124  for (hx = *x++, hy = *y++; x < xe; ++x, ++y) {
125  hx <<= CHAR_BIT;
126  hy <<= CHAR_BIT;
127  hx |= *x;
128  hy |= *y;
129  }
130  /* Searching */
131  while (hx != hy) {
132  if (y == ye)
133  return -1;
134  hy <<= CHAR_BIT;
135  hy |= *y;
136  hy &= mask;
137  y++;
138  }
139  return y - ys - m;
140 }
141 #endif
142 
143 static inline long
144 rb_memsearch_qs(const unsigned char *xs, long m, const unsigned char *ys, long n)
145 {
146  const unsigned char *x = xs, *xe = xs + m;
147  const unsigned char *y = ys;
148  VALUE i, qstable[256];
149 
150  /* Preprocessing */
151  for (i = 0; i < 256; ++i)
152  qstable[i] = m + 1;
153  for (; x < xe; ++x)
154  qstable[*x] = xe - x;
155  /* Searching */
156  for (; y + m <= ys + n; y += *(qstable + y[m])) {
157  if (*xs == *y && memcmp(xs, y, m) == 0)
158  return y - ys;
159  }
160  return -1;
161 }
162 
163 static inline unsigned int
164 rb_memsearch_qs_utf8_hash(const unsigned char *x)
165 {
166  register const unsigned int mix = 8353;
167  register unsigned int h = *x;
168  if (h < 0xC0) {
169  return h + 256;
170  }
171  else if (h < 0xE0) {
172  h *= mix;
173  h += x[1];
174  }
175  else if (h < 0xF0) {
176  h *= mix;
177  h += x[1];
178  h *= mix;
179  h += x[2];
180  }
181  else if (h < 0xF5) {
182  h *= mix;
183  h += x[1];
184  h *= mix;
185  h += x[2];
186  h *= mix;
187  h += x[3];
188  }
189  else {
190  return h + 256;
191  }
192  return (unsigned char)h;
193 }
194 
195 static inline long
196 rb_memsearch_qs_utf8(const unsigned char *xs, long m, const unsigned char *ys, long n)
197 {
198  const unsigned char *x = xs, *xe = xs + m;
199  const unsigned char *y = ys;
200  VALUE i, qstable[512];
201 
202  /* Preprocessing */
203  for (i = 0; i < 512; ++i) {
204  qstable[i] = m + 1;
205  }
206  for (; x < xe; ++x) {
207  qstable[rb_memsearch_qs_utf8_hash(x)] = xe - x;
208  }
209  /* Searching */
210  for (; y + m <= ys + n; y += qstable[rb_memsearch_qs_utf8_hash(y+m)]) {
211  if (*xs == *y && memcmp(xs, y, m) == 0)
212  return y - ys;
213  }
214  return -1;
215 }
216 
217 static inline long
218 rb_memsearch_wchar(const unsigned char *xs, long m, const unsigned char *ys, long n)
219 {
220  const unsigned char *x = xs, x0 = *xs, *y = ys;
221  enum {char_size = 2};
222 
223  for (n -= m; n >= 0; n -= char_size, y += char_size) {
224  if (x0 == *y && memcmp(x+1, y+1, m-1) == 0)
225  return y - ys;
226  }
227  return -1;
228 }
229 
230 static inline long
231 rb_memsearch_qchar(const unsigned char *xs, long m, const unsigned char *ys, long n)
232 {
233  const unsigned char *x = xs, x0 = *xs, *y = ys;
234  enum {char_size = 4};
235 
236  for (n -= m; n >= 0; n -= char_size, y += char_size) {
237  if (x0 == *y && memcmp(x+1, y+1, m-1) == 0)
238  return y - ys;
239  }
240  return -1;
241 }
242 
243 long
244 rb_memsearch(const void *x0, long m, const void *y0, long n, rb_encoding *enc)
245 {
246  const unsigned char *x = x0, *y = y0;
247 
248  if (m > n) return -1;
249  else if (m == n) {
250  return memcmp(x0, y0, m) == 0 ? 0 : -1;
251  }
252  else if (m < 1) {
253  return 0;
254  }
255  else if (m == 1) {
256  const unsigned char *ys = memchr(y, *x, n);
257 
258  if (ys)
259  return ys - y;
260  else
261  return -1;
262  }
263  else if (LIKELY(rb_enc_mbminlen(enc) == 1)) {
264  if (m <= SIZEOF_VALUE) {
265  return rb_memsearch_ss(x0, m, y0, n);
266  }
267  else if (enc == rb_utf8_encoding()){
268  return rb_memsearch_qs_utf8(x0, m, y0, n);
269  }
270  }
271  else if (LIKELY(rb_enc_mbminlen(enc) == 2)) {
272  return rb_memsearch_wchar(x0, m, y0, n);
273  }
274  else if (LIKELY(rb_enc_mbminlen(enc) == 4)) {
275  return rb_memsearch_qchar(x0, m, y0, n);
276  }
277  return rb_memsearch_qs(x0, m, y0, n);
278 }
279 
280 #define REG_LITERAL FL_USER5
281 #define REG_ENCODING_NONE FL_USER6
282 
283 #define KCODE_FIXED FL_USER4
284 
285 #define ARG_REG_OPTION_MASK \
286  (ONIG_OPTION_IGNORECASE|ONIG_OPTION_MULTILINE|ONIG_OPTION_EXTEND)
287 #define ARG_ENCODING_FIXED 16
288 #define ARG_ENCODING_NONE 32
289 
290 static int
291 char_to_option(int c)
292 {
293  int val;
294 
295  switch (c) {
296  case 'i':
298  break;
299  case 'x':
300  val = ONIG_OPTION_EXTEND;
301  break;
302  case 'm':
303  val = ONIG_OPTION_MULTILINE;
304  break;
305  default:
306  val = 0;
307  break;
308  }
309  return val;
310 }
311 
312 static char *
313 option_to_str(char str[4], int options)
314 {
315  char *p = str;
316  if (options & ONIG_OPTION_MULTILINE) *p++ = 'm';
317  if (options & ONIG_OPTION_IGNORECASE) *p++ = 'i';
318  if (options & ONIG_OPTION_EXTEND) *p++ = 'x';
319  *p = 0;
320  return str;
321 }
322 
323 extern int
324 rb_char_to_option_kcode(int c, int *option, int *kcode)
325 {
326  *option = 0;
327 
328  switch (c) {
329  case 'n':
330  *kcode = rb_ascii8bit_encindex();
331  return (*option = ARG_ENCODING_NONE);
332  case 'e':
333  *kcode = ENCINDEX_EUC_JP;
334  break;
335  case 's':
336  *kcode = ENCINDEX_Windows_31J;
337  break;
338  case 'u':
339  *kcode = rb_utf8_encindex();
340  break;
341  default:
342  *kcode = -1;
343  return (*option = char_to_option(c));
344  }
345  *option = ARG_ENCODING_FIXED;
346  return 1;
347 }
348 
349 static void
350 rb_reg_check(VALUE re)
351 {
352  if (!RREGEXP_PTR(re) || !RREGEXP_SRC(re) || !RREGEXP_SRC_PTR(re)) {
353  rb_raise(rb_eTypeError, "uninitialized Regexp");
354  }
355 }
356 
357 static void
358 rb_reg_expr_str(VALUE str, const char *s, long len,
359  rb_encoding *enc, rb_encoding *resenc)
360 {
361  const char *p, *pend;
362  int cr = ENC_CODERANGE_UNKNOWN;
363  int need_escape = 0;
364  int c, clen;
365 
366  p = s; pend = p + len;
367  rb_str_coderange_scan_restartable(p, pend, enc, &cr);
368  if (rb_enc_asciicompat(enc) && ENC_CODERANGE_CLEAN_P(cr)) {
369  while (p < pend) {
370  c = rb_enc_ascget(p, pend, &clen, enc);
371  if (c == -1) {
372  if (enc == resenc) {
373  p += mbclen(p, pend, enc);
374  }
375  else {
376  need_escape = 1;
377  break;
378  }
379  }
380  else if (c != '/' && rb_enc_isprint(c, enc)) {
381  p += clen;
382  }
383  else {
384  need_escape = 1;
385  break;
386  }
387  }
388  }
389  else {
390  need_escape = 1;
391  }
392 
393  if (!need_escape) {
394  rb_str_buf_cat(str, s, len);
395  }
396  else {
397  int unicode_p = rb_enc_unicode_p(enc);
398  p = s;
399  while (p<pend) {
400  c = rb_enc_ascget(p, pend, &clen, enc);
401  if (c == '\\' && p+clen < pend) {
402  int n = clen + mbclen(p+clen, pend, enc);
403  rb_str_buf_cat(str, p, n);
404  p += n;
405  continue;
406  }
407  else if (c == '/') {
408  char c = '\\';
409  rb_str_buf_cat(str, &c, 1);
410  rb_str_buf_cat(str, p, clen);
411  }
412  else if (c == -1) {
413  clen = rb_enc_precise_mbclen(p, pend, enc);
414  if (!MBCLEN_CHARFOUND_P(clen)) {
415  c = (unsigned char)*p;
416  clen = 1;
417  goto hex;
418  }
419  if (resenc) {
420  unsigned int c = rb_enc_mbc_to_codepoint(p, pend, enc);
421  rb_str_buf_cat_escaped_char(str, c, unicode_p);
422  }
423  else {
424  clen = MBCLEN_CHARFOUND_LEN(clen);
425  rb_str_buf_cat(str, p, clen);
426  }
427  }
428  else if (rb_enc_isprint(c, enc)) {
429  rb_str_buf_cat(str, p, clen);
430  }
431  else if (!rb_enc_isspace(c, enc)) {
432  char b[8];
433 
434  hex:
435  snprintf(b, sizeof(b), "\\x%02X", c);
436  rb_str_buf_cat(str, b, 4);
437  }
438  else {
439  rb_str_buf_cat(str, p, clen);
440  }
441  p += clen;
442  }
443  }
444 }
445 
446 static VALUE
447 rb_reg_desc(const char *s, long len, VALUE re)
448 {
449  rb_encoding *enc = rb_enc_get(re);
450  VALUE str = rb_str_buf_new2("/");
452  if (resenc == NULL) resenc = rb_default_external_encoding();
453 
454  if (re && rb_enc_asciicompat(enc)) {
455  rb_enc_copy(str, re);
456  }
457  else {
459  }
460  rb_reg_expr_str(str, s, len, enc, resenc);
461  rb_str_buf_cat2(str, "/");
462  if (re) {
463  char opts[4];
464  rb_reg_check(re);
465  if (*option_to_str(opts, RREGEXP_PTR(re)->options))
466  rb_str_buf_cat2(str, opts);
467  if (RBASIC(re)->flags & REG_ENCODING_NONE)
468  rb_str_buf_cat2(str, "n");
469  }
470  OBJ_INFECT(str, re);
471  return str;
472 }
473 
474 
475 /*
476  * call-seq:
477  * rxp.source -> str
478  *
479  * Returns the original string of the pattern.
480  *
481  * /ab+c/ix.source #=> "ab+c"
482  *
483  * Note that escape sequences are retained as is.
484  *
485  * /\x20\+/.source #=> "\\x20\\+"
486  *
487  */
488 
489 static VALUE
490 rb_reg_source(VALUE re)
491 {
492  VALUE str;
493 
494  rb_reg_check(re);
495  str = rb_str_dup(RREGEXP_SRC(re));
496  if (OBJ_TAINTED(re)) OBJ_TAINT(str);
497  return str;
498 }
499 
500 /*
501  * call-seq:
502  * rxp.inspect -> string
503  *
504  * Produce a nicely formatted string-version of _rxp_. Perhaps surprisingly,
505  * <code>#inspect</code> actually produces the more natural version of
506  * the string than <code>#to_s</code>.
507  *
508  * /ab+c/ix.inspect #=> "/ab+c/ix"
509  *
510  */
511 
512 static VALUE
513 rb_reg_inspect(VALUE re)
514 {
515  if (!RREGEXP_PTR(re) || !RREGEXP_SRC(re) || !RREGEXP_SRC_PTR(re)) {
516  return rb_any_to_s(re);
517  }
518  return rb_reg_desc(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), re);
519 }
520 
521 
522 /*
523  * call-seq:
524  * rxp.to_s -> str
525  *
526  * Returns a string containing the regular expression and its options (using the
527  * <code>(?opts:source)</code> notation. This string can be fed back in to
528  * <code>Regexp::new</code> to a regular expression with the same semantics as
529  * the original. (However, <code>Regexp#==</code> may not return true when
530  * comparing the two, as the source of the regular expression itself may
531  * differ, as the example shows). <code>Regexp#inspect</code> produces a
532  * generally more readable version of <i>rxp</i>.
533  *
534  * r1 = /ab+c/ix #=> /ab+c/ix
535  * s1 = r1.to_s #=> "(?ix-m:ab+c)"
536  * r2 = Regexp.new(s1) #=> /(?ix-m:ab+c)/
537  * r1 == r2 #=> false
538  * r1.source #=> "ab+c"
539  * r2.source #=> "(?ix-m:ab+c)"
540  */
541 
542 static VALUE
543 rb_reg_to_s(VALUE re)
544 {
545  int options, opt;
547  long len;
548  const UChar* ptr;
549  VALUE str = rb_str_buf_new2("(?");
550  char optbuf[5];
551  rb_encoding *enc = rb_enc_get(re);
552 
553  rb_reg_check(re);
554 
555  rb_enc_copy(str, re);
556  options = RREGEXP_PTR(re)->options;
557  ptr = (UChar*)RREGEXP_SRC_PTR(re);
558  len = RREGEXP_SRC_LEN(re);
559  again:
560  if (len >= 4 && ptr[0] == '(' && ptr[1] == '?') {
561  int err = 1;
562  ptr += 2;
563  if ((len -= 2) > 0) {
564  do {
565  opt = char_to_option((int )*ptr);
566  if (opt != 0) {
567  options |= opt;
568  }
569  else {
570  break;
571  }
572  ++ptr;
573  } while (--len > 0);
574  }
575  if (len > 1 && *ptr == '-') {
576  ++ptr;
577  --len;
578  do {
579  opt = char_to_option((int )*ptr);
580  if (opt != 0) {
581  options &= ~opt;
582  }
583  else {
584  break;
585  }
586  ++ptr;
587  } while (--len > 0);
588  }
589  if (*ptr == ')') {
590  --len;
591  ++ptr;
592  goto again;
593  }
594  if (*ptr == ':' && ptr[len-1] == ')') {
595  Regexp *rp;
596  VALUE verbose = ruby_verbose;
598 
599  ++ptr;
600  len -= 2;
601  err = onig_new(&rp, ptr, ptr + len, options,
602  enc, OnigDefaultSyntax, NULL);
603  onig_free(rp);
604  ruby_verbose = verbose;
605  }
606  if (err) {
607  options = RREGEXP_PTR(re)->options;
608  ptr = (UChar*)RREGEXP_SRC_PTR(re);
609  len = RREGEXP_SRC_LEN(re);
610  }
611  }
612 
613  if (*option_to_str(optbuf, options)) rb_str_buf_cat2(str, optbuf);
614 
615  if ((options & embeddable) != embeddable) {
616  optbuf[0] = '-';
617  option_to_str(optbuf + 1, ~options);
618  rb_str_buf_cat2(str, optbuf);
619  }
620 
621  rb_str_buf_cat2(str, ":");
622  if (rb_enc_asciicompat(enc)) {
623  rb_reg_expr_str(str, (char*)ptr, len, enc, NULL);
624  rb_str_buf_cat2(str, ")");
625  }
626  else {
627  const char *s, *e;
628  char *paren;
629  ptrdiff_t n;
630  rb_str_buf_cat2(str, ")");
632  str = rb_str_encode(str, rb_enc_from_encoding(enc), 0, Qnil);
633 
634  /* backup encoded ")" to paren */
635  s = RSTRING_PTR(str);
636  e = RSTRING_END(str);
637  s = rb_enc_left_char_head(s, e-1, e, enc);
638  n = e - s;
639  paren = ALLOCA_N(char, n);
640  memcpy(paren, s, n);
641  rb_str_resize(str, RSTRING_LEN(str) - n);
642 
643  rb_reg_expr_str(str, (char*)ptr, len, enc, NULL);
644  rb_str_buf_cat(str, paren, n);
645  }
646  rb_enc_copy(str, re);
647 
648  OBJ_INFECT(str, re);
649  return str;
650 }
651 
652 static void
653 rb_reg_raise(const char *s, long len, const char *err, VALUE re)
654 {
655  VALUE desc = rb_reg_desc(s, len, re);
656 
657  rb_raise(rb_eRegexpError, "%s: %"PRIsVALUE, err, desc);
658 }
659 
660 static VALUE
661 rb_enc_reg_error_desc(const char *s, long len, rb_encoding *enc, int options, const char *err)
662 {
663  char opts[6];
664  VALUE desc = rb_str_buf_new2(err);
666  if (resenc == NULL) resenc = rb_default_external_encoding();
667 
668  rb_enc_associate(desc, enc);
669  rb_str_buf_cat2(desc, ": /");
670  rb_reg_expr_str(desc, s, len, enc, resenc);
671  opts[0] = '/';
672  option_to_str(opts + 1, options);
673  rb_str_buf_cat2(desc, opts);
674  return rb_exc_new3(rb_eRegexpError, desc);
675 }
676 
677 static void
678 rb_enc_reg_raise(const char *s, long len, rb_encoding *enc, int options, const char *err)
679 {
680  rb_exc_raise(rb_enc_reg_error_desc(s, len, enc, options, err));
681 }
682 
683 static VALUE
684 rb_reg_error_desc(VALUE str, int options, const char *err)
685 {
686  return rb_enc_reg_error_desc(RSTRING_PTR(str), RSTRING_LEN(str),
687  rb_enc_get(str), options, err);
688 }
689 
690 static void
691 rb_reg_raise_str(VALUE str, int options, const char *err)
692 {
693  rb_exc_raise(rb_reg_error_desc(str, options, err));
694 }
695 
696 
697 /*
698  * call-seq:
699  * rxp.casefold? -> true or false
700  *
701  * Returns the value of the case-insensitive flag.
702  *
703  * /a/.casefold? #=> false
704  * /a/i.casefold? #=> true
705  * /(?i:a)/.casefold? #=> false
706  */
707 
708 static VALUE
709 rb_reg_casefold_p(VALUE re)
710 {
711  rb_reg_check(re);
712  if (RREGEXP_PTR(re)->options & ONIG_OPTION_IGNORECASE) return Qtrue;
713  return Qfalse;
714 }
715 
716 
717 /*
718  * call-seq:
719  * rxp.options -> integer
720  *
721  * Returns the set of bits corresponding to the options used when creating this
722  * Regexp (see <code>Regexp::new</code> for details. Note that additional bits
723  * may be set in the returned options: these are used internally by the regular
724  * expression code. These extra bits are ignored if the options are passed to
725  * <code>Regexp::new</code>.
726  *
727  * Regexp::IGNORECASE #=> 1
728  * Regexp::EXTENDED #=> 2
729  * Regexp::MULTILINE #=> 4
730  *
731  * /cat/.options #=> 0
732  * /cat/ix.options #=> 3
733  * Regexp.new('cat', true).options #=> 1
734  * /\xa1\xa2/e.options #=> 16
735  *
736  * r = /cat/ix
737  * Regexp.new(r.source, r.options) #=> /cat/ix
738  */
739 
740 static VALUE
741 rb_reg_options_m(VALUE re)
742 {
743  int options = rb_reg_options(re);
744  return INT2NUM(options);
745 }
746 
747 static int
748 reg_names_iter(const OnigUChar *name, const OnigUChar *name_end,
749  int back_num, int *back_refs, OnigRegex regex, void *arg)
750 {
751  VALUE ary = (VALUE)arg;
752  rb_ary_push(ary, rb_enc_str_new((const char *)name, name_end-name, regex->enc));
753  return 0;
754 }
755 
756 /*
757  * call-seq:
758  * rxp.names -> [name1, name2, ...]
759  *
760  * Returns a list of names of captures as an array of strings.
761  *
762  * /(?<foo>.)(?<bar>.)(?<baz>.)/.names
763  * #=> ["foo", "bar", "baz"]
764  *
765  * /(?<foo>.)(?<foo>.)/.names
766  * #=> ["foo"]
767  *
768  * /(.)(.)/.names
769  * #=> []
770  */
771 
772 static VALUE
773 rb_reg_names(VALUE re)
774 {
775  VALUE ary;
776  rb_reg_check(re);
778  onig_foreach_name(RREGEXP_PTR(re), reg_names_iter, (void*)ary);
779  return ary;
780 }
781 
782 static int
783 reg_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end,
784  int back_num, int *back_refs, OnigRegex regex, void *arg)
785 {
786  VALUE hash = (VALUE)arg;
787  VALUE ary = rb_ary_new2(back_num);
788  int i;
789 
790  for (i = 0; i < back_num; i++)
791  rb_ary_store(ary, i, INT2NUM(back_refs[i]));
792 
793  rb_hash_aset(hash, rb_str_new((const char*)name, name_end-name),ary);
794 
795  return 0;
796 }
797 
798 /*
799  * call-seq:
800  * rxp.named_captures -> hash
801  *
802  * Returns a hash representing information about named captures of <i>rxp</i>.
803  *
804  * A key of the hash is a name of the named captures.
805  * A value of the hash is an array which is list of indexes of corresponding
806  * named captures.
807  *
808  * /(?<foo>.)(?<bar>.)/.named_captures
809  * #=> {"foo"=>[1], "bar"=>[2]}
810  *
811  * /(?<foo>.)(?<foo>.)/.named_captures
812  * #=> {"foo"=>[1, 2]}
813  *
814  * If there are no named captures, an empty hash is returned.
815  *
816  * /(.)(.)/.named_captures
817  * #=> {}
818  */
819 
820 static VALUE
821 rb_reg_named_captures(VALUE re)
822 {
823  regex_t *reg = (rb_reg_check(re), RREGEXP_PTR(re));
825  onig_foreach_name(reg, reg_named_captures_iter, (void*)hash);
826  return hash;
827 }
828 
829 static int
830 onig_new_with_source(regex_t** reg, const UChar* pattern, const UChar* pattern_end,
831  OnigOptionType option, OnigEncoding enc, const OnigSyntaxType* syntax,
832  OnigErrorInfo* einfo, const char *sourcefile, int sourceline)
833 {
834  int r;
835 
836  *reg = (regex_t* )malloc(sizeof(regex_t));
837  if (IS_NULL(*reg)) return ONIGERR_MEMORY;
838 
839  r = onig_reg_init(*reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
840  if (r) goto err;
841 
842  r = onig_compile_ruby(*reg, pattern, pattern_end, einfo, sourcefile, sourceline);
843  if (r) {
844  err:
845  onig_free(*reg);
846  *reg = NULL;
847  }
848  return r;
849 }
850 
851 static Regexp*
852 make_regexp(const char *s, long len, rb_encoding *enc, int flags, onig_errmsg_buffer err,
853  const char *sourcefile, int sourceline)
854 {
855  Regexp *rp;
856  int r;
857  OnigErrorInfo einfo;
858 
859  /* Handle escaped characters first. */
860 
861  /* Build a copy of the string (in dest) with the
862  escaped characters translated, and generate the regex
863  from that.
864  */
865 
866  r = onig_new_with_source(&rp, (UChar*)s, (UChar*)(s + len), flags,
867  enc, OnigDefaultSyntax, &einfo, sourcefile, sourceline);
868  if (r) {
869  onig_error_code_to_str((UChar*)err, r, &einfo);
870  return 0;
871  }
872  return rp;
873 }
874 
875 
876 /*
877  * Document-class: MatchData
878  *
879  * <code>MatchData</code> is the type of the special variable <code>$~</code>,
880  * and is the type of the object returned by <code>Regexp#match</code> and
881  * <code>Regexp.last_match</code>. It encapsulates all the results of a pattern
882  * match, results normally accessed through the special variables
883  * <code>$&</code>, <code>$'</code>, <code>$`</code>, <code>$1</code>,
884  * <code>$2</code>, and so on.
885  *
886  */
887 
889 
890 static VALUE
891 match_alloc(VALUE klass)
892 {
893  NEWOBJ_OF(match, struct RMatch, klass, T_MATCH);
894 
895  match->str = 0;
896  match->rmatch = 0;
897  match->regexp = 0;
898  match->rmatch = ZALLOC(struct rmatch);
899 
900  return (VALUE)match;
901 }
902 
903 int
904 rb_reg_region_copy(struct re_registers *to, const struct re_registers *from)
905 {
906  onig_region_copy(to, (OnigRegion *)from);
907  if (to->allocated) return 0;
908  rb_gc();
909  onig_region_copy(to, (OnigRegion *)from);
910  if (to->allocated) return 0;
911  return ONIGERR_MEMORY;
912 }
913 
914 typedef struct {
915  long byte_pos;
916  long char_pos;
917 } pair_t;
918 
919 static int
920 pair_byte_cmp(const void *pair1, const void *pair2)
921 {
922  long diff = ((pair_t*)pair1)->byte_pos - ((pair_t*)pair2)->byte_pos;
923 #if SIZEOF_LONG > SIZEOF_INT
924  return diff ? diff > 0 ? 1 : -1 : 0;
925 #else
926  return (int)diff;
927 #endif
928 }
929 
930 static void
931 update_char_offset(VALUE match)
932 {
933  struct rmatch *rm = RMATCH(match)->rmatch;
934  struct re_registers *regs;
935  int i, num_regs, num_pos;
936  long c;
937  char *s, *p, *q;
938  rb_encoding *enc;
939  pair_t *pairs;
940 
941  if (rm->char_offset_updated)
942  return;
943 
944  regs = &rm->regs;
945  num_regs = rm->regs.num_regs;
946 
947  if (rm->char_offset_num_allocated < num_regs) {
948  REALLOC_N(rm->char_offset, struct rmatch_offset, num_regs);
950  }
951 
952  enc = rb_enc_get(RMATCH(match)->str);
953  if (rb_enc_mbmaxlen(enc) == 1) {
954  for (i = 0; i < num_regs; i++) {
955  rm->char_offset[i].beg = BEG(i);
956  rm->char_offset[i].end = END(i);
957  }
958  rm->char_offset_updated = 1;
959  return;
960  }
961 
962  pairs = ALLOCA_N(pair_t, num_regs*2);
963  num_pos = 0;
964  for (i = 0; i < num_regs; i++) {
965  if (BEG(i) < 0)
966  continue;
967  pairs[num_pos++].byte_pos = BEG(i);
968  pairs[num_pos++].byte_pos = END(i);
969  }
970  qsort(pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
971 
972  s = p = RSTRING_PTR(RMATCH(match)->str);
973  c = 0;
974  for (i = 0; i < num_pos; i++) {
975  q = s + pairs[i].byte_pos;
976  c += rb_enc_strlen(p, q, enc);
977  pairs[i].char_pos = c;
978  p = q;
979  }
980 
981  for (i = 0; i < num_regs; i++) {
982  pair_t key, *found;
983  if (BEG(i) < 0) {
984  rm->char_offset[i].beg = -1;
985  rm->char_offset[i].end = -1;
986  continue;
987  }
988 
989  key.byte_pos = BEG(i);
990  found = bsearch(&key, pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
991  rm->char_offset[i].beg = found->char_pos;
992 
993  key.byte_pos = END(i);
994  found = bsearch(&key, pairs, num_pos, sizeof(pair_t), pair_byte_cmp);
995  rm->char_offset[i].end = found->char_pos;
996  }
997 
998  rm->char_offset_updated = 1;
999 }
1000 
1001 static void
1002 match_check(VALUE match)
1003 {
1004  if (!RMATCH(match)->regexp) {
1005  rb_raise(rb_eTypeError, "uninitialized Match");
1006  }
1007 }
1008 
1009 /* :nodoc: */
1010 static VALUE
1011 match_init_copy(VALUE obj, VALUE orig)
1012 {
1013  struct rmatch *rm;
1014 
1015  if (!OBJ_INIT_COPY(obj, orig)) return obj;
1016 
1017  RMATCH(obj)->str = RMATCH(orig)->str;
1018  RMATCH(obj)->regexp = RMATCH(orig)->regexp;
1019 
1020  rm = RMATCH(obj)->rmatch;
1021  if (rb_reg_region_copy(&rm->regs, RMATCH_REGS(orig)))
1022  rb_memerror();
1023 
1024  if (!RMATCH(orig)->rmatch->char_offset_updated) {
1025  rm->char_offset_updated = 0;
1026  }
1027  else {
1028  if (rm->char_offset_num_allocated < rm->regs.num_regs) {
1029  REALLOC_N(rm->char_offset, struct rmatch_offset, rm->regs.num_regs);
1031  }
1033  struct rmatch_offset, rm->regs.num_regs);
1034  rm->char_offset_updated = 1;
1035  RB_GC_GUARD(orig);
1036  }
1037 
1038  return obj;
1039 }
1040 
1041 
1042 /*
1043  * call-seq:
1044  * mtch.regexp -> regexp
1045  *
1046  * Returns the regexp.
1047  *
1048  * m = /a.*b/.match("abc")
1049  * m.regexp #=> /a.*b/
1050  */
1051 
1052 static VALUE
1053 match_regexp(VALUE match)
1054 {
1055  VALUE regexp;
1056  match_check(match);
1057  regexp = RMATCH(match)->regexp;
1058  if (NIL_P(regexp)) {
1059  VALUE str = rb_reg_nth_match(0, match);
1060  regexp = rb_reg_regcomp(rb_reg_quote(str));
1061  RMATCH(match)->regexp = regexp;
1062  }
1063  return regexp;
1064 }
1065 
1066 /*
1067  * call-seq:
1068  * mtch.names -> [name1, name2, ...]
1069  *
1070  * Returns a list of names of captures as an array of strings.
1071  * It is same as mtch.regexp.names.
1072  *
1073  * /(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge").names
1074  * #=> ["foo", "bar", "baz"]
1075  *
1076  * m = /(?<x>.)(?<y>.)?/.match("a") #=> #<MatchData "a" x:"a" y:nil>
1077  * m.names #=> ["x", "y"]
1078  */
1079 
1080 static VALUE
1081 match_names(VALUE match)
1082 {
1083  match_check(match);
1084  if (NIL_P(RMATCH(match)->regexp))
1085  return rb_ary_new_capa(0);
1086  return rb_reg_names(RMATCH(match)->regexp);
1087 }
1088 
1089 /*
1090  * call-seq:
1091  * mtch.length -> integer
1092  * mtch.size -> integer
1093  *
1094  * Returns the number of elements in the match array.
1095  *
1096  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1097  * m.length #=> 5
1098  * m.size #=> 5
1099  */
1100 
1101 static VALUE
1102 match_size(VALUE match)
1103 {
1104  match_check(match);
1105  return INT2FIX(RMATCH_REGS(match)->num_regs);
1106 }
1107 
1108 static int name_to_backref_number(struct re_registers *, VALUE, const char*, const char*);
1109 
1110 static int
1111 match_backref_number(VALUE match, VALUE backref)
1112 {
1113  const char *name;
1114  int num;
1115 
1116  struct re_registers *regs = RMATCH_REGS(match);
1117  VALUE regexp = RMATCH(match)->regexp;
1118 
1119  match_check(match);
1120  if (SYMBOL_P(backref)) {
1121  backref = rb_sym2str(backref);
1122  }
1123  else if (!RB_TYPE_P(backref, T_STRING)) {
1124  return NUM2INT(backref);
1125  }
1126  name = StringValueCStr(backref);
1127 
1128  num = name_to_backref_number(regs, regexp, name, name + strlen(name));
1129 
1130  if (num < 1) {
1131  rb_raise(rb_eIndexError, "undefined group name reference: %s", name);
1132  }
1133 
1134  return num;
1135 }
1136 
1137 int
1139 {
1140  return match_backref_number(match, backref);
1141 }
1142 
1143 /*
1144  * call-seq:
1145  * mtch.offset(n) -> array
1146  *
1147  * Returns a two-element array containing the beginning and ending offsets of
1148  * the <em>n</em>th match.
1149  * <em>n</em> can be a string or symbol to reference a named capture.
1150  *
1151  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1152  * m.offset(0) #=> [1, 7]
1153  * m.offset(4) #=> [6, 7]
1154  *
1155  * m = /(?<foo>.)(.)(?<bar>.)/.match("hoge")
1156  * p m.offset(:foo) #=> [0, 1]
1157  * p m.offset(:bar) #=> [2, 3]
1158  *
1159  */
1160 
1161 static VALUE
1162 match_offset(VALUE match, VALUE n)
1163 {
1164  int i = match_backref_number(match, n);
1165  struct re_registers *regs = RMATCH_REGS(match);
1166 
1167  match_check(match);
1168  if (i < 0 || regs->num_regs <= i)
1169  rb_raise(rb_eIndexError, "index %d out of matches", i);
1170 
1171  if (BEG(i) < 0)
1172  return rb_assoc_new(Qnil, Qnil);
1173 
1174  update_char_offset(match);
1175  return rb_assoc_new(INT2FIX(RMATCH(match)->rmatch->char_offset[i].beg),
1176  INT2FIX(RMATCH(match)->rmatch->char_offset[i].end));
1177 }
1178 
1179 
1180 /*
1181  * call-seq:
1182  * mtch.begin(n) -> integer
1183  *
1184  * Returns the offset of the start of the <em>n</em>th element of the match
1185  * array in the string.
1186  * <em>n</em> can be a string or symbol to reference a named capture.
1187  *
1188  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1189  * m.begin(0) #=> 1
1190  * m.begin(2) #=> 2
1191  *
1192  * m = /(?<foo>.)(.)(?<bar>.)/.match("hoge")
1193  * p m.begin(:foo) #=> 0
1194  * p m.begin(:bar) #=> 2
1195  */
1196 
1197 static VALUE
1198 match_begin(VALUE match, VALUE n)
1199 {
1200  int i = match_backref_number(match, n);
1201  struct re_registers *regs = RMATCH_REGS(match);
1202 
1203  match_check(match);
1204  if (i < 0 || regs->num_regs <= i)
1205  rb_raise(rb_eIndexError, "index %d out of matches", i);
1206 
1207  if (BEG(i) < 0)
1208  return Qnil;
1209 
1210  update_char_offset(match);
1211  return INT2FIX(RMATCH(match)->rmatch->char_offset[i].beg);
1212 }
1213 
1214 
1215 /*
1216  * call-seq:
1217  * mtch.end(n) -> integer
1218  *
1219  * Returns the offset of the character immediately following the end of the
1220  * <em>n</em>th element of the match array in the string.
1221  * <em>n</em> can be a string or symbol to reference a named capture.
1222  *
1223  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1224  * m.end(0) #=> 7
1225  * m.end(2) #=> 3
1226  *
1227  * m = /(?<foo>.)(.)(?<bar>.)/.match("hoge")
1228  * p m.end(:foo) #=> 1
1229  * p m.end(:bar) #=> 3
1230  */
1231 
1232 static VALUE
1233 match_end(VALUE match, VALUE n)
1234 {
1235  int i = match_backref_number(match, n);
1236  struct re_registers *regs = RMATCH_REGS(match);
1237 
1238  match_check(match);
1239  if (i < 0 || regs->num_regs <= i)
1240  rb_raise(rb_eIndexError, "index %d out of matches", i);
1241 
1242  if (BEG(i) < 0)
1243  return Qnil;
1244 
1245  update_char_offset(match);
1246  return INT2FIX(RMATCH(match)->rmatch->char_offset[i].end);
1247 }
1248 
1249 #define MATCH_BUSY FL_USER2
1250 
1251 void
1253 {
1254  FL_SET(match, MATCH_BUSY);
1255 }
1256 
1257 int
1259 {
1260  struct re_registers *regs;
1261  if (NIL_P(match)) return -1;
1262  regs = RMATCH_REGS(match);
1263  if (!regs) return -1;
1264  return regs->num_regs;
1265 }
1266 
1267 int
1269 {
1270  struct re_registers *regs;
1271  if (NIL_P(match)) return FALSE;
1272  regs = RMATCH_REGS(match);
1273  if (!regs) return FALSE;
1274  if (nth >= regs->num_regs) {
1275  return FALSE;
1276  }
1277  if (nth < 0) {
1278  nth += regs->num_regs;
1279  if (nth <= 0) return FALSE;
1280  }
1281  return (BEG(nth) != -1);
1282 }
1283 
1284 static void
1285 match_set_string(VALUE m, VALUE string, long pos, long len)
1286 {
1287  struct RMatch *match = (struct RMatch *)m;
1288  struct rmatch *rmatch = match->rmatch;
1289 
1290  match->str = string;
1291  match->regexp = Qnil;
1292  onig_region_resize(&rmatch->regs, 1);
1293  rmatch->regs.beg[0] = pos;
1294  rmatch->regs.end[0] = pos + len;
1295  rmatch->char_offset_updated = 0;
1296  OBJ_INFECT(match, string);
1297 }
1298 
1299 void
1300 rb_backref_set_string(VALUE string, long pos, long len)
1301 {
1302  VALUE match = rb_backref_get();
1303  if (NIL_P(match) || FL_TEST(match, MATCH_BUSY)) {
1304  match = match_alloc(rb_cMatch);
1305  }
1306  match_set_string(match, string, pos, len);
1307  rb_backref_set(match);
1308 }
1309 
1310 /*
1311  * call-seq:
1312  * rxp.fixed_encoding? -> true or false
1313  *
1314  * Returns false if rxp is applicable to
1315  * a string with any ASCII compatible encoding.
1316  * Returns true otherwise.
1317  *
1318  * r = /a/
1319  * r.fixed_encoding? #=> false
1320  * r =~ "\u{6666} a" #=> 2
1321  * r =~ "\xa1\xa2 a".force_encoding("euc-jp") #=> 2
1322  * r =~ "abc".force_encoding("euc-jp") #=> 0
1323  *
1324  * r = /a/u
1325  * r.fixed_encoding? #=> true
1326  * r.encoding #=> #<Encoding:UTF-8>
1327  * r =~ "\u{6666} a" #=> 2
1328  * r =~ "\xa1\xa2".force_encoding("euc-jp") #=> ArgumentError
1329  * r =~ "abc".force_encoding("euc-jp") #=> 0
1330  *
1331  * r = /\u{6666}/
1332  * r.fixed_encoding? #=> true
1333  * r.encoding #=> #<Encoding:UTF-8>
1334  * r =~ "\u{6666} a" #=> 0
1335  * r =~ "\xa1\xa2".force_encoding("euc-jp") #=> ArgumentError
1336  * r =~ "abc".force_encoding("euc-jp") #=> nil
1337  */
1338 
1339 static VALUE
1340 rb_reg_fixed_encoding_p(VALUE re)
1341 {
1342  if (FL_TEST(re, KCODE_FIXED))
1343  return Qtrue;
1344  else
1345  return Qfalse;
1346 }
1347 
1348 static VALUE
1349 rb_reg_preprocess(const char *p, const char *end, rb_encoding *enc,
1350  rb_encoding **fixed_enc, onig_errmsg_buffer err);
1351 
1352 
1353 static void
1354 reg_enc_error(VALUE re, VALUE str)
1355 {
1357  "incompatible encoding regexp match (%s regexp with %s string)",
1358  rb_enc_name(rb_enc_get(re)),
1359  rb_enc_name(rb_enc_get(str)));
1360 }
1361 
1362 static inline int
1363 str_coderange(VALUE str)
1364 {
1365  int cr = ENC_CODERANGE(str);
1366  if (cr == ENC_CODERANGE_UNKNOWN) {
1367  cr = rb_enc_str_coderange(str);
1368  }
1369  return cr;
1370 }
1371 
1372 static rb_encoding*
1373 rb_reg_prepare_enc(VALUE re, VALUE str, int warn)
1374 {
1375  rb_encoding *enc = 0;
1376  int cr = str_coderange(str);
1377 
1378  if (cr == ENC_CODERANGE_BROKEN) {
1380  "invalid byte sequence in %s",
1381  rb_enc_name(rb_enc_get(str)));
1382  }
1383 
1384  rb_reg_check(re);
1385  enc = rb_enc_get(str);
1386  if (RREGEXP_PTR(re)->enc == enc) {
1387  }
1388  else if (cr == ENC_CODERANGE_7BIT &&
1389  RREGEXP_PTR(re)->enc == rb_usascii_encoding()) {
1390  enc = RREGEXP_PTR(re)->enc;
1391  }
1392  else if (!rb_enc_asciicompat(enc)) {
1393  reg_enc_error(re, str);
1394  }
1395  else if (rb_reg_fixed_encoding_p(re)) {
1396  if ((!rb_enc_asciicompat(RREGEXP_PTR(re)->enc) ||
1397  cr != ENC_CODERANGE_7BIT)) {
1398  reg_enc_error(re, str);
1399  }
1400  enc = RREGEXP_PTR(re)->enc;
1401  }
1402  else if (warn && (RBASIC(re)->flags & REG_ENCODING_NONE) &&
1403  enc != rb_ascii8bit_encoding() &&
1404  cr != ENC_CODERANGE_7BIT) {
1405  rb_warn("historical binary regexp match /.../n against %s string",
1406  rb_enc_name(enc));
1407  }
1408  return enc;
1409 }
1410 
1411 regex_t *
1413 {
1414  regex_t *reg = RREGEXP_PTR(re);
1415  int r;
1416  OnigErrorInfo einfo;
1417  const char *pattern;
1418  VALUE unescaped;
1419  rb_encoding *fixed_enc = 0;
1420  rb_encoding *enc = rb_reg_prepare_enc(re, str, 1);
1421 
1422  if (reg->enc == enc) return reg;
1423 
1424  rb_reg_check(re);
1425  reg = RREGEXP_PTR(re);
1426  pattern = RREGEXP_SRC_PTR(re);
1427 
1428  unescaped = rb_reg_preprocess(
1429  pattern, pattern + RREGEXP_SRC_LEN(re), enc,
1430  &fixed_enc, err);
1431 
1432  if (unescaped == Qnil) {
1433  rb_raise(rb_eArgError, "regexp preprocess failed: %s", err);
1434  }
1435 
1436  r = onig_new(&reg, (UChar* )RSTRING_PTR(unescaped),
1437  (UChar* )(RSTRING_PTR(unescaped) + RSTRING_LEN(unescaped)),
1438  reg->options, enc,
1439  OnigDefaultSyntax, &einfo);
1440  if (r) {
1441  onig_error_code_to_str((UChar*)err, r, &einfo);
1442  rb_reg_raise(pattern, RREGEXP_SRC_LEN(re), err, re);
1443  }
1444 
1445  RB_GC_GUARD(unescaped);
1446  return reg;
1447 }
1448 
1449 regex_t *
1451 {
1452  onig_errmsg_buffer err = "";
1453  return rb_reg_prepare_re0(re, str, err);
1454 }
1455 
1456 long
1457 rb_reg_adjust_startpos(VALUE re, VALUE str, long pos, int reverse)
1458 {
1459  long range;
1460  rb_encoding *enc;
1461  UChar *p, *string;
1462 
1463  enc = rb_reg_prepare_enc(re, str, 0);
1464 
1465  if (reverse) {
1466  range = -pos;
1467  }
1468  else {
1469  range = RSTRING_LEN(str) - pos;
1470  }
1471 
1472  if (pos > 0 && ONIGENC_MBC_MAXLEN(enc) != 1 && pos < RSTRING_LEN(str)) {
1473  string = (UChar*)RSTRING_PTR(str);
1474 
1475  if (range > 0) {
1476  p = onigenc_get_right_adjust_char_head(enc, string, string + pos, string + RSTRING_LEN(str));
1477  }
1478  else {
1479  p = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, string, string + pos, string + RSTRING_LEN(str));
1480  }
1481  return p - string;
1482  }
1483 
1484  return pos;
1485 }
1486 
1487 /* returns byte offset */
1488 long
1489 rb_reg_search0(VALUE re, VALUE str, long pos, int reverse, int set_backref_str)
1490 {
1491  long result;
1492  VALUE match;
1493  struct re_registers regi, *regs = &regi;
1494  char *range = RSTRING_PTR(str);
1495  regex_t *reg;
1496  int tmpreg;
1497  onig_errmsg_buffer err = "";
1498 
1499  if (pos > RSTRING_LEN(str) || pos < 0) {
1501  return -1;
1502  }
1503 
1504  reg = rb_reg_prepare_re0(re, str, err);
1505  tmpreg = reg != RREGEXP_PTR(re);
1506  if (!tmpreg) RREGEXP(re)->usecnt++;
1507 
1508  match = rb_backref_get();
1509  if (!NIL_P(match)) {
1510  if (FL_TEST(match, MATCH_BUSY)) {
1511  match = Qnil;
1512  }
1513  else {
1514  regs = RMATCH_REGS(match);
1515  }
1516  }
1517  if (NIL_P(match)) {
1518  MEMZERO(regs, struct re_registers, 1);
1519  }
1520  if (!reverse) {
1521  range += RSTRING_LEN(str);
1522  }
1523  result = onig_search(reg,
1524  (UChar*)(RSTRING_PTR(str)),
1525  ((UChar*)(RSTRING_PTR(str)) + RSTRING_LEN(str)),
1526  ((UChar*)(RSTRING_PTR(str)) + pos),
1527  ((UChar*)range),
1528  regs, ONIG_OPTION_NONE);
1529  if (!tmpreg) RREGEXP(re)->usecnt--;
1530  if (tmpreg) {
1531  if (RREGEXP(re)->usecnt) {
1532  onig_free(reg);
1533  }
1534  else {
1535  onig_free(RREGEXP_PTR(re));
1536  RREGEXP_PTR(re) = reg;
1537  }
1538  }
1539  if (result < 0) {
1540  if (regs == &regi)
1541  onig_region_free(regs, 0);
1542  if (result == ONIG_MISMATCH) {
1544  return result;
1545  }
1546  else {
1547  onig_error_code_to_str((UChar*)err, (int)result);
1548  rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re);
1549  }
1550  }
1551 
1552  if (NIL_P(match)) {
1553  int err;
1554  match = match_alloc(rb_cMatch);
1555  err = rb_reg_region_copy(RMATCH_REGS(match), regs);
1556  onig_region_free(regs, 0);
1557  if (err) rb_memerror();
1558  }
1559  else {
1560  FL_UNSET(match, FL_TAINT);
1561  }
1562 
1563  if (set_backref_str) {
1564  RMATCH(match)->str = rb_str_new4(str);
1565  OBJ_INFECT(match, str);
1566  }
1567 
1568  RMATCH(match)->regexp = re;
1569  RMATCH(match)->rmatch->char_offset_updated = 0;
1570  rb_backref_set(match);
1571 
1572  OBJ_INFECT(match, re);
1573 
1574  return result;
1575 }
1576 
1577 long
1578 rb_reg_search(VALUE re, VALUE str, long pos, int reverse)
1579 {
1580  return rb_reg_search0(re, str, pos, reverse, 1);
1581 }
1582 
1583 bool
1585 {
1586  long result;
1587  VALUE match;
1588  struct re_registers regi, *regs = &regi;
1589  regex_t *reg;
1590  int tmpreg;
1591  onig_errmsg_buffer err = "";
1592 
1593  reg = rb_reg_prepare_re0(re, str, err);
1594  tmpreg = reg != RREGEXP_PTR(re);
1595  if (!tmpreg) RREGEXP(re)->usecnt++;
1596 
1597  match = rb_backref_get();
1598  if (!NIL_P(match)) {
1599  if (FL_TEST(match, MATCH_BUSY)) {
1600  match = Qnil;
1601  }
1602  else {
1603  regs = RMATCH_REGS(match);
1604  }
1605  }
1606  if (NIL_P(match)) {
1607  MEMZERO(regs, struct re_registers, 1);
1608  }
1609  result = onig_match(reg,
1610  (UChar*)(RSTRING_PTR(str)),
1611  ((UChar*)(RSTRING_PTR(str)) + RSTRING_LEN(str)),
1612  (UChar*)(RSTRING_PTR(str)),
1613  regs, ONIG_OPTION_NONE);
1614  if (!tmpreg) RREGEXP(re)->usecnt--;
1615  if (tmpreg) {
1616  if (RREGEXP(re)->usecnt) {
1617  onig_free(reg);
1618  }
1619  else {
1620  onig_free(RREGEXP_PTR(re));
1621  RREGEXP_PTR(re) = reg;
1622  }
1623  }
1624  if (result < 0) {
1625  if (regs == &regi)
1626  onig_region_free(regs, 0);
1627  if (result == ONIG_MISMATCH) {
1629  return false;
1630  }
1631  else {
1632  onig_error_code_to_str((UChar*)err, (int)result);
1633  rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re);
1634  }
1635  }
1636 
1637  if (NIL_P(match)) {
1638  int err;
1639  match = match_alloc(rb_cMatch);
1640  err = rb_reg_region_copy(RMATCH_REGS(match), regs);
1641  onig_region_free(regs, 0);
1642  if (err) rb_memerror();
1643  }
1644  else {
1645  FL_UNSET(match, FL_TAINT);
1646  }
1647 
1648  RMATCH(match)->str = rb_str_new4(str);
1649  OBJ_INFECT(match, str);
1650 
1651  RMATCH(match)->regexp = re;
1652  RMATCH(match)->rmatch->char_offset_updated = 0;
1653  rb_backref_set(match);
1654 
1655  OBJ_INFECT(match, re);
1656 
1657  return true;
1658 }
1659 
1660 VALUE
1661 rb_reg_nth_defined(int nth, VALUE match)
1662 {
1663  struct re_registers *regs;
1664  if (NIL_P(match)) return Qnil;
1665  match_check(match);
1666  regs = RMATCH_REGS(match);
1667  if (nth >= regs->num_regs) {
1668  return Qnil;
1669  }
1670  if (nth < 0) {
1671  nth += regs->num_regs;
1672  if (nth <= 0) return Qnil;
1673  }
1674  if (BEG(nth) == -1) return Qfalse;
1675  return Qtrue;
1676 }
1677 
1678 VALUE
1679 rb_reg_nth_match(int nth, VALUE match)
1680 {
1681  VALUE str;
1682  long start, end, len;
1683  struct re_registers *regs;
1684 
1685  if (NIL_P(match)) return Qnil;
1686  match_check(match);
1687  regs = RMATCH_REGS(match);
1688  if (nth >= regs->num_regs) {
1689  return Qnil;
1690  }
1691  if (nth < 0) {
1692  nth += regs->num_regs;
1693  if (nth <= 0) return Qnil;
1694  }
1695  start = BEG(nth);
1696  if (start == -1) return Qnil;
1697  end = END(nth);
1698  len = end - start;
1699  str = rb_str_subseq(RMATCH(match)->str, start, len);
1700  OBJ_INFECT(str, match);
1701  return str;
1702 }
1703 
1704 VALUE
1706 {
1707  return rb_reg_nth_match(0, match);
1708 }
1709 
1710 
1711 /*
1712  * call-seq:
1713  * mtch.pre_match -> str
1714  *
1715  * Returns the portion of the original string before the current match.
1716  * Equivalent to the special variable <code>$`</code>.
1717  *
1718  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1719  * m.pre_match #=> "T"
1720  */
1721 
1722 VALUE
1724 {
1725  VALUE str;
1726  struct re_registers *regs;
1727 
1728  if (NIL_P(match)) return Qnil;
1729  match_check(match);
1730  regs = RMATCH_REGS(match);
1731  if (BEG(0) == -1) return Qnil;
1732  str = rb_str_subseq(RMATCH(match)->str, 0, BEG(0));
1733  if (OBJ_TAINTED(match)) OBJ_TAINT(str);
1734  return str;
1735 }
1736 
1737 
1738 /*
1739  * call-seq:
1740  * mtch.post_match -> str
1741  *
1742  * Returns the portion of the original string after the current match.
1743  * Equivalent to the special variable <code>$'</code>.
1744  *
1745  * m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
1746  * m.post_match #=> ": The Movie"
1747  */
1748 
1749 VALUE
1751 {
1752  VALUE str;
1753  long pos;
1754  struct re_registers *regs;
1755 
1756  if (NIL_P(match)) return Qnil;
1757  match_check(match);
1758  regs = RMATCH_REGS(match);
1759  if (BEG(0) == -1) return Qnil;
1760  str = RMATCH(match)->str;
1761  pos = END(0);
1762  str = rb_str_subseq(str, pos, RSTRING_LEN(str) - pos);
1763  if (OBJ_TAINTED(match)) OBJ_TAINT(str);
1764  return str;
1765 }
1766 
1767 VALUE
1769 {
1770  int i;
1771  struct re_registers *regs;
1772 
1773  if (NIL_P(match)) return Qnil;
1774  match_check(match);
1775  regs = RMATCH_REGS(match);
1776  if (BEG(0) == -1) return Qnil;
1777 
1778  for (i=regs->num_regs-1; BEG(i) == -1 && i > 0; i--)
1779  ;
1780  if (i == 0) return Qnil;
1781  return rb_reg_nth_match(i, match);
1782 }
1783 
1784 static VALUE
1785 last_match_getter(void)
1786 {
1788 }
1789 
1790 static VALUE
1791 prematch_getter(void)
1792 {
1793  return rb_reg_match_pre(rb_backref_get());
1794 }
1795 
1796 static VALUE
1797 postmatch_getter(void)
1798 {
1800 }
1801 
1802 static VALUE
1803 last_paren_match_getter(void)
1804 {
1806 }
1807 
1808 static VALUE
1809 match_array(VALUE match, int start)
1810 {
1811  struct re_registers *regs;
1812  VALUE ary;
1813  VALUE target;
1814  int i;
1815  int taint = OBJ_TAINTED(match);
1816 
1817  match_check(match);
1818  regs = RMATCH_REGS(match);
1819  ary = rb_ary_new2(regs->num_regs);
1820  target = RMATCH(match)->str;
1821 
1822  for (i=start; i<regs->num_regs; i++) {
1823  if (regs->beg[i] == -1) {
1824  rb_ary_push(ary, Qnil);
1825  }
1826  else {
1827  VALUE str = rb_str_subseq(target, regs->beg[i], regs->end[i]-regs->beg[i]);
1828  if (taint) OBJ_TAINT(str);
1829  rb_ary_push(ary, str);
1830  }
1831  }
1832  return ary;
1833 }
1834 
1835 
1836 /*
1837  * call-seq:
1838  * mtch.to_a -> anArray
1839  *
1840  * Returns the array of matches.
1841  *
1842  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1843  * m.to_a #=> ["HX1138", "H", "X", "113", "8"]
1844  *
1845  * Because <code>to_a</code> is called when expanding
1846  * <code>*</code><em>variable</em>, there's a useful assignment
1847  * shortcut for extracting matched fields. This is slightly slower than
1848  * accessing the fields directly (as an intermediate array is
1849  * generated).
1850  *
1851  * all,f1,f2,f3 = * /(.)(.)(\d+)(\d)/.match("THX1138.")
1852  * all #=> "HX1138"
1853  * f1 #=> "H"
1854  * f2 #=> "X"
1855  * f3 #=> "113"
1856  */
1857 
1858 static VALUE
1859 match_to_a(VALUE match)
1860 {
1861  return match_array(match, 0);
1862 }
1863 
1864 
1865 /*
1866  * call-seq:
1867  * mtch.captures -> array
1868  *
1869  * Returns the array of captures; equivalent to <code>mtch.to_a[1..-1]</code>.
1870  *
1871  * f1,f2,f3,f4 = /(.)(.)(\d+)(\d)/.match("THX1138.").captures
1872  * f1 #=> "H"
1873  * f2 #=> "X"
1874  * f3 #=> "113"
1875  * f4 #=> "8"
1876  */
1877 static VALUE
1878 match_captures(VALUE match)
1879 {
1880  return match_array(match, 1);
1881 }
1882 
1883 static int
1884 name_to_backref_number(struct re_registers *regs, VALUE regexp, const char* name, const char* name_end)
1885 {
1887  (const unsigned char *)name, (const unsigned char *)name_end, regs);
1888 }
1889 
1890 NORETURN(static void name_to_backref_error(VALUE name));
1891 static void
1892 name_to_backref_error(VALUE name)
1893 {
1894  rb_raise(rb_eIndexError, "undefined group name reference: % "PRIsVALUE,
1895  name);
1896 }
1897 
1898 #define NAME_TO_NUMBER(regs, re, name, name_ptr, name_end) \
1899  (NIL_P(re) ? 0 : \
1900  !rb_enc_compatible(RREGEXP_SRC(re), (name)) ? 0 : \
1901  name_to_backref_number((regs), (re), (name_ptr), (name_end)))
1902 
1903 static int
1904 namev_to_backref_number(struct re_registers *regs, VALUE re, VALUE name)
1905 {
1906  int num;
1907 
1908  if (SYMBOL_P(name)) {
1909  name = rb_sym2str(name);
1910  }
1911  else if (!RB_TYPE_P(name, T_STRING)) {
1912  return -1;
1913  }
1914  num = NAME_TO_NUMBER(regs, re, name,
1915  RSTRING_PTR(name), RSTRING_END(name));
1916  if (num < 1) {
1917  name_to_backref_error(name);
1918  }
1919  return num;
1920 }
1921 
1922 static VALUE
1923 match_ary_subseq(VALUE match, long beg, long len, VALUE result)
1924 {
1925  long olen = RMATCH_REGS(match)->num_regs;
1926  long j, end = olen < beg+len ? olen : beg+len;
1927  if (NIL_P(result)) result = rb_ary_new_capa(len);
1928  if (len == 0) return result;
1929 
1930  for (j = beg; j < end; j++) {
1931  rb_ary_push(result, rb_reg_nth_match((int)j, match));
1932  }
1933  if (beg + len > j) {
1934  rb_ary_resize(result, RARRAY_LEN(result) + (beg + len) - j);
1935  }
1936  return result;
1937 }
1938 
1939 static VALUE
1940 match_ary_aref(VALUE match, VALUE idx, VALUE result)
1941 {
1942  long beg, len;
1943  int num_regs = RMATCH_REGS(match)->num_regs;
1944 
1945  /* check if idx is Range */
1946  switch (rb_range_beg_len(idx, &beg, &len, (long)num_regs, !NIL_P(result))) {
1947  case Qfalse:
1948  if (NIL_P(result)) return rb_reg_nth_match(NUM2INT(idx), match);
1949  rb_ary_push(result, rb_reg_nth_match(NUM2INT(idx), match));
1950  return result;
1951  case Qnil:
1952  return Qnil;
1953  default:
1954  return match_ary_subseq(match, beg, len, result);
1955  }
1956 }
1957 
1958 /*
1959  * call-seq:
1960  * mtch[i] -> str or nil
1961  * mtch[start, length] -> array
1962  * mtch[range] -> array
1963  * mtch[name] -> str or nil
1964  *
1965  * Match Reference -- <code>MatchData</code> acts as an array, and may be
1966  * accessed using the normal array indexing techniques. <code>mtch[0]</code>
1967  * is equivalent to the special variable <code>$&</code>, and returns the
1968  * entire matched string. <code>mtch[1]</code>, <code>mtch[2]</code>, and so
1969  * on return the values of the matched backreferences (portions of the
1970  * pattern between parentheses).
1971  *
1972  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
1973  * m #=> #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8">
1974  * m[0] #=> "HX1138"
1975  * m[1, 2] #=> ["H", "X"]
1976  * m[1..3] #=> ["H", "X", "113"]
1977  * m[-3, 2] #=> ["X", "113"]
1978  *
1979  * m = /(?<foo>a+)b/.match("ccaaab")
1980  * m #=> #<MatchData "aaab" foo:"aaa">
1981  * m["foo"] #=> "aaa"
1982  * m[:foo] #=> "aaa"
1983  */
1984 
1985 static VALUE
1986 match_aref(int argc, VALUE *argv, VALUE match)
1987 {
1988  VALUE idx, length;
1989 
1990  match_check(match);
1991  rb_scan_args(argc, argv, "11", &idx, &length);
1992 
1993  if (NIL_P(length)) {
1994  if (FIXNUM_P(idx)) {
1995  return rb_reg_nth_match(FIX2INT(idx), match);
1996  }
1997  else {
1998  int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, idx);
1999  if (num >= 0) {
2000  return rb_reg_nth_match(num, match);
2001  }
2002  else {
2003  return match_ary_aref(match, idx, Qnil);
2004  }
2005  }
2006  }
2007  else {
2008  long beg = NUM2LONG(idx);
2009  long len = NUM2LONG(length);
2010  long num_regs = RMATCH_REGS(match)->num_regs;
2011  if (len < 0) {
2012  return Qnil;
2013  }
2014  if (beg < 0) {
2015  beg += num_regs;
2016  if (beg < 0) return Qnil;
2017  }
2018  else if (beg > num_regs) {
2019  return Qnil;
2020  }
2021  else if (beg+len > num_regs) {
2022  len = num_regs - beg;
2023  }
2024  return match_ary_subseq(match, beg, len, Qnil);
2025  }
2026 }
2027 
2028 /*
2029  * call-seq:
2030  *
2031  * mtch.values_at([index]*) -> array
2032  *
2033  * Uses each <i>index</i> to access the matching values, returning an array of
2034  * the corresponding matches.
2035  *
2036  * m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")
2037  * m.to_a #=> ["HX1138", "H", "X", "113", "8"]
2038  * m.values_at(0, 2, -2) #=> ["HX1138", "X", "113"]
2039  *
2040  * m = /(?<a>\d+) *(?<op>[+\-*\/]) *(?<b>\d+)/.match("1 + 2")
2041  * m.to_a #=> ["1 + 2", "1", "+", "2"]
2042  * m.values_at(:a, :b, :op) #=> ["1", "2", "+"]
2043  */
2044 
2045 static VALUE
2046 match_values_at(int argc, VALUE *argv, VALUE match)
2047 {
2048  VALUE result;
2049  int i;
2050 
2051  match_check(match);
2052  result = rb_ary_new2(argc);
2053 
2054  for (i=0; i<argc; i++) {
2055  if (FIXNUM_P(argv[i])) {
2056  rb_ary_push(result, rb_reg_nth_match(FIX2INT(argv[i]), match));
2057  }
2058  else {
2059  int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, argv[i]);
2060  if (num >= 0) {
2061  rb_ary_push(result, rb_reg_nth_match(num, match));
2062  }
2063  else {
2064  match_ary_aref(match, argv[i], result);
2065  }
2066  }
2067  }
2068  return result;
2069 }
2070 
2071 
2072 /*
2073  * call-seq:
2074  * mtch.to_s -> str
2075  *
2076  * Returns the entire matched string.
2077  *
2078  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2079  * m.to_s #=> "HX1138"
2080  */
2081 
2082 static VALUE
2083 match_to_s(VALUE match)
2084 {
2085  VALUE str = rb_reg_last_match(match);
2086 
2087  match_check(match);
2088  if (NIL_P(str)) str = rb_str_new(0,0);
2089  if (OBJ_TAINTED(match)) OBJ_TAINT(str);
2090  if (OBJ_TAINTED(RMATCH(match)->str)) OBJ_TAINT(str);
2091  return str;
2092 }
2093 
2094 static int
2095 match_named_captures_iter(const OnigUChar *name, const OnigUChar *name_end,
2096  int back_num, int *back_refs, OnigRegex regex, void *arg) {
2097  struct MEMO *memo = MEMO_CAST(arg);
2098  VALUE hash = memo->v1;
2099  VALUE match = memo->v2;
2100 
2101  VALUE key = rb_enc_str_new((const char *)name, name_end-name, regex->enc);
2102  VALUE value;
2103 
2104  int i;
2105  int found = 0;
2106 
2107  for (i = 0; i < back_num; i++) {
2108  value = rb_reg_nth_match(back_refs[i], match);
2109  if (RTEST(value)) {
2110  rb_hash_aset(hash, key, value);
2111  found = 1;
2112  }
2113  }
2114 
2115  if (found == 0) {
2116  rb_hash_aset(hash, key, Qnil);
2117  }
2118 
2119  return 0;
2120 }
2121 
2122 /*
2123  * call-seq:
2124  * mtch.named_captures -> hash
2125  *
2126  * Returns a Hash using named capture.
2127  *
2128  * A key of the hash is a name of the named captures.
2129  * A value of the hash is a string of last successful capture of corresponding
2130  * group.
2131  *
2132  * m = /(?<a>.)(?<b>.)/.match("01")
2133  * m.named_captures #=> {"a" => "0", "b" => "1"}
2134  *
2135  * m = /(?<a>.)(?<b>.)?/.match("0")
2136  * m.named_captures #=> {"a" => "0", "b" => nil}
2137  *
2138  * m = /(?<a>.)(?<a>.)/.match("01")
2139  * m.named_captures #=> {"a" => "1"}
2140  *
2141  * m = /(?<a>x)|(?<a>y)/.match("x")
2142  * m.named_captures #=> {"a" => "x"}
2143  */
2144 
2145 static VALUE
2146 match_named_captures(VALUE match)
2147 {
2148  VALUE hash;
2149  struct MEMO *memo;
2150 
2151  match_check(match);
2152  if (NIL_P(RMATCH(match)->regexp))
2153  return rb_hash_new();
2154 
2155  hash = rb_hash_new();
2156  memo = MEMO_NEW(hash, match, 0);
2157 
2158  onig_foreach_name(RREGEXP(RMATCH(match)->regexp)->ptr, match_named_captures_iter, (void*)memo);
2159 
2160  return hash;
2161 }
2162 
2163 /*
2164  * call-seq:
2165  * mtch.string -> str
2166  *
2167  * Returns a frozen copy of the string passed in to <code>match</code>.
2168  *
2169  * m = /(.)(.)(\d+)(\d)/.match("THX1138.")
2170  * m.string #=> "THX1138."
2171  */
2172 
2173 static VALUE
2174 match_string(VALUE match)
2175 {
2176  match_check(match);
2177  return RMATCH(match)->str; /* str is frozen */
2178 }
2179 
2181  const UChar *name;
2182  long len;
2183 };
2184 
2185 static int
2186 match_inspect_name_iter(const OnigUChar *name, const OnigUChar *name_end,
2187  int back_num, int *back_refs, OnigRegex regex, void *arg0)
2188 {
2189  struct backref_name_tag *arg = (struct backref_name_tag *)arg0;
2190  int i;
2191 
2192  for (i = 0; i < back_num; i++) {
2193  arg[back_refs[i]].name = name;
2194  arg[back_refs[i]].len = name_end - name;
2195  }
2196  return 0;
2197 }
2198 
2199 /*
2200  * call-seq:
2201  * mtch.inspect -> str
2202  *
2203  * Returns a printable version of <i>mtch</i>.
2204  *
2205  * puts /.$/.match("foo").inspect
2206  * #=> #<MatchData "o">
2207  *
2208  * puts /(.)(.)(.)/.match("foo").inspect
2209  * #=> #<MatchData "foo" 1:"f" 2:"o" 3:"o">
2210  *
2211  * puts /(.)(.)?(.)/.match("fo").inspect
2212  * #=> #<MatchData "fo" 1:"f" 2:nil 3:"o">
2213  *
2214  * puts /(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge").inspect
2215  * #=> #<MatchData "hog" foo:"h" bar:"o" baz:"g">
2216  *
2217  */
2218 
2219 static VALUE
2220 match_inspect(VALUE match)
2221 {
2222  VALUE cname = rb_class_path(rb_obj_class(match));
2223  VALUE str;
2224  int i;
2225  struct re_registers *regs = RMATCH_REGS(match);
2226  int num_regs = regs->num_regs;
2227  struct backref_name_tag *names;
2228  VALUE regexp = RMATCH(match)->regexp;
2229 
2230  if (regexp == 0) {
2231  return rb_sprintf("#<%"PRIsVALUE":%p>", cname, (void*)match);
2232  }
2233  else if (NIL_P(regexp)) {
2234  return rb_sprintf("#<%"PRIsVALUE": %"PRIsVALUE">",
2235  cname, rb_reg_nth_match(0, match));
2236  }
2237 
2238  names = ALLOCA_N(struct backref_name_tag, num_regs);
2239  MEMZERO(names, struct backref_name_tag, num_regs);
2240 
2242  match_inspect_name_iter, names);
2243 
2244  str = rb_str_buf_new2("#<");
2245  rb_str_append(str, cname);
2246 
2247  for (i = 0; i < num_regs; i++) {
2248  VALUE v;
2249  rb_str_buf_cat2(str, " ");
2250  if (0 < i) {
2251  if (names[i].name)
2252  rb_str_buf_cat(str, (const char *)names[i].name, names[i].len);
2253  else {
2254  rb_str_catf(str, "%d", i);
2255  }
2256  rb_str_buf_cat2(str, ":");
2257  }
2258  v = rb_reg_nth_match(i, match);
2259  if (v == Qnil)
2260  rb_str_buf_cat2(str, "nil");
2261  else
2263  }
2264  rb_str_buf_cat2(str, ">");
2265 
2266  return str;
2267 }
2268 
2270 
2271 static int
2272 read_escaped_byte(const char **pp, const char *end, onig_errmsg_buffer err)
2273 {
2274  const char *p = *pp;
2275  int code;
2276  int meta_prefix = 0, ctrl_prefix = 0;
2277  size_t len;
2278 
2279  if (p == end || *p++ != '\\') {
2280  errcpy(err, "too short escaped multibyte character");
2281  return -1;
2282  }
2283 
2284 again:
2285  if (p == end) {
2286  errcpy(err, "too short escape sequence");
2287  return -1;
2288  }
2289  switch (*p++) {
2290  case '\\': code = '\\'; break;
2291  case 'n': code = '\n'; break;
2292  case 't': code = '\t'; break;
2293  case 'r': code = '\r'; break;
2294  case 'f': code = '\f'; break;
2295  case 'v': code = '\013'; break;
2296  case 'a': code = '\007'; break;
2297  case 'e': code = '\033'; break;
2298 
2299  /* \OOO */
2300  case '0': case '1': case '2': case '3':
2301  case '4': case '5': case '6': case '7':
2302  p--;
2303  code = scan_oct(p, end < p+3 ? end-p : 3, &len);
2304  p += len;
2305  break;
2306 
2307  case 'x': /* \xHH */
2308  code = scan_hex(p, end < p+2 ? end-p : 2, &len);
2309  if (len < 1) {
2310  errcpy(err, "invalid hex escape");
2311  return -1;
2312  }
2313  p += len;
2314  break;
2315 
2316  case 'M': /* \M-X, \M-\C-X, \M-\cX */
2317  if (meta_prefix) {
2318  errcpy(err, "duplicate meta escape");
2319  return -1;
2320  }
2321  meta_prefix = 1;
2322  if (p+1 < end && *p++ == '-' && (*p & 0x80) == 0) {
2323  if (*p == '\\') {
2324  p++;
2325  goto again;
2326  }
2327  else {
2328  code = *p++;
2329  break;
2330  }
2331  }
2332  errcpy(err, "too short meta escape");
2333  return -1;
2334 
2335  case 'C': /* \C-X, \C-\M-X */
2336  if (p == end || *p++ != '-') {
2337  errcpy(err, "too short control escape");
2338  return -1;
2339  }
2340  case 'c': /* \cX, \c\M-X */
2341  if (ctrl_prefix) {
2342  errcpy(err, "duplicate control escape");
2343  return -1;
2344  }
2345  ctrl_prefix = 1;
2346  if (p < end && (*p & 0x80) == 0) {
2347  if (*p == '\\') {
2348  p++;
2349  goto again;
2350  }
2351  else {
2352  code = *p++;
2353  break;
2354  }
2355  }
2356  errcpy(err, "too short control escape");
2357  return -1;
2358 
2359  default:
2360  errcpy(err, "unexpected escape sequence");
2361  return -1;
2362  }
2363  if (code < 0 || 0xff < code) {
2364  errcpy(err, "invalid escape code");
2365  return -1;
2366  }
2367 
2368  if (ctrl_prefix)
2369  code &= 0x1f;
2370  if (meta_prefix)
2371  code |= 0x80;
2372 
2373  *pp = p;
2374  return code;
2375 }
2376 
2377 static int
2378 unescape_escaped_nonascii(const char **pp, const char *end, rb_encoding *enc,
2380 {
2381  const char *p = *pp;
2382  int chmaxlen = rb_enc_mbmaxlen(enc);
2383  char *chbuf = ALLOCA_N(char, chmaxlen);
2384  int chlen = 0;
2385  int byte;
2386  int l;
2387 
2388  memset(chbuf, 0, chmaxlen);
2389 
2390  byte = read_escaped_byte(&p, end, err);
2391  if (byte == -1) {
2392  return -1;
2393  }
2394 
2395  chbuf[chlen++] = byte;
2396  while (chlen < chmaxlen &&
2397  MBCLEN_NEEDMORE_P(rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc))) {
2398  byte = read_escaped_byte(&p, end, err);
2399  if (byte == -1) {
2400  return -1;
2401  }
2402  chbuf[chlen++] = byte;
2403  }
2404 
2405  l = rb_enc_precise_mbclen(chbuf, chbuf+chlen, enc);
2406  if (MBCLEN_INVALID_P(l)) {
2407  errcpy(err, "invalid multibyte escape");
2408  return -1;
2409  }
2410  if (1 < chlen || (chbuf[0] & 0x80)) {
2411  rb_str_buf_cat(buf, chbuf, chlen);
2412 
2413  if (*encp == 0)
2414  *encp = enc;
2415  else if (*encp != enc) {
2416  errcpy(err, "escaped non ASCII character in UTF-8 regexp");
2417  return -1;
2418  }
2419  }
2420  else {
2421  char escbuf[5];
2422  snprintf(escbuf, sizeof(escbuf), "\\x%02X", chbuf[0]&0xff);
2423  rb_str_buf_cat(buf, escbuf, 4);
2424  }
2425  *pp = p;
2426  return 0;
2427 }
2428 
2429 static int
2430 check_unicode_range(unsigned long code, onig_errmsg_buffer err)
2431 {
2432  if ((0xd800 <= code && code <= 0xdfff) || /* Surrogates */
2433  0x10ffff < code) {
2434  errcpy(err, "invalid Unicode range");
2435  return -1;
2436  }
2437  return 0;
2438 }
2439 
2440 static int
2441 append_utf8(unsigned long uv,
2443 {
2444  if (check_unicode_range(uv, err) != 0)
2445  return -1;
2446  if (uv < 0x80) {
2447  char escbuf[5];
2448  snprintf(escbuf, sizeof(escbuf), "\\x%02X", (int)uv);
2449  rb_str_buf_cat(buf, escbuf, 4);
2450  }
2451  else {
2452  int len;
2453  char utf8buf[6];
2454  len = rb_uv_to_utf8(utf8buf, uv);
2455  rb_str_buf_cat(buf, utf8buf, len);
2456 
2457  if (*encp == 0)
2458  *encp = rb_utf8_encoding();
2459  else if (*encp != rb_utf8_encoding()) {
2460  errcpy(err, "UTF-8 character in non UTF-8 regexp");
2461  return -1;
2462  }
2463  }
2464  return 0;
2465 }
2466 
2467 static int
2468 unescape_unicode_list(const char **pp, const char *end,
2470 {
2471  const char *p = *pp;
2472  int has_unicode = 0;
2473  unsigned long code;
2474  size_t len;
2475 
2476  while (p < end && ISSPACE(*p)) p++;
2477 
2478  while (1) {
2479  code = ruby_scan_hex(p, end-p, &len);
2480  if (len == 0)
2481  break;
2482  if (6 < len) { /* max 10FFFF */
2483  errcpy(err, "invalid Unicode range");
2484  return -1;
2485  }
2486  p += len;
2487  if (append_utf8(code, buf, encp, err) != 0)
2488  return -1;
2489  has_unicode = 1;
2490 
2491  while (p < end && ISSPACE(*p)) p++;
2492  }
2493 
2494  if (has_unicode == 0) {
2495  errcpy(err, "invalid Unicode list");
2496  return -1;
2497  }
2498 
2499  *pp = p;
2500 
2501  return 0;
2502 }
2503 
2504 static int
2505 unescape_unicode_bmp(const char **pp, const char *end,
2507 {
2508  const char *p = *pp;
2509  size_t len;
2510  unsigned long code;
2511 
2512  if (end < p+4) {
2513  errcpy(err, "invalid Unicode escape");
2514  return -1;
2515  }
2516  code = ruby_scan_hex(p, 4, &len);
2517  if (len != 4) {
2518  errcpy(err, "invalid Unicode escape");
2519  return -1;
2520  }
2521  if (append_utf8(code, buf, encp, err) != 0)
2522  return -1;
2523  *pp = p + 4;
2524  return 0;
2525 }
2526 
2527 static int
2528 unescape_nonascii(const char *p, const char *end, rb_encoding *enc,
2529  VALUE buf, rb_encoding **encp, int *has_property,
2531 {
2532  char c;
2533  char smallbuf[2];
2534 
2535  while (p < end) {
2536  int chlen = rb_enc_precise_mbclen(p, end, enc);
2537  if (!MBCLEN_CHARFOUND_P(chlen)) {
2538  errcpy(err, "invalid multibyte character");
2539  return -1;
2540  }
2541  chlen = MBCLEN_CHARFOUND_LEN(chlen);
2542  if (1 < chlen || (*p & 0x80)) {
2543  rb_str_buf_cat(buf, p, chlen);
2544  p += chlen;
2545  if (*encp == 0)
2546  *encp = enc;
2547  else if (*encp != enc) {
2548  errcpy(err, "non ASCII character in UTF-8 regexp");
2549  return -1;
2550  }
2551  continue;
2552  }
2553 
2554  switch (c = *p++) {
2555  case '\\':
2556  if (p == end) {
2557  errcpy(err, "too short escape sequence");
2558  return -1;
2559  }
2560  switch (c = *p++) {
2561  case '1': case '2': case '3':
2562  case '4': case '5': case '6': case '7': /* \O, \OO, \OOO or backref */
2563  {
2564  size_t len = end-(p-1), octlen;
2565  if (ruby_scan_oct(p-1, len < 3 ? len : 3, &octlen) <= 0177) {
2566  /* backref or 7bit octal.
2567  no need to unescape anyway.
2568  re-escaping may break backref */
2569  goto escape_asis;
2570  }
2571  }
2572  /* xxx: How about more than 199 subexpressions? */
2573 
2574  case '0': /* \0, \0O, \0OO */
2575 
2576  case 'x': /* \xHH */
2577  case 'c': /* \cX, \c\M-X */
2578  case 'C': /* \C-X, \C-\M-X */
2579  case 'M': /* \M-X, \M-\C-X, \M-\cX */
2580  p = p-2;
2581  if (enc == rb_usascii_encoding()) {
2582  const char *pbeg = p;
2583  c = read_escaped_byte(&p, end, err);
2584  if (c == (char)-1) return -1;
2585  rb_str_buf_cat(buf, pbeg, p-pbeg);
2586  }
2587  else {
2588  if (unescape_escaped_nonascii(&p, end, enc, buf, encp, err) != 0)
2589  return -1;
2590  }
2591  break;
2592 
2593  case 'u':
2594  if (p == end) {
2595  errcpy(err, "too short escape sequence");
2596  return -1;
2597  }
2598  if (*p == '{') {
2599  /* \u{H HH HHH HHHH HHHHH HHHHHH ...} */
2600  p++;
2601  if (unescape_unicode_list(&p, end, buf, encp, err) != 0)
2602  return -1;
2603  if (p == end || *p++ != '}') {
2604  errcpy(err, "invalid Unicode list");
2605  return -1;
2606  }
2607  break;
2608  }
2609  else {
2610  /* \uHHHH */
2611  if (unescape_unicode_bmp(&p, end, buf, encp, err) != 0)
2612  return -1;
2613  break;
2614  }
2615 
2616  case 'p': /* \p{Hiragana} */
2617  case 'P':
2618  if (!*encp) {
2619  *has_property = 1;
2620  }
2621  goto escape_asis;
2622 
2623  default: /* \n, \\, \d, \9, etc. */
2624 escape_asis:
2625  smallbuf[0] = '\\';
2626  smallbuf[1] = c;
2627  rb_str_buf_cat(buf, smallbuf, 2);
2628  break;
2629  }
2630  break;
2631 
2632  default:
2633  rb_str_buf_cat(buf, &c, 1);
2634  break;
2635  }
2636  }
2637 
2638  return 0;
2639 }
2640 
2641 static VALUE
2642 rb_reg_preprocess(const char *p, const char *end, rb_encoding *enc,
2643  rb_encoding **fixed_enc, onig_errmsg_buffer err)
2644 {
2645  VALUE buf;
2646  int has_property = 0;
2647 
2648  buf = rb_str_buf_new(0);
2649 
2650  if (rb_enc_asciicompat(enc))
2651  *fixed_enc = 0;
2652  else {
2653  *fixed_enc = enc;
2654  rb_enc_associate(buf, enc);
2655  }
2656 
2657  if (unescape_nonascii(p, end, enc, buf, fixed_enc, &has_property, err) != 0)
2658  return Qnil;
2659 
2660  if (has_property && !*fixed_enc) {
2661  *fixed_enc = enc;
2662  }
2663 
2664  if (*fixed_enc) {
2665  rb_enc_associate(buf, *fixed_enc);
2666  }
2667 
2668  return buf;
2669 }
2670 
2671 VALUE
2673 {
2674  rb_encoding *fixed_enc = 0;
2675  onig_errmsg_buffer err = "";
2676  VALUE buf;
2677  char *p, *end;
2678  rb_encoding *enc;
2679 
2680  StringValue(str);
2681  p = RSTRING_PTR(str);
2682  end = p + RSTRING_LEN(str);
2683  enc = rb_enc_get(str);
2684 
2685  buf = rb_reg_preprocess(p, end, enc, &fixed_enc, err);
2686  RB_GC_GUARD(str);
2687 
2688  if (buf == Qnil) {
2689  return rb_reg_error_desc(str, 0, err);
2690  }
2691  return Qnil;
2692 }
2693 
2694 static VALUE
2695 rb_reg_preprocess_dregexp(VALUE ary, int options)
2696 {
2697  rb_encoding *fixed_enc = 0;
2698  rb_encoding *regexp_enc = 0;
2699  onig_errmsg_buffer err = "";
2700  int i;
2701  VALUE result = 0;
2702  rb_encoding *ascii8bit = rb_ascii8bit_encoding();
2703 
2704  if (RARRAY_LEN(ary) == 0) {
2705  rb_raise(rb_eArgError, "no arguments given");
2706  }
2707 
2708  for (i = 0; i < RARRAY_LEN(ary); i++) {
2709  VALUE str = RARRAY_AREF(ary, i);
2710  VALUE buf;
2711  char *p, *end;
2712  rb_encoding *src_enc;
2713 
2714  src_enc = rb_enc_get(str);
2715  if (options & ARG_ENCODING_NONE &&
2716  src_enc != ascii8bit) {
2717  if (str_coderange(str) != ENC_CODERANGE_7BIT)
2718  rb_raise(rb_eRegexpError, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
2719  else
2720  src_enc = ascii8bit;
2721  }
2722 
2723  StringValue(str);
2724  p = RSTRING_PTR(str);
2725  end = p + RSTRING_LEN(str);
2726 
2727  buf = rb_reg_preprocess(p, end, src_enc, &fixed_enc, err);
2728 
2729  if (buf == Qnil)
2730  rb_raise(rb_eArgError, "%s", err);
2731 
2732  if (fixed_enc != 0) {
2733  if (regexp_enc != 0 && regexp_enc != fixed_enc) {
2734  rb_raise(rb_eRegexpError, "encoding mismatch in dynamic regexp : %s and %s",
2735  rb_enc_name(regexp_enc), rb_enc_name(fixed_enc));
2736  }
2737  regexp_enc = fixed_enc;
2738  }
2739 
2740  if (!result)
2741  result = rb_str_new3(str);
2742  else
2743  rb_str_buf_append(result, str);
2744  }
2745  if (regexp_enc) {
2746  rb_enc_associate(result, regexp_enc);
2747  }
2748 
2749  return result;
2750 }
2751 
2752 static int
2753 rb_reg_initialize(VALUE obj, const char *s, long len, rb_encoding *enc,
2754  int options, onig_errmsg_buffer err,
2755  const char *sourcefile, int sourceline)
2756 {
2757  struct RRegexp *re = RREGEXP(obj);
2758  VALUE unescaped;
2759  rb_encoding *fixed_enc = 0;
2761 
2762  rb_check_frozen(obj);
2763  if (FL_TEST(obj, REG_LITERAL))
2764  rb_raise(rb_eSecurityError, "can't modify literal regexp");
2765  if (re->ptr)
2766  rb_raise(rb_eTypeError, "already initialized regexp");
2767  re->ptr = 0;
2768 
2769  if (rb_enc_dummy_p(enc)) {
2770  errcpy(err, "can't make regexp with dummy encoding");
2771  return -1;
2772  }
2773 
2774  unescaped = rb_reg_preprocess(s, s+len, enc, &fixed_enc, err);
2775  if (unescaped == Qnil)
2776  return -1;
2777 
2778  if (fixed_enc) {
2779  if ((fixed_enc != enc && (options & ARG_ENCODING_FIXED)) ||
2780  (fixed_enc != a_enc && (options & ARG_ENCODING_NONE))) {
2781  errcpy(err, "incompatible character encoding");
2782  return -1;
2783  }
2784  if (fixed_enc != a_enc) {
2785  options |= ARG_ENCODING_FIXED;
2786  enc = fixed_enc;
2787  }
2788  }
2789  else if (!(options & ARG_ENCODING_FIXED)) {
2790  enc = rb_usascii_encoding();
2791  }
2792 
2793  rb_enc_associate((VALUE)re, enc);
2794  if ((options & ARG_ENCODING_FIXED) || fixed_enc) {
2795  re->basic.flags |= KCODE_FIXED;
2796  }
2797  if (options & ARG_ENCODING_NONE) {
2798  re->basic.flags |= REG_ENCODING_NONE;
2799  }
2800 
2801  re->ptr = make_regexp(RSTRING_PTR(unescaped), RSTRING_LEN(unescaped), enc,
2802  options & ARG_REG_OPTION_MASK, err,
2803  sourcefile, sourceline);
2804  if (!re->ptr) return -1;
2805  RB_GC_GUARD(unescaped);
2806  return 0;
2807 }
2808 
2809 static void
2810 reg_set_source(VALUE reg, VALUE str, rb_encoding *enc)
2811 {
2812  rb_encoding *regenc = rb_enc_get(reg);
2813  if (regenc != enc) {
2814  str = rb_enc_associate(rb_str_dup(str), enc = regenc);
2815  }
2816  RB_OBJ_WRITE(reg, &RREGEXP(reg)->src, rb_fstring(str));
2817 }
2818 
2819 static int
2820 rb_reg_initialize_str(VALUE obj, VALUE str, int options, onig_errmsg_buffer err,
2821  const char *sourcefile, int sourceline)
2822 {
2823  int ret;
2824  rb_encoding *str_enc = rb_enc_get(str), *enc = str_enc;
2825  if (options & ARG_ENCODING_NONE) {
2826  rb_encoding *ascii8bit = rb_ascii8bit_encoding();
2827  if (enc != ascii8bit) {
2828  if (str_coderange(str) != ENC_CODERANGE_7BIT) {
2829  errcpy(err, "/.../n has a non escaped non ASCII character in non ASCII-8BIT script");
2830  return -1;
2831  }
2832  enc = ascii8bit;
2833  }
2834  }
2835  ret = rb_reg_initialize(obj, RSTRING_PTR(str), RSTRING_LEN(str), enc,
2836  options, err, sourcefile, sourceline);
2837  OBJ_INFECT(obj, str);
2838  if (ret == 0) reg_set_source(obj, str, str_enc);
2839  return ret;
2840 }
2841 
2842 static VALUE
2843 rb_reg_s_alloc(VALUE klass)
2844 {
2846 
2847  re->ptr = 0;
2848  RB_OBJ_WRITE(re, &re->src, 0);
2849  re->usecnt = 0;
2850 
2851  return (VALUE)re;
2852 }
2853 
2854 VALUE
2856 {
2857  return rb_reg_s_alloc(rb_cRegexp);
2858 }
2859 
2860 VALUE
2861 rb_reg_new_str(VALUE s, int options)
2862 {
2863  return rb_reg_init_str(rb_reg_alloc(), s, options);
2864 }
2865 
2866 VALUE
2867 rb_reg_init_str(VALUE re, VALUE s, int options)
2868 {
2869  onig_errmsg_buffer err = "";
2870 
2871  if (rb_reg_initialize_str(re, s, options, err, NULL, 0) != 0) {
2872  rb_reg_raise_str(s, options, err);
2873  }
2874 
2875  return re;
2876 }
2877 
2878 static VALUE
2879 rb_reg_init_str_enc(VALUE re, VALUE s, rb_encoding *enc, int options)
2880 {
2881  onig_errmsg_buffer err = "";
2882 
2883  if (rb_reg_initialize(re, RSTRING_PTR(s), RSTRING_LEN(s),
2884  enc, options, err, NULL, 0) != 0) {
2885  rb_reg_raise_str(s, options, err);
2886  }
2887  reg_set_source(re, s, enc);
2888 
2889  return re;
2890 }
2891 
2892 VALUE
2893 rb_reg_new_ary(VALUE ary, int opt)
2894 {
2895  return rb_reg_new_str(rb_reg_preprocess_dregexp(ary, opt), opt);
2896 }
2897 
2898 VALUE
2899 rb_enc_reg_new(const char *s, long len, rb_encoding *enc, int options)
2900 {
2901  VALUE re = rb_reg_alloc();
2902  onig_errmsg_buffer err = "";
2903 
2904  if (rb_reg_initialize(re, s, len, enc, options, err, NULL, 0) != 0) {
2905  rb_enc_reg_raise(s, len, enc, options, err);
2906  }
2907  RB_OBJ_WRITE(re, &RREGEXP(re)->src, rb_fstring(rb_enc_str_new(s, len, enc)));
2908 
2909  return re;
2910 }
2911 
2912 VALUE
2913 rb_reg_new(const char *s, long len, int options)
2914 {
2915  return rb_enc_reg_new(s, len, rb_ascii8bit_encoding(), options);
2916 }
2917 
2918 VALUE
2919 rb_reg_compile(VALUE str, int options, const char *sourcefile, int sourceline)
2920 {
2921  VALUE re = rb_reg_alloc();
2922  onig_errmsg_buffer err = "";
2923 
2924  if (!str) str = rb_str_new(0,0);
2925  if (rb_reg_initialize_str(re, str, options, err, sourcefile, sourceline) != 0) {
2926  rb_set_errinfo(rb_reg_error_desc(str, options, err));
2927  return Qnil;
2928  }
2929  FL_SET(re, REG_LITERAL);
2930  return re;
2931 }
2932 
2933 static VALUE reg_cache;
2934 
2935 VALUE
2937 {
2938  if (reg_cache && RREGEXP_SRC_LEN(reg_cache) == RSTRING_LEN(str)
2939  && ENCODING_GET(reg_cache) == ENCODING_GET(str)
2940  && memcmp(RREGEXP_SRC_PTR(reg_cache), RSTRING_PTR(str), RSTRING_LEN(str)) == 0)
2941  return reg_cache;
2942 
2943  return reg_cache = rb_reg_new_str(str, 0);
2944 }
2945 
2946 static st_index_t reg_hash(VALUE re);
2947 /*
2948  * call-seq:
2949  * rxp.hash -> integer
2950  *
2951  * Produce a hash based on the text and options of this regular expression.
2952  *
2953  * See also Object#hash.
2954  */
2955 
2956 static VALUE
2957 rb_reg_hash(VALUE re)
2958 {
2959  st_index_t hashval = reg_hash(re);
2960  return ST2FIX(hashval);
2961 }
2962 
2963 static st_index_t
2964 reg_hash(VALUE re)
2965 {
2966  st_index_t hashval;
2967 
2968  rb_reg_check(re);
2969  hashval = RREGEXP_PTR(re)->options;
2970  hashval = rb_hash_uint(hashval, rb_memhash(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re)));
2971  return rb_hash_end(hashval);
2972 }
2973 
2974 
2975 /*
2976  * call-seq:
2977  * rxp == other_rxp -> true or false
2978  * rxp.eql?(other_rxp) -> true or false
2979  *
2980  * Equality---Two regexps are equal if their patterns are identical, they have
2981  * the same character set code, and their <code>casefold?</code> values are the
2982  * same.
2983  *
2984  * /abc/ == /abc/x #=> false
2985  * /abc/ == /abc/i #=> false
2986  * /abc/ == /abc/u #=> false
2987  * /abc/u == /abc/n #=> false
2988  */
2989 
2990 static VALUE
2991 rb_reg_equal(VALUE re1, VALUE re2)
2992 {
2993  if (re1 == re2) return Qtrue;
2994  if (!RB_TYPE_P(re2, T_REGEXP)) return Qfalse;
2995  rb_reg_check(re1); rb_reg_check(re2);
2996  if (FL_TEST(re1, KCODE_FIXED) != FL_TEST(re2, KCODE_FIXED)) return Qfalse;
2997  if (RREGEXP_PTR(re1)->options != RREGEXP_PTR(re2)->options) return Qfalse;
2998  if (RREGEXP_SRC_LEN(re1) != RREGEXP_SRC_LEN(re2)) return Qfalse;
2999  if (ENCODING_GET(re1) != ENCODING_GET(re2)) return Qfalse;
3000  if (memcmp(RREGEXP_SRC_PTR(re1), RREGEXP_SRC_PTR(re2), RREGEXP_SRC_LEN(re1)) == 0) {
3001  return Qtrue;
3002  }
3003  return Qfalse;
3004 }
3005 
3006 /*
3007  * call-seq:
3008  * mtch.hash -> integer
3009  *
3010  * Produce a hash based on the target string, regexp and matched
3011  * positions of this matchdata.
3012  *
3013  * See also Object#hash.
3014  */
3015 
3016 static VALUE
3017 match_hash(VALUE match)
3018 {
3019  const struct re_registers *regs;
3020  st_index_t hashval;
3021 
3022  match_check(match);
3023  hashval = rb_hash_start(rb_str_hash(RMATCH(match)->str));
3024  hashval = rb_hash_uint(hashval, reg_hash(match_regexp(match)));
3025  regs = RMATCH_REGS(match);
3026  hashval = rb_hash_uint(hashval, regs->num_regs);
3027  hashval = rb_hash_uint(hashval, rb_memhash(regs->beg, regs->num_regs * sizeof(*regs->beg)));
3028  hashval = rb_hash_uint(hashval, rb_memhash(regs->end, regs->num_regs * sizeof(*regs->end)));
3029  hashval = rb_hash_end(hashval);
3030  return ST2FIX(hashval);
3031 }
3032 
3033 /*
3034  * call-seq:
3035  * mtch == mtch2 -> true or false
3036  * mtch.eql?(mtch2) -> true or false
3037  *
3038  * Equality---Two matchdata are equal if their target strings,
3039  * patterns, and matched positions are identical.
3040  */
3041 
3042 static VALUE
3043 match_equal(VALUE match1, VALUE match2)
3044 {
3045  const struct re_registers *regs1, *regs2;
3046 
3047  if (match1 == match2) return Qtrue;
3048  if (!RB_TYPE_P(match2, T_MATCH)) return Qfalse;
3049  if (!RMATCH(match1)->regexp || !RMATCH(match2)->regexp) return Qfalse;
3050  if (!rb_str_equal(RMATCH(match1)->str, RMATCH(match2)->str)) return Qfalse;
3051  if (!rb_reg_equal(match_regexp(match1), match_regexp(match2))) return Qfalse;
3052  regs1 = RMATCH_REGS(match1);
3053  regs2 = RMATCH_REGS(match2);
3054  if (regs1->num_regs != regs2->num_regs) return Qfalse;
3055  if (memcmp(regs1->beg, regs2->beg, regs1->num_regs * sizeof(*regs1->beg))) return Qfalse;
3056  if (memcmp(regs1->end, regs2->end, regs1->num_regs * sizeof(*regs1->end))) return Qfalse;
3057  return Qtrue;
3058 }
3059 
3060 static VALUE
3061 reg_operand(VALUE s, int check)
3062 {
3063  if (SYMBOL_P(s)) {
3064  return rb_sym2str(s);
3065  }
3066  else {
3067  return (check ? rb_str_to_str : rb_check_string_type)(s);
3068  }
3069 }
3070 
3071 static long
3072 reg_match_pos(VALUE re, VALUE *strp, long pos)
3073 {
3074  VALUE str = *strp;
3075 
3076  if (NIL_P(str)) {
3078  return -1;
3079  }
3080  *strp = str = reg_operand(str, TRUE);
3081  if (pos != 0) {
3082  if (pos < 0) {
3083  VALUE l = rb_str_length(str);
3084  pos += NUM2INT(l);
3085  if (pos < 0) {
3086  return pos;
3087  }
3088  }
3089  pos = rb_str_offset(str, pos);
3090  }
3091  return rb_reg_search(re, str, pos, 0);
3092 }
3093 
3094 /*
3095  * call-seq:
3096  * rxp =~ str -> integer or nil
3097  *
3098  * Match---Matches <i>rxp</i> against <i>str</i>.
3099  *
3100  * /at/ =~ "input data" #=> 7
3101  * /ax/ =~ "input data" #=> nil
3102  *
3103  * If <code>=~</code> is used with a regexp literal with named captures,
3104  * captured strings (or nil) is assigned to local variables named by
3105  * the capture names.
3106  *
3107  * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ " x = y "
3108  * p lhs #=> "x"
3109  * p rhs #=> "y"
3110  *
3111  * If it is not matched, nil is assigned for the variables.
3112  *
3113  * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ " x = "
3114  * p lhs #=> nil
3115  * p rhs #=> nil
3116  *
3117  * This assignment is implemented in the Ruby parser.
3118  * The parser detects 'regexp-literal =~ expression' for the assignment.
3119  * The regexp must be a literal without interpolation and placed at left hand side.
3120  *
3121  * The assignment does not occur if the regexp is not a literal.
3122  *
3123  * re = /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/
3124  * re =~ " x = y "
3125  * p lhs # undefined local variable
3126  * p rhs # undefined local variable
3127  *
3128  * A regexp interpolation, <code>#{}</code>, also disables
3129  * the assignment.
3130  *
3131  * rhs_pat = /(?<rhs>\w+)/
3132  * /(?<lhs>\w+)\s*=\s*#{rhs_pat}/ =~ "x = y"
3133  * p lhs # undefined local variable
3134  *
3135  * The assignment does not occur if the regexp is placed at the right hand side.
3136  *
3137  * " x = y " =~ /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/
3138  * p lhs, rhs # undefined local variable
3139  *
3140  */
3141 
3142 VALUE
3144 {
3145  long pos = reg_match_pos(re, &str, 0);
3146  if (pos < 0) return Qnil;
3147  pos = rb_str_sublen(str, pos);
3148  return LONG2FIX(pos);
3149 }
3150 
3151 /*
3152  * call-seq:
3153  * rxp === str -> true or false
3154  *
3155  * Case Equality---Used in case statements.
3156  *
3157  * a = "HELLO"
3158  * case a
3159  * when /^[a-z]*$/; print "Lower case\n"
3160  * when /^[A-Z]*$/; print "Upper case\n"
3161  * else; print "Mixed case\n"
3162  * end
3163  * #=> "Upper case"
3164  *
3165  * Following a regular expression literal with the #=== operator allows you to
3166  * compare against a String.
3167  *
3168  * /^[a-z]*$/ === "HELLO" #=> false
3169  * /^[A-Z]*$/ === "HELLO" #=> true
3170  */
3171 
3172 VALUE
3174 {
3175  long start;
3176 
3177  str = reg_operand(str, FALSE);
3178  if (NIL_P(str)) {
3180  return Qfalse;
3181  }
3182  start = rb_reg_search(re, str, 0, 0);
3183  if (start < 0) {
3184  return Qfalse;
3185  }
3186  return Qtrue;
3187 }
3188 
3189 
3190 /*
3191  * call-seq:
3192  * ~ rxp -> integer or nil
3193  *
3194  * Match---Matches <i>rxp</i> against the contents of <code>$_</code>.
3195  * Equivalent to <code><i>rxp</i> =~ $_</code>.
3196  *
3197  * $_ = "input data"
3198  * ~ /at/ #=> 7
3199  */
3200 
3201 VALUE
3203 {
3204  long start;
3205  VALUE line = rb_lastline_get();
3206 
3207  if (!RB_TYPE_P(line, T_STRING)) {
3209  return Qnil;
3210  }
3211 
3212  start = rb_reg_search(re, line, 0, 0);
3213  if (start < 0) {
3214  return Qnil;
3215  }
3216  start = rb_str_sublen(line, start);
3217  return LONG2FIX(start);
3218 }
3219 
3220 
3221 /*
3222  * call-seq:
3223  * rxp.match(str) -> matchdata or nil
3224  * rxp.match(str,pos) -> matchdata or nil
3225  *
3226  * Returns a <code>MatchData</code> object describing the match, or
3227  * <code>nil</code> if there was no match. This is equivalent to retrieving the
3228  * value of the special variable <code>$~</code> following a normal match.
3229  * If the second parameter is present, it specifies the position in the string
3230  * to begin the search.
3231  *
3232  * /(.)(.)(.)/.match("abc")[2] #=> "b"
3233  * /(.)(.)/.match("abc", 1)[2] #=> "c"
3234  *
3235  * If a block is given, invoke the block with MatchData if match succeed, so
3236  * that you can write
3237  *
3238  * /M(.*)/.match("Matz") do |m|
3239  * puts m[0]
3240  * puts m[1]
3241  * end
3242  *
3243  * instead of
3244  *
3245  * if m = /M(.*)/.match("Matz")
3246  * puts m[0]
3247  * puts m[1]
3248  * end
3249  *
3250  * The return value is a value from block execution in this case.
3251  */
3252 
3253 static VALUE
3254 rb_reg_match_m(int argc, VALUE *argv, VALUE re)
3255 {
3256  VALUE result, str, initpos;
3257  long pos;
3258 
3259  if (rb_scan_args(argc, argv, "11", &str, &initpos) == 2) {
3260  pos = NUM2LONG(initpos);
3261  }
3262  else {
3263  pos = 0;
3264  }
3265 
3266  pos = reg_match_pos(re, &str, pos);
3267  if (pos < 0) {
3269  return Qnil;
3270  }
3271  result = rb_backref_get();
3272  rb_match_busy(result);
3273  if (!NIL_P(result) && rb_block_given_p()) {
3274  return rb_yield(result);
3275  }
3276  return result;
3277 }
3278 
3279 /*
3280  * call-seq:
3281  * rxp.match?(str) -> true or false
3282  * rxp.match?(str,pos) -> true or false
3283  *
3284  * Returns a <code>true</code> or <code>false</code> indicates whether the
3285  * regexp is matched or not without updating $~ and other related variables.
3286  * If the second parameter is present, it specifies the position in the string
3287  * to begin the search.
3288  *
3289  * /R.../.match?("Ruby") #=> true
3290  * /R.../.match?("Ruby", 1) #=> false
3291  * /P.../.match?("Ruby") #=> false
3292  * $& #=> nil
3293  */
3294 
3295 static VALUE
3296 rb_reg_match_m_p(int argc, VALUE *argv, VALUE re)
3297 {
3298  long pos = rb_check_arity(argc, 1, 2) > 1 ? NUM2LONG(argv[1]) : 0;
3299  return rb_reg_match_p(re, argv[0], pos);
3300 }
3301 
3302 VALUE
3303 rb_reg_match_p(VALUE re, VALUE str, long pos)
3304 {
3305  regex_t *reg;
3306  onig_errmsg_buffer err = "";
3307  OnigPosition result;
3308  const UChar *start, *end;
3309  int tmpreg;
3310 
3311  if (NIL_P(str)) return Qfalse;
3312  str = SYMBOL_P(str) ? rb_sym2str(str) : StringValue(str);
3313  if (pos) {
3314  if (pos < 0) {
3315  pos += NUM2LONG(rb_str_length(str));
3316  if (pos < 0) return Qfalse;
3317  }
3318  if (pos > 0) {
3319  long len = 1;
3320  const char *beg = rb_str_subpos(str, pos, &len);
3321  if (!beg) return Qfalse;
3322  pos = beg - RSTRING_PTR(str);
3323  }
3324  }
3325  reg = rb_reg_prepare_re0(re, str, err);
3326  tmpreg = reg != RREGEXP_PTR(re);
3327  if (!tmpreg) RREGEXP(re)->usecnt++;
3328  start = ((UChar*)RSTRING_PTR(str));
3329  end = start + RSTRING_LEN(str);
3330  result = onig_search(reg, start, end, start + pos, end,
3332  if (!tmpreg) RREGEXP(re)->usecnt--;
3333  if (tmpreg) {
3334  if (RREGEXP(re)->usecnt) {
3335  onig_free(reg);
3336  }
3337  else {
3338  onig_free(RREGEXP_PTR(re));
3339  RREGEXP_PTR(re) = reg;
3340  }
3341  }
3342  if (result < 0) {
3343  if (result == ONIG_MISMATCH) {
3344  return Qfalse;
3345  }
3346  else {
3347  onig_error_code_to_str((UChar*)err, (int)result);
3348  rb_reg_raise(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), err, re);
3349  }
3350  }
3351  return Qtrue;
3352 }
3353 
3354 /*
3355  * Document-method: compile
3356  *
3357  * Alias for <code>Regexp.new</code>
3358  */
3359 
3360 /*
3361  * call-seq:
3362  * Regexp.new(string, [options]) -> regexp
3363  * Regexp.new(regexp) -> regexp
3364  * Regexp.compile(string, [options]) -> regexp
3365  * Regexp.compile(regexp) -> regexp
3366  *
3367  * Constructs a new regular expression from +pattern+, which can be either a
3368  * String or a Regexp (in which case that regexp's options are propagated),
3369  * and new options may not be specified (a change as of Ruby 1.8).
3370  *
3371  * If +options+ is an Integer, it should be one or more of the constants
3372  * Regexp::EXTENDED, Regexp::IGNORECASE, and Regexp::MULTILINE,
3373  * <em>or</em>-ed together. Otherwise, if +options+ is not
3374  * +nil+ or +false+, the regexp will be case insensitive.
3375  *
3376  * r1 = Regexp.new('^a-z+:\\s+\w+') #=> /^a-z+:\s+\w+/
3377  * r2 = Regexp.new('cat', true) #=> /cat/i
3378  * r3 = Regexp.new(r2) #=> /cat/i
3379  * r4 = Regexp.new('dog', Regexp::EXTENDED | Regexp::IGNORECASE) #=> /dog/ix
3380  */
3381 
3382 static VALUE
3383 rb_reg_initialize_m(int argc, VALUE *argv, VALUE self)
3384 {
3385  int flags = 0;
3386  VALUE str;
3387  rb_encoding *enc = 0;
3388 
3389  rb_check_arity(argc, 1, 3);
3390  if (RB_TYPE_P(argv[0], T_REGEXP)) {
3391  VALUE re = argv[0];
3392 
3393  if (argc > 1) {
3394  rb_warn("flags ignored");
3395  }
3396  rb_reg_check(re);
3397  flags = rb_reg_options(re);
3398  str = RREGEXP_SRC(re);
3399  }
3400  else {
3401  if (argc >= 2) {
3402  if (FIXNUM_P(argv[1])) flags = FIX2INT(argv[1]);
3403  else if (RTEST(argv[1])) flags = ONIG_OPTION_IGNORECASE;
3404  }
3405  if (argc == 3 && !NIL_P(argv[2])) {
3406  char *kcode = StringValuePtr(argv[2]);
3407  if (kcode[0] == 'n' || kcode[0] == 'N') {
3408  enc = rb_ascii8bit_encoding();
3409  flags |= ARG_ENCODING_NONE;
3410  }
3411  else {
3412  rb_warn("encoding option is ignored - %s", kcode);
3413  }
3414  }
3415  str = StringValue(argv[0]);
3416  }
3417  if (enc && rb_enc_get(str) != enc)
3418  rb_reg_init_str_enc(self, str, enc, flags);
3419  else
3420  rb_reg_init_str(self, str, flags);
3421  return self;
3422 }
3423 
3424 VALUE
3426 {
3427  rb_encoding *enc = rb_enc_get(str);
3428  char *s, *send, *t;
3429  VALUE tmp;
3430  int c, clen;
3431  int ascii_only = rb_enc_str_asciionly_p(str);
3432 
3433  s = RSTRING_PTR(str);
3434  send = s + RSTRING_LEN(str);
3435  while (s < send) {
3436  c = rb_enc_ascget(s, send, &clen, enc);
3437  if (c == -1) {
3438  s += mbclen(s, send, enc);
3439  continue;
3440  }
3441  switch (c) {
3442  case '[': case ']': case '{': case '}':
3443  case '(': case ')': case '|': case '-':
3444  case '*': case '.': case '\\':
3445  case '?': case '+': case '^': case '$':
3446  case ' ': case '#':
3447  case '\t': case '\f': case '\v': case '\n': case '\r':
3448  goto meta_found;
3449  }
3450  s += clen;
3451  }
3452  tmp = rb_str_new3(str);
3453  if (ascii_only) {
3455  }
3456  return tmp;
3457 
3458  meta_found:
3459  tmp = rb_str_new(0, RSTRING_LEN(str)*2);
3460  if (ascii_only) {
3462  }
3463  else {
3464  rb_enc_copy(tmp, str);
3465  }
3466  t = RSTRING_PTR(tmp);
3467  /* copy upto metacharacter */
3468  memcpy(t, RSTRING_PTR(str), s - RSTRING_PTR(str));
3469  t += s - RSTRING_PTR(str);
3470 
3471  while (s < send) {
3472  c = rb_enc_ascget(s, send, &clen, enc);
3473  if (c == -1) {
3474  int n = mbclen(s, send, enc);
3475 
3476  while (n--)
3477  *t++ = *s++;
3478  continue;
3479  }
3480  s += clen;
3481  switch (c) {
3482  case '[': case ']': case '{': case '}':
3483  case '(': case ')': case '|': case '-':
3484  case '*': case '.': case '\\':
3485  case '?': case '+': case '^': case '$':
3486  case '#':
3487  t += rb_enc_mbcput('\\', t, enc);
3488  break;
3489  case ' ':
3490  t += rb_enc_mbcput('\\', t, enc);
3491  t += rb_enc_mbcput(' ', t, enc);
3492  continue;
3493  case '\t':
3494  t += rb_enc_mbcput('\\', t, enc);
3495  t += rb_enc_mbcput('t', t, enc);
3496  continue;
3497  case '\n':
3498  t += rb_enc_mbcput('\\', t, enc);
3499  t += rb_enc_mbcput('n', t, enc);
3500  continue;
3501  case '\r':
3502  t += rb_enc_mbcput('\\', t, enc);
3503  t += rb_enc_mbcput('r', t, enc);
3504  continue;
3505  case '\f':
3506  t += rb_enc_mbcput('\\', t, enc);
3507  t += rb_enc_mbcput('f', t, enc);
3508  continue;
3509  case '\v':
3510  t += rb_enc_mbcput('\\', t, enc);
3511  t += rb_enc_mbcput('v', t, enc);
3512  continue;
3513  }
3514  t += rb_enc_mbcput(c, t, enc);
3515  }
3516  rb_str_resize(tmp, t - RSTRING_PTR(tmp));
3517  OBJ_INFECT(tmp, str);
3518  return tmp;
3519 }
3520 
3521 
3522 /*
3523  * call-seq:
3524  * Regexp.escape(str) -> string
3525  * Regexp.quote(str) -> string
3526  *
3527  * Escapes any characters that would have special meaning in a regular
3528  * expression. Returns a new escaped string, or self if no characters are
3529  * escaped. For any string,
3530  * <code>Regexp.new(Regexp.escape(<i>str</i>))=~<i>str</i></code> will be true.
3531  *
3532  * Regexp.escape('\*?{}.') #=> \\\*\?\{\}\.
3533  *
3534  */
3535 
3536 static VALUE
3537 rb_reg_s_quote(VALUE c, VALUE str)
3538 {
3539  return rb_reg_quote(reg_operand(str, TRUE));
3540 }
3541 
3542 int
3544 {
3545  int options;
3546 
3547  rb_reg_check(re);
3548  options = RREGEXP_PTR(re)->options & ARG_REG_OPTION_MASK;
3549  if (RBASIC(re)->flags & KCODE_FIXED) options |= ARG_ENCODING_FIXED;
3550  if (RBASIC(re)->flags & REG_ENCODING_NONE) options |= ARG_ENCODING_NONE;
3551  return options;
3552 }
3553 
3554 VALUE
3556 {
3557  return rb_check_convert_type(re, T_REGEXP, "Regexp", "to_regexp");
3558 }
3559 
3560 /*
3561  * call-seq:
3562  * Regexp.try_convert(obj) -> re or nil
3563  *
3564  * Try to convert <i>obj</i> into a Regexp, using to_regexp method.
3565  * Returns converted regexp or nil if <i>obj</i> cannot be converted
3566  * for any reason.
3567  *
3568  * Regexp.try_convert(/re/) #=> /re/
3569  * Regexp.try_convert("re") #=> nil
3570  *
3571  * o = Object.new
3572  * Regexp.try_convert(o) #=> nil
3573  * def o.to_regexp() /foo/ end
3574  * Regexp.try_convert(o) #=> /foo/
3575  *
3576  */
3577 static VALUE
3578 rb_reg_s_try_convert(VALUE dummy, VALUE re)
3579 {
3580  return rb_check_regexp_type(re);
3581 }
3582 
3583 static VALUE
3584 rb_reg_s_union(VALUE self, VALUE args0)
3585 {
3586  long argc = RARRAY_LEN(args0);
3587 
3588  if (argc == 0) {
3589  VALUE args[1];
3590  args[0] = rb_str_new2("(?!)");
3591  return rb_class_new_instance(1, args, rb_cRegexp);
3592  }
3593  else if (argc == 1) {
3594  VALUE arg = rb_ary_entry(args0, 0);
3595  VALUE re = rb_check_regexp_type(arg);
3596  if (!NIL_P(re))
3597  return re;
3598  else {
3599  VALUE quoted;
3600  quoted = rb_reg_s_quote(Qnil, arg);
3601  return rb_reg_new_str(quoted, 0);
3602  }
3603  }
3604  else {
3605  int i;
3606  VALUE source = rb_str_buf_new(0);
3607  rb_encoding *result_enc;
3608 
3609  int has_asciionly = 0;
3610  rb_encoding *has_ascii_compat_fixed = 0;
3611  rb_encoding *has_ascii_incompat = 0;
3612 
3613  for (i = 0; i < argc; i++) {
3614  volatile VALUE v;
3615  VALUE e = rb_ary_entry(args0, i);
3616 
3617  if (0 < i)
3618  rb_str_buf_cat_ascii(source, "|");
3619 
3620  v = rb_check_regexp_type(e);
3621  if (!NIL_P(v)) {
3622  rb_encoding *enc = rb_enc_get(v);
3623  if (!rb_enc_asciicompat(enc)) {
3624  if (!has_ascii_incompat)
3625  has_ascii_incompat = enc;
3626  else if (has_ascii_incompat != enc)
3627  rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
3628  rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
3629  }
3630  else if (rb_reg_fixed_encoding_p(v)) {
3631  if (!has_ascii_compat_fixed)
3632  has_ascii_compat_fixed = enc;
3633  else if (has_ascii_compat_fixed != enc)
3634  rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
3635  rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
3636  }
3637  else {
3638  has_asciionly = 1;
3639  }
3640  v = rb_reg_to_s(v);
3641  }
3642  else {
3643  rb_encoding *enc;
3644  StringValue(e);
3645  enc = rb_enc_get(e);
3646  if (!rb_enc_asciicompat(enc)) {
3647  if (!has_ascii_incompat)
3648  has_ascii_incompat = enc;
3649  else if (has_ascii_incompat != enc)
3650  rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
3651  rb_enc_name(has_ascii_incompat), rb_enc_name(enc));
3652  }
3653  else if (rb_enc_str_asciionly_p(e)) {
3654  has_asciionly = 1;
3655  }
3656  else {
3657  if (!has_ascii_compat_fixed)
3658  has_ascii_compat_fixed = enc;
3659  else if (has_ascii_compat_fixed != enc)
3660  rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
3661  rb_enc_name(has_ascii_compat_fixed), rb_enc_name(enc));
3662  }
3663  v = rb_reg_s_quote(Qnil, e);
3664  }
3665  if (has_ascii_incompat) {
3666  if (has_asciionly) {
3667  rb_raise(rb_eArgError, "ASCII incompatible encoding: %s",
3668  rb_enc_name(has_ascii_incompat));
3669  }
3670  if (has_ascii_compat_fixed) {
3671  rb_raise(rb_eArgError, "incompatible encodings: %s and %s",
3672  rb_enc_name(has_ascii_incompat), rb_enc_name(has_ascii_compat_fixed));
3673  }
3674  }
3675 
3676  if (i == 0) {
3677  rb_enc_copy(source, v);
3678  }
3679  rb_str_append(source, v);
3680  }
3681 
3682  if (has_ascii_incompat) {
3683  result_enc = has_ascii_incompat;
3684  }
3685  else if (has_ascii_compat_fixed) {
3686  result_enc = has_ascii_compat_fixed;
3687  }
3688  else {
3689  result_enc = rb_ascii8bit_encoding();
3690  }
3691 
3692  rb_enc_associate(source, result_enc);
3693  return rb_class_new_instance(1, &source, rb_cRegexp);
3694  }
3695 }
3696 
3697 /*
3698  * call-seq:
3699  * Regexp.union(pat1, pat2, ...) -> new_regexp
3700  * Regexp.union(pats_ary) -> new_regexp
3701  *
3702  * Return a <code>Regexp</code> object that is the union of the given
3703  * <em>pattern</em>s, i.e., will match any of its parts. The <em>pattern</em>s
3704  * can be Regexp objects, in which case their options will be preserved, or
3705  * Strings. If no patterns are given, returns <code>/(?!)/</code>.
3706  * The behavior is unspecified if any given <em>pattern</em> contains capture.
3707  *
3708  * Regexp.union #=> /(?!)/
3709  * Regexp.union("penzance") #=> /penzance/
3710  * Regexp.union("a+b*c") #=> /a\+b\*c/
3711  * Regexp.union("skiing", "sledding") #=> /skiing|sledding/
3712  * Regexp.union(["skiing", "sledding"]) #=> /skiing|sledding/
3713  * Regexp.union(/dogs/, /cats/i) #=> /(?-mix:dogs)|(?i-mx:cats)/
3714  *
3715  * Note: the arguments for ::union will try to be converted into a regular
3716  * expression literal via #to_regexp.
3717  */
3718 static VALUE
3719 rb_reg_s_union_m(VALUE self, VALUE args)
3720 {
3721  VALUE v;
3722  if (RARRAY_LEN(args) == 1 &&
3723  !NIL_P(v = rb_check_array_type(rb_ary_entry(args, 0)))) {
3724  return rb_reg_s_union(self, v);
3725  }
3726  return rb_reg_s_union(self, args);
3727 }
3728 
3729 /* :nodoc: */
3730 static VALUE
3731 rb_reg_init_copy(VALUE copy, VALUE re)
3732 {
3733  if (!OBJ_INIT_COPY(copy, re)) return copy;
3734  rb_reg_check(re);
3735  return rb_reg_init_str(copy, RREGEXP_SRC(re), rb_reg_options(re));
3736 }
3737 
3738 VALUE
3739 rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp)
3740 {
3741  VALUE val = 0;
3742  char *p, *s, *e;
3743  int no, clen;
3744  rb_encoding *str_enc = rb_enc_get(str);
3745  rb_encoding *src_enc = rb_enc_get(src);
3746  int acompat = rb_enc_asciicompat(str_enc);
3747 #define ASCGET(s,e,cl) (acompat ? (*(cl)=1,ISASCII((s)[0])?(s)[0]:-1) : rb_enc_ascget((s), (e), (cl), str_enc))
3748 
3749  p = s = RSTRING_PTR(str);
3750  e = s + RSTRING_LEN(str);
3751 
3752  while (s < e) {
3753  int c = ASCGET(s, e, &clen);
3754  char *ss;
3755 
3756  if (c == -1) {
3757  s += mbclen(s, e, str_enc);
3758  continue;
3759  }
3760  ss = s;
3761  s += clen;
3762 
3763  if (c != '\\' || s == e) continue;
3764 
3765  if (!val) {
3766  val = rb_str_buf_new(ss-p);
3767  }
3768  rb_enc_str_buf_cat(val, p, ss-p, str_enc);
3769 
3770  c = ASCGET(s, e, &clen);
3771  if (c == -1) {
3772  s += mbclen(s, e, str_enc);
3773  rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
3774  p = s;
3775  continue;
3776  }
3777  s += clen;
3778 
3779  p = s;
3780  switch (c) {
3781  case '1': case '2': case '3': case '4':
3782  case '5': case '6': case '7': case '8': case '9':
3783  if (!NIL_P(regexp) && onig_noname_group_capture_is_active(RREGEXP_PTR(regexp))) {
3784  no = c - '0';
3785  }
3786  else {
3787  continue;
3788  }
3789  break;
3790 
3791  case 'k':
3792  if (s < e && ASCGET(s, e, &clen) == '<') {
3793  char *name, *name_end;
3794 
3795  name_end = name = s + clen;
3796  while (name_end < e) {
3797  c = ASCGET(name_end, e, &clen);
3798  if (c == '>') break;
3799  name_end += c == -1 ? mbclen(name_end, e, str_enc) : clen;
3800  }
3801  if (name_end < e) {
3802  VALUE n = rb_str_subseq(str, (long)(name - RSTRING_PTR(str)),
3803  (long)(name_end - name));
3804  if ((no = NAME_TO_NUMBER(regs, regexp, n, name, name_end)) < 1) {
3805  name_to_backref_error(n);
3806  }
3807  p = s = name_end + clen;
3808  break;
3809  }
3810  else {
3811  rb_raise(rb_eRuntimeError, "invalid group name reference format");
3812  }
3813  }
3814 
3815  rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
3816  continue;
3817 
3818  case '0':
3819  case '&':
3820  no = 0;
3821  break;
3822 
3823  case '`':
3824  rb_enc_str_buf_cat(val, RSTRING_PTR(src), BEG(0), src_enc);
3825  continue;
3826 
3827  case '\'':
3828  rb_enc_str_buf_cat(val, RSTRING_PTR(src)+END(0), RSTRING_LEN(src)-END(0), src_enc);
3829  continue;
3830 
3831  case '+':
3832  no = regs->num_regs-1;
3833  while (BEG(no) == -1 && no > 0) no--;
3834  if (no == 0) continue;
3835  break;
3836 
3837  case '\\':
3838  rb_enc_str_buf_cat(val, s-clen, clen, str_enc);
3839  continue;
3840 
3841  default:
3842  rb_enc_str_buf_cat(val, ss, s-ss, str_enc);
3843  continue;
3844  }
3845 
3846  if (no >= 0) {
3847  if (no >= regs->num_regs) continue;
3848  if (BEG(no) == -1) continue;
3849  rb_enc_str_buf_cat(val, RSTRING_PTR(src)+BEG(no), END(no)-BEG(no), src_enc);
3850  }
3851  }
3852 
3853  if (!val) return str;
3854  if (p < e) {
3855  rb_enc_str_buf_cat(val, p, e-p, str_enc);
3856  }
3857 
3858  return val;
3859 }
3860 
3861 static VALUE
3862 kcode_getter(void)
3863 {
3864  rb_warn("variable $KCODE is no longer effective");
3865  return Qnil;
3866 }
3867 
3868 static void
3869 kcode_setter(VALUE val, ID id)
3870 {
3871  rb_warn("variable $KCODE is no longer effective; ignored");
3872 }
3873 
3874 static VALUE
3875 ignorecase_getter(void)
3876 {
3877  rb_warn("variable $= is no longer effective");
3878  return Qfalse;
3879 }
3880 
3881 static void
3882 ignorecase_setter(VALUE val, ID id)
3883 {
3884  rb_warn("variable $= is no longer effective; ignored");
3885 }
3886 
3887 static VALUE
3888 match_getter(void)
3889 {
3890  VALUE match = rb_backref_get();
3891 
3892  if (NIL_P(match)) return Qnil;
3893  rb_match_busy(match);
3894  return match;
3895 }
3896 
3897 static void
3898 match_setter(VALUE val)
3899 {
3900  if (!NIL_P(val)) {
3901  Check_Type(val, T_MATCH);
3902  }
3903  rb_backref_set(val);
3904 }
3905 
3906 /*
3907  * call-seq:
3908  * Regexp.last_match -> matchdata
3909  * Regexp.last_match(n) -> str
3910  *
3911  * The first form returns the MatchData object generated by the
3912  * last successful pattern match. Equivalent to reading the special global
3913  * variable <code>$~</code> (see Special global variables in Regexp for
3914  * details).
3915  *
3916  * The second form returns the <i>n</i>th field in this MatchData object.
3917  * _n_ can be a string or symbol to reference a named capture.
3918  *
3919  * Note that the last_match is local to the thread and method scope of the
3920  * method that did the pattern match.
3921  *
3922  * /c(.)t/ =~ 'cat' #=> 0
3923  * Regexp.last_match #=> #<MatchData "cat" 1:"a">
3924  * Regexp.last_match(0) #=> "cat"
3925  * Regexp.last_match(1) #=> "a"
3926  * Regexp.last_match(2) #=> nil
3927  *
3928  * /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ "var = val"
3929  * Regexp.last_match #=> #<MatchData "var = val" lhs:"var" rhs:"val">
3930  * Regexp.last_match(:lhs) #=> "var"
3931  * Regexp.last_match(:rhs) #=> "val"
3932  */
3933 
3934 static VALUE
3935 rb_reg_s_last_match(int argc, VALUE *argv)
3936 {
3937  VALUE nth;
3938 
3939  if (argc > 0 && rb_scan_args(argc, argv, "01", &nth) == 1) {
3940  VALUE match = rb_backref_get();
3941  int n;
3942  if (NIL_P(match)) return Qnil;
3943  n = match_backref_number(match, nth);
3944  return rb_reg_nth_match(n, match);
3945  }
3946  return match_getter();
3947 }
3948 
3949 static void
3950 re_warn(const char *s)
3951 {
3952  rb_warn("%s", s);
3953 }
3954 
3955 /*
3956  * Document-class: RegexpError
3957  *
3958  * Raised when given an invalid regexp expression.
3959  *
3960  * Regexp.new("?")
3961  *
3962  * <em>raises the exception:</em>
3963  *
3964  * RegexpError: target of repeat operator is not specified: /?/
3965  */
3966 
3967 /*
3968  * Document-class: Regexp
3969  *
3970  * A <code>Regexp</code> holds a regular expression, used to match a pattern
3971  * against strings. Regexps are created using the <code>/.../</code> and
3972  * <code>%r{...}</code> literals, and by the <code>Regexp::new</code>
3973  * constructor.
3974  *
3975  * :include: doc/regexp.rdoc
3976  */
3977 
3978 void
3980 {
3982 
3984  onig_set_warn_func(re_warn);
3985  onig_set_verb_warn_func(re_warn);
3986 
3987  rb_define_virtual_variable("$~", match_getter, match_setter);
3988  rb_define_virtual_variable("$&", last_match_getter, 0);
3989  rb_define_virtual_variable("$`", prematch_getter, 0);
3990  rb_define_virtual_variable("$'", postmatch_getter, 0);
3991  rb_define_virtual_variable("$+", last_paren_match_getter, 0);
3992 
3993  rb_define_virtual_variable("$=", ignorecase_getter, ignorecase_setter);
3994  rb_define_virtual_variable("$KCODE", kcode_getter, kcode_setter);
3995  rb_define_virtual_variable("$-K", kcode_getter, kcode_setter);
3996 
3997  rb_cRegexp = rb_define_class("Regexp", rb_cObject);
3998  rb_define_alloc_func(rb_cRegexp, rb_reg_s_alloc);
4000  rb_define_singleton_method(rb_cRegexp, "quote", rb_reg_s_quote, 1);
4001  rb_define_singleton_method(rb_cRegexp, "escape", rb_reg_s_quote, 1);
4002  rb_define_singleton_method(rb_cRegexp, "union", rb_reg_s_union_m, -2);
4003  rb_define_singleton_method(rb_cRegexp, "last_match", rb_reg_s_last_match, -1);
4004  rb_define_singleton_method(rb_cRegexp, "try_convert", rb_reg_s_try_convert, 1);
4005 
4006  rb_define_method(rb_cRegexp, "initialize", rb_reg_initialize_m, -1);
4007  rb_define_method(rb_cRegexp, "initialize_copy", rb_reg_init_copy, 1);
4008  rb_define_method(rb_cRegexp, "hash", rb_reg_hash, 0);
4009  rb_define_method(rb_cRegexp, "eql?", rb_reg_equal, 1);
4010  rb_define_method(rb_cRegexp, "==", rb_reg_equal, 1);
4014  rb_define_method(rb_cRegexp, "match", rb_reg_match_m, -1);
4015  rb_define_method(rb_cRegexp, "match?", rb_reg_match_m_p, -1);
4016  rb_define_method(rb_cRegexp, "to_s", rb_reg_to_s, 0);
4017  rb_define_method(rb_cRegexp, "inspect", rb_reg_inspect, 0);
4018  rb_define_method(rb_cRegexp, "source", rb_reg_source, 0);
4019  rb_define_method(rb_cRegexp, "casefold?", rb_reg_casefold_p, 0);
4020  rb_define_method(rb_cRegexp, "options", rb_reg_options_m, 0);
4021  rb_define_method(rb_cRegexp, "encoding", rb_obj_encoding, 0); /* in encoding.c */
4022  rb_define_method(rb_cRegexp, "fixed_encoding?", rb_reg_fixed_encoding_p, 0);
4023  rb_define_method(rb_cRegexp, "names", rb_reg_names, 0);
4024  rb_define_method(rb_cRegexp, "named_captures", rb_reg_named_captures, 0);
4025 
4026  /* see Regexp.options and Regexp.new */
4028  /* see Regexp.options and Regexp.new */
4030  /* see Regexp.options and Regexp.new */
4032  /* see Regexp.options and Regexp.new */
4034  /* see Regexp.options and Regexp.new */
4036 
4037  rb_global_variable(&reg_cache);
4038 
4039  rb_cMatch = rb_define_class("MatchData", rb_cObject);
4040  rb_define_alloc_func(rb_cMatch, match_alloc);
4042 
4043  rb_define_method(rb_cMatch, "initialize_copy", match_init_copy, 1);
4044  rb_define_method(rb_cMatch, "regexp", match_regexp, 0);
4045  rb_define_method(rb_cMatch, "names", match_names, 0);
4046  rb_define_method(rb_cMatch, "size", match_size, 0);
4047  rb_define_method(rb_cMatch, "length", match_size, 0);
4048  rb_define_method(rb_cMatch, "offset", match_offset, 1);
4049  rb_define_method(rb_cMatch, "begin", match_begin, 1);
4050  rb_define_method(rb_cMatch, "end", match_end, 1);
4051  rb_define_method(rb_cMatch, "to_a", match_to_a, 0);
4052  rb_define_method(rb_cMatch, "[]", match_aref, -1);
4053  rb_define_method(rb_cMatch, "captures", match_captures, 0);
4054  rb_define_method(rb_cMatch, "named_captures", match_named_captures, 0);
4055  rb_define_method(rb_cMatch, "values_at", match_values_at, -1);
4056  rb_define_method(rb_cMatch, "pre_match", rb_reg_match_pre, 0);
4057  rb_define_method(rb_cMatch, "post_match", rb_reg_match_post, 0);
4058  rb_define_method(rb_cMatch, "to_s", match_to_s, 0);
4059  rb_define_method(rb_cMatch, "inspect", match_inspect, 0);
4060  rb_define_method(rb_cMatch, "string", match_string, 0);
4061  rb_define_method(rb_cMatch, "hash", match_hash, 0);
4062  rb_define_method(rb_cMatch, "eql?", match_equal, 1);
4063  rb_define_method(rb_cMatch, "==", match_equal, 1);
4064 }
unsigned int OnigOptionType
Definition: onigmo.h:445
VALUE rb_reg_match(VALUE re, VALUE str)
Definition: re.c:3143
void rb_gc(void)
Definition: gc.c:6727
ONIG_EXTERN int onig_foreach_name(OnigRegex reg, int(*func)(const OnigUChar *, const OnigUChar *, int, int *, OnigRegex, void *), void *arg)
ONIG_EXTERN int onigenc_set_default_encoding(OnigEncoding enc)
Definition: regenc.c:48
#define ASCGET(s, e, cl)
Definition: re.h:44
#define IS_NULL(p)
Definition: regint.h:298
int onig_compile_ruby(regex_t *reg, const UChar *pattern, const UChar *pattern_end, OnigErrorInfo *einfo, const char *sourcefile, int sourceline)
Definition: regcomp.c:5707
#define MBCLEN_CHARFOUND_P(ret)
Definition: encoding.h:185
#define ONIGENC_MBC_MAXLEN(enc)
Definition: onigmo.h:362
void rb_warn(const char *fmt,...)
Definition: error.c:246
VALUE regexp
Definition: re.h:48
void rb_bug(const char *fmt,...)
Definition: error.c:521
#define rb_str_new4
Definition: intern.h:837
ONIG_EXTERN OnigUChar * onigenc_get_right_adjust_char_head(OnigEncoding enc, const OnigUChar *start, const OnigUChar *s, const OnigUChar *end)
VALUE rb_str_length(VALUE)
Definition: string.c:1803
VALUE rb_ary_entry(VALUE ary, long offset)
Definition: array.c:1215
#define MBCLEN_CHARFOUND_LEN(ret)
Definition: encoding.h:186
#define RARRAY_LEN(a)
Definition: ruby.h:1019
#define rb_enc_mbc_to_codepoint(p, e, enc)
Definition: encoding.h:202
VALUE rb_ary_new_capa(long capa)
Definition: array.c:493
#define FALSE
Definition: nkf.h:174
void rb_enc_copy(VALUE obj1, VALUE obj2)
Definition: encoding.c:978
VALUE rb_str_equal(VALUE str1, VALUE str2)
Definition: string.c:3214
long rb_str_coderange_scan_restartable(const char *, const char *, rb_encoding *, int *)
Definition: string.c:531
size_t strlen(const char *)
#define ONIG_MISMATCH
Definition: onigmo.h:625
#define INT2NUM(x)
Definition: ruby.h:1538
const VALUE v2
Definition: internal.h:949
#define scan_oct(s, l, e)
Definition: util.h:53
void rb_backref_set(VALUE)
Definition: vm.c:1235
#define T_MATCH
Definition: ruby.h:507
void rb_define_virtual_variable(const char *, VALUE(*)(ANYARGS), void(*)(ANYARGS))
Definition: variable.c:648
#define NUM2INT(x)
Definition: ruby.h:684
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1716
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition: eval.c:835
#define ENCINDEX_EUC_JP
Definition: encindex.h:52
#define FL_TAINT
Definition: ruby.h:1213
#define CLASS_OF(v)
Definition: ruby.h:453
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2284
ONIG_EXTERN int onig_number_of_names(const OnigRegexType *reg)
Definition: regparse.c:623
#define Qtrue
Definition: ruby.h:437
ONIG_EXTERN int onig_new(OnigRegex *, const OnigUChar *pattern, const OnigUChar *pattern_end, OnigOptionType option, OnigEncoding enc, const OnigSyntaxType *syntax, OnigErrorInfo *einfo)
st_index_t rb_hash_end(st_index_t)
#define ARG_ENCODING_FIXED
Definition: re.c:287
#define OBJ_INIT_COPY(obj, orig)
Definition: intern.h:283
OnigPosition * end
Definition: onigmo.h:718
#define ONIGENC_CASE_FOLD_DEFAULT
Definition: onigmo.h:131
int rb_enc_dummy_p(rb_encoding *enc)
Definition: encoding.c:132
regex_t * rb_reg_prepare_re0(VALUE re, VALUE str, onig_errmsg_buffer err)
Definition: re.c:1412
#define MEMO_CAST(m)
Definition: internal.h:961
VALUE rb_eEncCompatError
Definition: error.c:808
#define RGENGC_WB_PROTECTED_REGEXP
Definition: ruby.h:786
#define REG_ENCODING_NONE
Definition: re.c:281
VALUE rb_enc_from_encoding(rb_encoding *encoding)
Definition: encoding.c:117
#define rb_check_arity
Definition: intern.h:298
st_table * names
Definition: encoding.c:58
#define ONIG_ENCODING_ASCII
Definition: onigmo.h:225
rb_encoding * rb_default_internal_encoding(void)
Definition: encoding.c:1510
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:924
#define RREGEXP_PTR(r)
Definition: ruby.h:1049
VALUE rb_str_buf_new2(const char *)
st_index_t rb_memhash(const void *ptr, long len)
Definition: random.c:1512
ONIG_EXTERN void onig_region_free(OnigRegion *region, int free_self)
Definition: regexec.c:341
int rb_reg_region_copy(struct re_registers *to, const struct re_registers *from)
Definition: re.c:904
VALUE rb_backref_get(void)
Definition: vm.c:1229
ptrdiff_t OnigPosition
Definition: onigmo.h:83
int rb_enc_str_coderange(VALUE)
Definition: string.c:621
#define Check_Type(v, t)
Definition: ruby.h:562
VALUE rb_enc_associate(VALUE obj, rb_encoding *enc)
Definition: encoding.c:854
struct re_registers regs
Definition: re.h:37
long byte_pos
Definition: re.c:915
VALUE rb_reg_regsub(VALUE str, VALUE src, struct re_registers *regs, VALUE regexp)
Definition: re.c:3739
#define RB_GC_GUARD(v)
Definition: ruby.h:552
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
NORETURN(static void name_to_backref_error(VALUE name))
ONIG_EXTERN void onig_free(OnigRegex)
VALUE rb_check_convert_type(VALUE, int, const char *, const char *)
Tries to convert an object into another type.
Definition: object.c:3006
int rb_reg_backref_number(VALUE match, VALUE backref)
Definition: re.c:1138
st_index_t rb_str_hash(VALUE)
Definition: string.c:3094
char * rb_str_subpos(VALUE, long, long *)
Definition: string.c:2430
#define ONIG_OPTION_IGNORECASE
Definition: onigmo.h:451
#define FL_UNSET(x, f)
Definition: ruby.h:1290
st_data_t st_index_t
Definition: st.h:50
VALUE rb_range_beg_len(VALUE, long *, long *, long, int)
Definition: range.c:1003
Definition: re.c:914
#define rb_enc_mbmaxlen(enc)
Definition: encoding.h:175
int char_offset_num_allocated
Definition: re.h:40
#define MEMO_NEW(a, b, c)
Definition: internal.h:963
#define FIXNUM_P(f)
Definition: ruby.h:365
VALUE rb_hash_new_with_size(st_index_t size)
Definition: hash.c:430
rb_encoding * rb_utf8_encoding(void)
Definition: encoding.c:1320
#define ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, start, s, end)
Definition: onigmo.h:336
#define FL_TEST(x, f)
Definition: ruby.h:1282
void rb_undef_method(VALUE klass, const char *name)
Definition: class.c:1533
VALUE rb_str_buf_append(VALUE, VALUE)
Definition: string.c:2884
long rb_reg_search0(VALUE re, VALUE str, long pos, int reverse, int set_backref_str)
Definition: re.c:1489
#define ENC_CODERANGE_7BIT
Definition: encoding.h:100
#define rb_ary_new2
Definition: intern.h:90
ONIG_EXTERN int onig_error_code_to_str(OnigUChar *s, OnigPosition err_code,...)
VALUE rb_eArgError
Definition: error.c:802
const UChar * name
Definition: re.c:2181
VALUE rb_reg_init_str(VALUE re, VALUE s, int options)
Definition: re.c:2867
ONIG_EXTERN int onig_noname_group_capture_is_active(const OnigRegexType *reg)
Definition: regparse.c:963
VALUE rb_str_buf_cat(VALUE, const char *, long)
#define NEWOBJ_OF(obj, type, klass, flags)
Definition: ruby.h:754
long rb_reg_search(VALUE re, VALUE str, long pos, int reverse)
Definition: re.c:1578
void rb_global_variable(VALUE *var)
Definition: gc.c:6276
VALUE rb_reg_new_str(VALUE s, int options)
Definition: re.c:2861
long beg
Definition: re.h:32
ONIG_EXTERN int onig_reg_init(OnigRegex reg, OnigOptionType option, OnigCaseFoldType case_fold_flag, OnigEncoding enc, const OnigSyntaxType *syntax)
VALUE rb_obj_class(VALUE)
call-seq: obj.class -> class
Definition: object.c:277
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
VALUE rb_reg_last_match(VALUE match)
Definition: re.c:1705
#define MEMZERO(p, type, n)
Definition: ruby.h:1660
const VALUE src
Definition: ruby.h:1046
VALUE rb_lastline_get(void)
Definition: vm.c:1241
rb_encoding * rb_default_external_encoding(void)
Definition: encoding.c:1425
VALUE rb_reg_match_post(VALUE match)
Definition: re.c:1750
regex_t * rb_reg_prepare_re(VALUE re, VALUE str)
Definition: re.c:1450
#define scan_hex(s, l, e)
Definition: util.h:55
int rb_match_nth_defined(int nth, VALUE match)
Definition: re.c:1268
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Definition: hash.c:1616
ONIG_EXTERN void onig_set_verb_warn_func(OnigWarnFunc f)
Definition: regparse.c:106
#define val
#define RREGEXP_SRC_PTR(r)
Definition: ruby.h:1051
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1893
VALUE rb_reg_new_ary(VALUE ary, int opt)
Definition: re.c:2893
#define MBCLEN_NEEDMORE_P(ret)
Definition: encoding.h:188
#define RSTRING_END(str)
Definition: ruby.h:979
void Init_Regexp(void)
Definition: re.c:3979
void rb_set_errinfo(VALUE err)
Sets the current exception ($!) to the given value.
Definition: eval.c:1792
#define mbclen(p, e, enc)
Definition: regex.h:33
#define FL_SET(x, f)
Definition: ruby.h:1288
VALUE rb_str_buf_cat2(VALUE, const char *)
ONIG_EXTERN int onig_name_to_backref_number(OnigRegex reg, const OnigUChar *name, const OnigUChar *name_end, const OnigRegion *region)
int rb_ascii8bit_encindex(void)
Definition: encoding.c:1314
VALUE rb_any_to_s(VALUE)
call-seq: obj.to_s -> string
Definition: object.c:631
VALUE rb_eIndexError
Definition: error.c:803
#define snprintf
Definition: subst.h:6
#define ONIG_MAX_ERROR_MESSAGE_LEN
Definition: onigmo.h:443
#define NIL_P(v)
Definition: ruby.h:451
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:646
VALUE rb_reg_nth_match(int nth, VALUE match)
Definition: re.c:1679
#define ENC_CODERANGE_CLEAN_P(cr)
Definition: encoding.h:103
void rb_define_const(VALUE, const char *, VALUE)
Definition: variable.c:2691
void rb_ary_store(VALUE ary, long idx, VALUE val)
Definition: array.c:815
MEMO.
Definition: internal.h:945
int argc
Definition: ruby.c:187
unsigned char OnigUChar
Definition: onigmo.h:79
#define Qfalse
Definition: ruby.h:436
#define ALLOCA_N(type, n)
Definition: ruby.h:1593
int rb_uv_to_utf8(char[6], unsigned long)
Definition: pack.c:1893
bool rb_reg_start_with_p(VALUE re, VALUE str)
Definition: re.c:1584
#define range(low, item, hi)
Definition: date_strftime.c:21
#define ENC_CODERANGE_UNKNOWN
Definition: encoding.h:99
#define rb_enc_isprint(c, enc)
Definition: encoding.h:230
#define MEMCPY(p1, p2, type, n)
Definition: ruby.h:1661
#define ENC_CODERANGE_BROKEN
Definition: encoding.h:102
#define rb_str_new2
Definition: intern.h:835
int err
Definition: win32.c:135
VALUE rb_cMatch
Definition: re.c:888
void rb_match_busy(VALUE match)
Definition: re.c:1252
#define rb_enc_mbminlen(enc)
Definition: encoding.h:174
VALUE rb_check_regexp_type(VALUE re)
Definition: re.c:3555
#define UChar
Definition: onigmo.h:76
#define ONIG_OPTION_EXTEND
Definition: onigmo.h:452
VALUE rb_reg_match2(VALUE re)
Definition: re.c:3202
#define END(no)
Definition: re.c:25
VALUE rb_str_resize(VALUE, long)
Definition: string.c:2644
long rb_str_offset(VALUE, long)
Definition: string.c:2348
int rb_reg_options(VALUE re)
Definition: re.c:3543
int rb_enc_ascget(const char *p, const char *e, int *len, rb_encoding *enc)
Definition: encoding.c:1032
long rb_memsearch(const void *x0, long m, const void *y0, long n, rb_encoding *enc)
Definition: re.c:244
VALUE rb_str_subseq(VALUE, long, long)
Definition: string.c:2406
#define NAME_TO_NUMBER(regs, re, name, name_ptr, name_end)
Definition: re.c:1898
struct re_pattern_buffer * ptr
Definition: ruby.h:1045
#define ZALLOC(type)
Definition: ruby.h:1590
#define RSTRING_LEN(str)
Definition: ruby.h:971
VALUE rb_yield(VALUE)
Definition: vm_eval.c:973
#define REALLOC_N(var, type, n)
Definition: ruby.h:1591
#define TRUE
Definition: nkf.h:175
VALUE rb_sprintf(const char *format,...)
Definition: sprintf.c:1452
#define rb_enc_isspace(c, enc)
Definition: encoding.h:231
int rb_enc_precise_mbclen(const char *p, const char *e, rb_encoding *enc)
Definition: encoding.c:1020
int rb_enc_unicode_p(rb_encoding *enc)
Definition: encoding.c:525
#define rb_enc_name(enc)
Definition: encoding.h:171
VALUE rb_class_path(VALUE)
Definition: variable.c:295
#define malloc
Definition: ripper.c:358
VALUE rb_hash_new(void)
Definition: hash.c:424
#define MATCH_BUSY
Definition: re.c:1249
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1908
#define REG_LITERAL
Definition: re.c:280
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Definition: array.c:639
#define PRIsVALUE
Definition: ruby.h:135
unsigned long ID
Definition: ruby.h:86
rb_encoding * rb_usascii_encoding(void)
Definition: encoding.c:1335
VALUE rb_reg_eqq(VALUE re, VALUE str)
Definition: re.c:3173
#define Qnil
Definition: ruby.h:438
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition: eval.c:615
VALUE rb_eStandardError
Definition: error.c:799
ONIG_EXTERN int onig_region_resize(OnigRegion *region, int n)
Definition: regexec.c:248
unsigned long VALUE
Definition: ruby.h:85
#define OBJ_TAINTED(x)
Definition: ruby.h:1296
#define RBASIC(obj)
Definition: ruby.h:1197
VALUE rb_eSecurityError
Definition: error.c:810
ONIG_EXTERN OnigPosition onig_search(OnigRegex, const OnigUChar *str, const OnigUChar *end, const OnigUChar *start, const OnigUChar *range, OnigRegion *region, OnigOptionType option)
VALUE rb_eTypeError
Definition: error.c:801
int rb_utf8_encindex(void)
Definition: encoding.c:1329
VALUE rb_enc_reg_new(const char *s, long len, rb_encoding *enc, int options)
Definition: re.c:2899
#define FIX2INT(x)
Definition: ruby.h:686
int rb_match_count(VALUE match)
Definition: re.c:1258
VALUE rb_obj_encoding(VALUE obj)
Definition: encoding.c:992
#define rb_enc_asciicompat(enc)
Definition: encoding.h:239
OnigPosition * beg
Definition: onigmo.h:717
int memcmp(const void *s1, const void *s2, size_t len)
Definition: memcmp.c:7
struct rmatch * rmatch
Definition: re.h:47
VALUE rb_fstring(VALUE)
Definition: string.c:306
VALUE rb_str_dup(VALUE)
Definition: string.c:1488
#define CHAR_BIT
Definition: ruby.h:196
Definition: re.h:36
int rb_memcicmp(const void *x, const void *y, long len)
Definition: re.c:79
void rb_memerror(void)
Definition: gc.c:7700
register unsigned int len
Definition: zonetab.h:51
#define StringValueCStr(v)
Definition: ruby.h:571
#define RMATCH_REGS(obj)
Definition: re.h:52
VALUE str
Definition: re.h:46
#define RSTRING_PTR(str)
Definition: ruby.h:975
#define KCODE_FIXED
Definition: re.c:283
#define ONIG_OPTION_MULTILINE
Definition: onigmo.h:453
#define rb_exc_new3
Definition: intern.h:244
#define RB_OBJ_WRITE(a, slot, b)
Definition: eval_intern.h:175
VALUE rb_ary_resize(VALUE ary, long len)
expands or shrinks ary to len elements.
Definition: array.c:1648
#define ENCODING_GET(obj)
Definition: encoding.h:58
rb_encoding * rb_enc_get(VALUE obj)
Definition: encoding.c:860
int rb_str_buf_cat_escaped_char(VALUE result, unsigned int c, int unicode_p)
Definition: string.c:5704
char onig_errmsg_buffer[ONIG_MAX_ERROR_MESSAGE_LEN]
Definition: re.c:21
VALUE rb_reg_quote(VALUE str)
Definition: re.c:3425
#define INT2FIX(i)
Definition: ruby.h:232
long rb_enc_strlen(const char *, const char *, rb_encoding *)
Definition: string.c:1700
#define ONIG_OPTION_NONE
Definition: onigmo.h:450
VALUE rb_reg_match_p(VALUE re, VALUE str, long pos)
Definition: re.c:3303
#define MBCLEN_INVALID_P(ret)
Definition: encoding.h:187
#define RARRAY_AREF(a, i)
Definition: ruby.h:1033
const VALUE v1
Definition: internal.h:948
VALUE rb_cRegexp
Definition: re.c:2269
VALUE rb_str_buf_cat_ascii(VALUE, const char *)
Definition: string.c:2860
void rb_backref_set_string(VALUE string, long pos, long len)
Definition: re.c:1300
VALUE rb_eRuntimeError
Definition: error.c:800
int num_regs
Definition: onigmo.h:716
VALUE rb_check_array_type(VALUE ary)
Definition: array.c:651
long rb_reg_adjust_startpos(VALUE re, VALUE str, long pos, int reverse)
Definition: re.c:1457
typedefRUBY_SYMBOL_EXPORT_BEGIN struct re_pattern_buffer Regexp
Definition: re.h:29
#define ENCINDEX_Windows_31J
Definition: encindex.h:53
VALUE rb_str_catf(VALUE str, const char *format,...)
Definition: sprintf.c:1492
#define FL_WB_PROTECTED
Definition: ruby.h:1209
#define ENC_CODERANGE(obj)
Definition: encoding.h:104
VALUE rb_check_string_type(VALUE)
Definition: string.c:2246
VALUE rb_reg_compile(VALUE str, int options, const char *sourcefile, int sourceline)
Definition: re.c:2919
#define LONG2FIX(i)
Definition: ruby.h:234
#define SIZEOF_VALUE
Definition: ruby.h:88
#define RTEST(v)
Definition: ruby.h:450
#define T_STRING
Definition: ruby.h:496
VALUE rb_reg_alloc(void)
Definition: re.c:2855
VALUE rb_class_new_instance(int, const VALUE *, VALUE)
Allocates and initializes an instance of klass.
Definition: object.c:2170
#define RREGEXP(obj)
Definition: ruby.h:1202
st_index_t rb_hash_uint(st_index_t, st_index_t)
#define char_size(c2, c1)
Definition: nkf.c:3811
#define OBJ_INFECT(x, s)
Definition: ruby.h:1302
VALUE rb_reg_match_last(VALUE match)
Definition: re.c:1768
#define ARG_REG_OPTION_MASK
Definition: re.c:285
long rb_str_sublen(VALUE, long)
Definition: string.c:2395
#define rb_enc_left_char_head(s, p, e, enc)
Definition: encoding.h:216
VALUE rb_str_inspect(VALUE)
Definition: string.c:5813
#define BEG(no)
Definition: re.c:24
VALUE rb_eRegexpError
Definition: re.c:19
int rb_char_to_option_kcode(int c, int *option, int *kcode)
Definition: re.c:324
VALUE rb_enc_str_new(const char *, long, rb_encoding *)
Definition: string.c:759
struct rmatch_offset * char_offset
Definition: re.h:41
ONIG_EXTERN const OnigSyntaxType * OnigDefaultSyntax
Definition: onigmo.h:515
unsigned long ruby_scan_hex(const char *, size_t, size_t *)
Definition: util.c:48
#define RREGEXP_SRC_LEN(r)
Definition: ruby.h:1052
ONIG_EXTERN void onig_region_copy(OnigRegion *to, const OnigRegion *from)
Definition: regexec.c:357
const char * name
Definition: nkf.c:208
#define StringValuePtr(v)
Definition: ruby.h:570
long end
Definition: re.h:33
ONIG_EXTERN OnigPosition onig_match(OnigRegex, const OnigUChar *str, const OnigUChar *end, const OnigUChar *at, OnigRegion *region, OnigOptionType option)
OnigEncoding enc
Definition: onigmo.h:772
#define RMATCH(obj)
Definition: re.h:51
long char_pos
Definition: re.c:916
rb_encoding * rb_ascii8bit_encoding(void)
Definition: encoding.c:1305
#define rb_check_frozen(obj)
Definition: intern.h:271
ONIG_EXTERN void onig_set_warn_func(OnigWarnFunc f)
Definition: regparse.c:101
#define ONIGERR_MEMORY
Definition: onigmo.h:629
VALUE rb_str_encode(VALUE str, VALUE to, int ecflags, VALUE ecopts)
Definition: transcode.c:2884
long len
Definition: re.c:2182
VALUE rb_reg_nth_defined(int nth, VALUE match)
Definition: re.c:1661
#define ARG_ENCODING_NONE
Definition: re.c:288
#define rb_enc_mbcput(c, buf, enc)
Definition: encoding.h:211
int rb_enc_str_asciionly_p(VALUE)
Definition: string.c:641
VALUE rb_reg_new(const char *s, long len, int options)
Definition: re.c:2913
VALUE rb_str_buf_new(long)
Definition: string.c:1282
int allocated
Definition: onigmo.h:715
#define SYMBOL_P(x)
Definition: ruby.h:382
#define rb_str_new3
Definition: intern.h:836
OnigOptionType options
Definition: onigmo.h:768
VALUE rb_reg_regcomp(VALUE str)
Definition: re.c:2936
#define NULL
Definition: _sdbm.c:102
#define RREGEXP_SRC(r)
Definition: ruby.h:1050
#define OBJ_TAINT(x)
Definition: ruby.h:1298
#define ST2FIX(h)
Definition: ruby_missing.h:21
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1515
#define ruby_verbose
Definition: ruby.h:1813
VALUE rb_str_append(VALUE, VALUE)
Definition: string.c:2900
const VALUE value
Definition: internal.h:953
VALUE rb_reg_match_pre(VALUE match)
Definition: re.c:1723
VALUE rb_str_to_str(VALUE)
Definition: string.c:1349
#define T_REGEXP
Definition: ruby.h:497
#define NUM2LONG(x)
Definition: ruby.h:648
st_index_t rb_hash_start(st_index_t)
Definition: random.c:1506
unsigned long ruby_scan_oct(const char *, size_t, size_t *)
Definition: util.c:34
int char_offset_updated
Definition: re.h:39
VALUE rb_reg_check_preprocess(VALUE str)
Definition: re.c:2672
char ** argv
Definition: ruby.c:188
Definition: ruby.h:1043
#define ISSPACE(c)
Definition: ruby.h:2145
VALUE rb_enc_str_buf_cat(VALUE str, const char *ptr, long len, rb_encoding *enc)
Definition: string.c:2853
#define StringValue(v)
Definition: ruby.h:569
#define rb_sym2str(sym)
Definition: console.c:107
VALUE rb_str_new(const char *, long)
Definition: string.c:737
#define errcpy(err, msg)
Definition: re.c:22
#define LIKELY(x)
Definition: internal.h:42