Debian Codegraph @

ext/re2/re2.cc

raw symbols SCIP
1 /*
2 * re2 (https://github.com/mudge/re2)
3 * Ruby bindings to RE2, a "fast, safe, thread-friendly alternative to
4 * backtracking regular expression engines like those used in PCRE, Perl, and
5 * Python".
6 *
7 * Copyright (c) 2010, Paul Mucur (https://mudge.name)
8 * Released under the BSD Licence, please see LICENSE.txt
9 */
10
11 #include <cstdint>
12
13 #include <map>
14 #include <sstream>
15 #include <string>
16 #include <vector>
17
18 #include <re2/re2.h>
19 #include <re2/set.h>
20 #include <ruby.h>
21 #include <ruby/encoding.h>
22 #include <ruby/thread.h>
23
24 #define BOOL2RUBY(v) (v ? Qtrue : Qfalse)
25
26 typedef struct {
27 RE2 *pattern;
28 } re2_pattern;
29
30 typedef struct {
31 re2::StringPiece *matches;
32 int number_of_matches;
33 VALUE regexp, text;
34 } re2_matchdata;
35
36 typedef struct {
37 re2::StringPiece *input;
38 int number_of_capturing_groups;
39 bool eof;
40 VALUE regexp, text;
41 } re2_scanner;
42
43 typedef struct {
44 RE2::Set *set;
45 } re2_set;
46
47 struct nogvl_match_arg {
48 const RE2 *pattern;
49 re2::StringPiece text;
50 size_t startpos;
51 size_t endpos;
52 RE2::Anchor anchor;
53 re2::StringPiece *matches;
54 int n;
55 bool matched;
56 };
57
58 static void *nogvl_match(void *ptr) {
59 auto *arg = static_cast<nogvl_match_arg *>(ptr);
60 #ifdef HAVE_ENDPOS_ARGUMENT
61 arg->matched = arg->pattern->Match(
62 arg->text, arg->startpos, arg->endpos,
63 arg->anchor, arg->matches, arg->n);
64 #else
65 arg->matched = arg->pattern->Match(
66 arg->text, arg->startpos,
67 arg->anchor, arg->matches, arg->n);
68 #endif
69 return nullptr;
70 }
71
72 static bool re2_match_without_gvl(
73 const RE2 *pattern, VALUE text, size_t startpos, size_t endpos,
74 RE2::Anchor anchor, re2::StringPiece *matches, int n) {
75 nogvl_match_arg arg;
76 arg.pattern = pattern;
77 arg.text = re2::StringPiece(RSTRING_PTR(text), RSTRING_LEN(text));
78 arg.startpos = startpos;
79 arg.endpos = endpos;
80 arg.anchor = anchor;
81 arg.matches = matches;
82 arg.n = n;
83 arg.matched = false;
84
85 /* Abseil's synchronization primitives (SRWLOCK, SleepConditionVariableSRW)
86 * are incompatible with Ruby's Win32 Mutex-based GVL, causing
87 * WAIT_ABANDONED crashes when multiple threads match concurrently.
88 */
89 #ifdef _WIN32
90 nogvl_match(&arg);
91 #else
92 /* No unblocking function is needed: RE2 matching is CPU-bound computation,
93 * not a blocking system call, so a signal cannot safely interrupt it.
94 */
95 rb_thread_call_without_gvl(nogvl_match, &arg, NULL, NULL);
96 #endif
97
98 return arg.matched;
99 }
100
101 struct nogvl_set_match_arg {
102 const RE2::Set *set;
103 re2::StringPiece text;
104 std::vector<int> *v;
105 #ifdef HAVE_ERROR_INFO_ARGUMENT
106 RE2::Set::ErrorInfo *error_info;
107 #endif
108 bool matched;
109 };
110
111 static void *nogvl_set_match(void *ptr) {
112 auto *arg = static_cast<nogvl_set_match_arg *>(ptr);
113 #ifdef HAVE_ERROR_INFO_ARGUMENT
114 if (arg->error_info) {
115 arg->matched = arg->set->Match(arg->text, arg->v, arg->error_info);
116 } else {
117 arg->matched = arg->set->Match(arg->text, arg->v);
118 }
119 #else
120 arg->matched = arg->set->Match(arg->text, arg->v);
121 #endif
122 return nullptr;
123 }
124
125 struct nogvl_replace_arg {
126 std::string *str;
127 const RE2 *pattern;
128 re2::StringPiece string_pattern;
129 re2::StringPiece rewrite;
130 };
131
132 static void *nogvl_replace(void *ptr) {
133 auto *arg = static_cast<nogvl_replace_arg *>(ptr);
134 if (arg->pattern) {
135 RE2::Replace(arg->str, *arg->pattern, arg->rewrite);
136 } else {
137 RE2::Replace(arg->str, arg->string_pattern, arg->rewrite);
138 }
139 return nullptr;
140 }
141
142 static void *nogvl_global_replace(void *ptr) {
143 auto *arg = static_cast<nogvl_replace_arg *>(ptr);
144 if (arg->pattern) {
145 RE2::GlobalReplace(arg->str, *arg->pattern, arg->rewrite);
146 } else {
147 RE2::GlobalReplace(arg->str, arg->string_pattern, arg->rewrite);
148 }
149 return nullptr;
150 }
151
152 struct nogvl_extract_arg {
153 re2::StringPiece text;
154 const RE2 *pattern;
155 re2::StringPiece string_pattern;
156 re2::StringPiece rewrite;
157 std::string *out;
158 bool extracted;
159 };
160
161 static void *nogvl_extract(void *ptr) {
162 auto *arg = static_cast<nogvl_extract_arg *>(ptr);
163 if (arg->pattern) {
164 arg->extracted = RE2::Extract(arg->text, *arg->pattern,
165 arg->rewrite, arg->out);
166 } else {
167 arg->extracted = RE2::Extract(arg->text, RE2(arg->string_pattern),
168 arg->rewrite, arg->out);
169 }
170 return nullptr;
171 }
172
173 VALUE re2_mRE2, re2_cRegexp, re2_cMatchData, re2_cScanner, re2_cSet,
174 re2_eSetMatchError, re2_eSetUnsupportedError, re2_eRegexpUnsupportedError;
175
176 /* Symbols used in RE2 options. */
177 static ID id_utf8, id_posix_syntax, id_longest_match, id_log_errors,
178 id_max_mem, id_literal, id_never_nl, id_case_sensitive,
179 id_perl_classes, id_word_boundary, id_one_line, id_unanchored,
180 id_anchor, id_anchor_start, id_anchor_both, id_exception,
181 id_submatches, id_startpos, id_endpos, id_symbolize_names;
182
183 inline VALUE encoded_str_new(const char *str, long length, RE2::Options::Encoding encoding) {
184 if (encoding == RE2::Options::EncodingUTF8) {
185 return rb_utf8_str_new(str, length);
186 }
187
188 VALUE string = rb_str_new(str, length);
189 rb_enc_associate_index(string, rb_enc_find_index("ISO-8859-1"));
190
191 return string;
192 }
193
194 static void parse_re2_options(RE2::Options* re2_options, const VALUE options) {
195 if (TYPE(options) != T_HASH) {
196 rb_raise(rb_eArgError, "options should be a hash");
197 }
198
199 VALUE utf8 = rb_hash_aref(options, ID2SYM(id_utf8));
200 if (!NIL_P(utf8)) {
201 re2_options->set_encoding(RTEST(utf8) ? RE2::Options::EncodingUTF8 : RE2::Options::EncodingLatin1);
202 }
203
204 VALUE posix_syntax = rb_hash_aref(options, ID2SYM(id_posix_syntax));
205 if (!NIL_P(posix_syntax)) {
206 re2_options->set_posix_syntax(RTEST(posix_syntax));
207 }
208
209 VALUE longest_match = rb_hash_aref(options, ID2SYM(id_longest_match));
210 if (!NIL_P(longest_match)) {
211 re2_options->set_longest_match(RTEST(longest_match));
212 }
213
214 VALUE log_errors = rb_hash_aref(options, ID2SYM(id_log_errors));
215 if (!NIL_P(log_errors)) {
216 re2_options->set_log_errors(RTEST(log_errors));
217 }
218
219 VALUE max_mem = rb_hash_aref(options, ID2SYM(id_max_mem));
220 if (!NIL_P(max_mem)) {
221 re2_options->set_max_mem(NUM2INT(max_mem));
222 }
223
224 VALUE literal = rb_hash_aref(options, ID2SYM(id_literal));
225 if (!NIL_P(literal)) {
226 re2_options->set_literal(RTEST(literal));
227 }
228
229 VALUE never_nl = rb_hash_aref(options, ID2SYM(id_never_nl));
230 if (!NIL_P(never_nl)) {
231 re2_options->set_never_nl(RTEST(never_nl));
232 }
233
234 VALUE case_sensitive = rb_hash_aref(options, ID2SYM(id_case_sensitive));
235 if (!NIL_P(case_sensitive)) {
236 re2_options->set_case_sensitive(RTEST(case_sensitive));
237 }
238
239 VALUE perl_classes = rb_hash_aref(options, ID2SYM(id_perl_classes));
240 if (!NIL_P(perl_classes)) {
241 re2_options->set_perl_classes(RTEST(perl_classes));
242 }
243
244 VALUE word_boundary = rb_hash_aref(options, ID2SYM(id_word_boundary));
245 if (!NIL_P(word_boundary)) {
246 re2_options->set_word_boundary(RTEST(word_boundary));
247 }
248
249 VALUE one_line = rb_hash_aref(options, ID2SYM(id_one_line));
250 if (!NIL_P(one_line)) {
251 re2_options->set_one_line(RTEST(one_line));
252 }
253 }
254
255 static void re2_matchdata_mark(void *ptr) {
256 re2_matchdata *m = static_cast<re2_matchdata *>(ptr);
257 rb_gc_mark_movable(m->regexp);
258
259 /* Text must not be movable because StringPiece matches hold pointers into
260 * its underlying buffer; moving the string would invalidate them.
261 */
262 rb_gc_mark(m->text);
263 }
264
265 static void re2_matchdata_compact(void *ptr) {
266 re2_matchdata *m = static_cast<re2_matchdata *>(ptr);
267 m->regexp = rb_gc_location(m->regexp);
268 }
269
270 static void re2_matchdata_free(void *ptr) {
271 re2_matchdata *m = static_cast<re2_matchdata *>(ptr);
272 if (m->matches) {
273 delete[] m->matches;
274 }
275 xfree(m);
276 }
277
278 static size_t re2_matchdata_memsize(const void *ptr) {
279 const re2_matchdata *m = static_cast<const re2_matchdata *>(ptr);
280 size_t size = sizeof(*m);
281 if (m->matches) {
282 size += sizeof(*m->matches) * m->number_of_matches;
283 }
284
285 return size;
286 }
287
288 static const rb_data_type_t re2_matchdata_data_type = {
289 "RE2::MatchData",
290 {
291 re2_matchdata_mark,
292 re2_matchdata_free,
293 re2_matchdata_memsize,
294 re2_matchdata_compact
295 },
296 0,
297 0,
298 // IMPORTANT: WB_PROTECTED objects must only use the RB_OBJ_WRITE()
299 // macro to update VALUE references, as to trigger write barriers.
300 RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
301 };
302
303 static void re2_scanner_mark(void *ptr) {
304 re2_scanner *s = static_cast<re2_scanner *>(ptr);
305 rb_gc_mark_movable(s->regexp);
306
307 /* Text must not be movable because the StringPiece input holds a pointer
308 * into its underlying buffer; moving the string would invalidate it.
309 */
310 rb_gc_mark(s->text);
311 }
312
313 static void re2_scanner_compact(void *ptr) {
314 re2_scanner *s = static_cast<re2_scanner *>(ptr);
315 s->regexp = rb_gc_location(s->regexp);
316 }
317
318 static void re2_scanner_free(void *ptr) {
319 re2_scanner *s = static_cast<re2_scanner *>(ptr);
320 if (s->input) {
321 delete s->input;
322 }
323 xfree(s);
324 }
325
326 static size_t re2_scanner_memsize(const void *ptr) {
327 const re2_scanner *s = static_cast<const re2_scanner *>(ptr);
328 size_t size = sizeof(*s);
329 if (s->input) {
330 size += sizeof(*s->input);
331 }
332
333 return size;
334 }
335
336 static const rb_data_type_t re2_scanner_data_type = {
337 "RE2::Scanner",
338 {
339 re2_scanner_mark,
340 re2_scanner_free,
341 re2_scanner_memsize,
342 re2_scanner_compact
343 },
344 0,
345 0,
346 // IMPORTANT: WB_PROTECTED objects must only use the RB_OBJ_WRITE()
347 // macro to update VALUE references, as to trigger write barriers.
348 RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
349 };
350
351 static void re2_regexp_free(void *ptr) {
352 re2_pattern *p = static_cast<re2_pattern *>(ptr);
353 if (p->pattern) {
354 delete p->pattern;
355 }
356 xfree(p);
357 }
358
359 static size_t re2_regexp_memsize(const void *ptr) {
360 const re2_pattern *p = static_cast<const re2_pattern *>(ptr);
361 size_t size = sizeof(*p);
362 if (p->pattern) {
363 size += sizeof(*p->pattern);
364 }
365
366 return size;
367 }
368
369 static const rb_data_type_t re2_regexp_data_type = {
370 "RE2::Regexp",
371 {
372 0,
373 re2_regexp_free,
374 re2_regexp_memsize,
375 },
376 0,
377 0,
378 // IMPORTANT: WB_PROTECTED objects must only use the RB_OBJ_WRITE()
379 // macro to update VALUE references, as to trigger write barriers.
380 RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FROZEN_SHAREABLE
381 };
382
383 static re2_pattern *unwrap_re2_regexp(VALUE self) {
384 re2_pattern *p;
385 TypedData_Get_Struct(self, re2_pattern, &re2_regexp_data_type, p);
386 if (!p->pattern) {
387 rb_raise(rb_eTypeError, "uninitialized RE2::Regexp");
388 }
389 return p;
390 }
391
392 static re2_matchdata *unwrap_re2_matchdata(VALUE self) {
393 re2_matchdata *m;
394 TypedData_Get_Struct(self, re2_matchdata, &re2_matchdata_data_type, m);
395 if (!RTEST(m->regexp)) {
396 rb_raise(rb_eTypeError, "uninitialized RE2::MatchData");
397 }
398 return m;
399 }
400
401 static re2_scanner *unwrap_re2_scanner(VALUE self) {
402 re2_scanner *c;
403 TypedData_Get_Struct(self, re2_scanner, &re2_scanner_data_type, c);
404 if (!RTEST(c->regexp)) {
405 rb_raise(rb_eTypeError, "uninitialized RE2::Scanner");
406 }
407 return c;
408 }
409
410 /*
411 * Returns an array of names of all named capturing groups. Names are returned
412 * in alphabetical order rather than definition order, as RE2 stores named
413 * groups internally in a sorted map.
414 *
415 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
416 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
417 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
418 *
419 * @return [Array<String>] an array of names of named capturing groups
420 * @example
421 * RE2::Regexp.new('(?P<a>\d+) (?P<b>\w+)').names #=> ["a", "b"]
422 */
423 static VALUE re2_regexp_names(const VALUE self) {
424 re2_pattern *p = unwrap_re2_regexp(self);
425
426 const auto& groups = p->pattern->NamedCapturingGroups();
427 VALUE names = rb_ary_new2(groups.size());
428
429 for (const auto& group : groups) {
430 rb_ary_push(names,
431 encoded_str_new(group.first.data(), group.first.size(),
432 p->pattern->options().encoding()));
433 }
434
435 return names;
436 }
437
438 static VALUE re2_matchdata_allocate(VALUE klass) {
439 re2_matchdata *m;
440
441 return TypedData_Make_Struct(klass, re2_matchdata, &re2_matchdata_data_type,
442 m);
443 }
444
445 static VALUE re2_scanner_allocate(VALUE klass) {
446 re2_scanner *c;
447
448 return TypedData_Make_Struct(klass, re2_scanner, &re2_scanner_data_type, c);
449 }
450
451 /*
452 * Returns a frozen copy of the text supplied when matching.
453 *
454 * If the text was already a frozen string, returns the original.
455 *
456 * @return [String] a frozen string with the text supplied when matching
457 * @example
458 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
459 * m.string #=> "bob 123"
460 */
461 static VALUE re2_matchdata_string(const VALUE self) {
462 re2_matchdata *m = unwrap_re2_matchdata(self);
463
464 return m->text;
465 }
466
467 /*
468 * Returns a frozen copy of the text supplied when incrementally matching with
469 * {RE2::Regexp#scan}.
470 *
471 * If the text was already a frozen string, returns the original.
472 *
473 * @return [String] a frozen string with the text passed to {RE2::Regexp#scan}
474 * @example
475 * c = RE2::Regexp.new('(\d+)').scan("foo")
476 * c.string #=> "foo"
477 */
478 static VALUE re2_scanner_string(const VALUE self) {
479 re2_scanner *c = unwrap_re2_scanner(self);
480
481 return c->text;
482 }
483
484 /*
485 * Returns whether the {RE2::Scanner} has consumed all input or not.
486 *
487 * @return [Boolean] whether the {RE2::Scanner} has consumed all input or not
488 * @example
489 * c = RE2::Regexp.new('(\d+)').scan("foo")
490 * c.eof? #=> true
491 */
492 static VALUE re2_scanner_eof(const VALUE self) {
493 re2_scanner *c = unwrap_re2_scanner(self);
494
495 return BOOL2RUBY(c->eof);
496 }
497
498 /*
499 * Rewind the {RE2::Scanner} to the start of the string.
500 *
501 * @example
502 * s = RE2::Regexp.new('(\d+)').scan("1 2 3")
503 * e = s.to_enum
504 * e.scan #=> ["1"]
505 * e.scan #=> ["2"]
506 * s.rewind
507 * e.scan #=> ["1"]
508 */
509 static VALUE re2_scanner_rewind(VALUE self) {
510 re2_scanner *c = unwrap_re2_scanner(self);
511
512 delete c->input;
513 c->input = new(std::nothrow) re2::StringPiece(
514 RSTRING_PTR(c->text), RSTRING_LEN(c->text));
515 if (c->input == nullptr) {
516 rb_raise(rb_eNoMemError,
517 "not enough memory to allocate StringPiece for input");
518 }
519
520 c->eof = false;
521
522 return self;
523 }
524
525 static VALUE re2_scanner_initialize_copy(VALUE self, VALUE other) {
526 re2_scanner *self_c;
527 re2_scanner *other_c = unwrap_re2_scanner(other);
528
529 TypedData_Get_Struct(self, re2_scanner, &re2_scanner_data_type, self_c);
530
531 if (self_c->input) {
532 delete self_c->input;
533 self_c->input = nullptr;
534 }
535
536 RB_OBJ_WRITE(self, &self_c->regexp, other_c->regexp);
537 RB_OBJ_WRITE(self, &self_c->text, other_c->text);
538 self_c->number_of_capturing_groups = other_c->number_of_capturing_groups;
539 self_c->eof = other_c->eof;
540
541 if (other_c->input) {
542 self_c->input = new(std::nothrow) re2::StringPiece(*other_c->input);
543 if (self_c->input == nullptr) {
544 rb_raise(rb_eNoMemError,
545 "not enough memory to allocate StringPiece for input");
546 }
547 } else {
548 self_c->input = nullptr;
549 }
550
551 return self;
552 }
553
554 /*
555 * Scan the given text incrementally for matches using
556 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L447-L463
557 * `FindAndConsume`}, returning an array of submatches on each subsequent
558 * call. Returns `nil` if no matches are found or an empty array for every
559 * match if the pattern has no capturing groups.
560 *
561 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
562 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
563 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
564 *
565 * @return [Array<String>] if the pattern has capturing groups
566 * @return [[]] if the pattern does not have capturing groups
567 * @return [nil] if no matches are found
568 * @example
569 * s = RE2::Regexp.new('(\w+)').scan("Foo bar baz")
570 * s.scan #=> ["Foo"]
571 * s.scan #=> ["bar"]
572 */
573 static VALUE re2_scanner_scan(VALUE self) {
574 re2_scanner *c = unwrap_re2_scanner(self);
575 re2_pattern *p = unwrap_re2_regexp(c->regexp);
576
577 std::vector<RE2::Arg> argv(c->number_of_capturing_groups);
578 std::vector<RE2::Arg*> args(c->number_of_capturing_groups);
579 std::vector<re2::StringPiece> matches(c->number_of_capturing_groups);
580
581 if (c->eof) {
582 return Qnil;
583 }
584
585 re2::StringPiece::size_type original_input_size = c->input->size();
586
587 for (int i = 0; i < c->number_of_capturing_groups; ++i) {
588 argv[i] = &matches[i];
589 args[i] = &argv[i];
590 }
591
592 if (RE2::FindAndConsumeN(c->input, *p->pattern, args.data(),
593 c->number_of_capturing_groups)) {
594 re2::StringPiece::size_type new_input_size = c->input->size();
595 bool input_advanced = new_input_size < original_input_size;
596
597 VALUE result = rb_ary_new2(c->number_of_capturing_groups);
598
599 for (int i = 0; i < c->number_of_capturing_groups; ++i) {
600 if (matches[i].data() == nullptr) {
601 rb_ary_push(result, Qnil);
602 } else {
603 rb_ary_push(result, encoded_str_new(matches[i].data(),
604 matches[i].size(),
605 p->pattern->options().encoding()));
606 }
607 }
608
609 /* Check whether we've exhausted the input yet. */
610 c->eof = new_input_size == 0;
611
612 /* If the match didn't advance the input, we need to do this ourselves,
613 * advancing by a whole character to avoid splitting multi-byte characters.
614 *
615 * The lookup table approach is taken from RE2's own Python extension: the
616 * high 4 bits of a UTF-8 lead byte determine the character's byte length.
617 *
618 * See https://github.com/google/re2/blob/972a15cedd008d846f1a39b2e88ce48d7f166cbd/python/_re2.cc#L46-L48
619 */
620 if (!input_advanced && new_input_size > 0) {
621 size_t char_size = 1;
622
623 if (p->pattern->options().encoding() == RE2::Options::EncodingUTF8) {
624 char_size = "\1\1\1\1\1\1\1\1\1\1\1\1\2\2\3\4"
625 [((*c->input)[0] & 0xFF) >> 4];
626
627 if (char_size > new_input_size) {
628 char_size = new_input_size;
629 }
630 }
631
632 c->input->remove_prefix(char_size);
633 }
634
635 return result;
636 } else {
637 return Qnil;
638 }
639 }
640
641 static re2::StringPiece *re2_matchdata_find_match(VALUE idx, const VALUE self) {
642 re2_matchdata *m = unwrap_re2_matchdata(self);
643 re2_pattern *p = unwrap_re2_regexp(m->regexp);
644
645 int id;
646
647 if (RB_INTEGER_TYPE_P(idx)) {
648 id = NUM2INT(idx);
649 } else if (SYMBOL_P(idx)) {
650 const auto& groups = p->pattern->NamedCapturingGroups();
651 auto search = groups.find(rb_id2name(SYM2ID(idx)));
652
653 if (search != groups.end()) {
654 id = search->second;
655 } else {
656 return nullptr;
657 }
658 } else {
659 StringValue(idx);
660
661 const auto& groups = p->pattern->NamedCapturingGroups();
662 auto search = groups.find(std::string(RSTRING_PTR(idx), RSTRING_LEN(idx)));
663
664 if (search != groups.end()) {
665 id = search->second;
666 } else {
667 return nullptr;
668 }
669 }
670
671 if (id >= 0 && id < m->number_of_matches) {
672 re2::StringPiece *match = &m->matches[id];
673
674 if (match->data() != nullptr) {
675 return match;
676 }
677 }
678
679 return nullptr;
680 }
681
682 /*
683 * Returns the number of elements in the {RE2::MatchData} (including the
684 * overall match, submatches and any `nils`).
685 *
686 * @return [Integer] the number of elements
687 * @example
688 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
689 * m.size #=> 2
690 * m.length #=> 2
691 */
692 static VALUE re2_matchdata_size(const VALUE self) {
693 re2_matchdata *m = unwrap_re2_matchdata(self);
694
695 return INT2FIX(m->number_of_matches);
696 }
697
698 /*
699 * Returns the offset of the start of the nth element of the {RE2::MatchData}.
700 *
701 * @param [Integer, String, Symbol] n the name or number of the submatch
702 * @return [Integer, nil] the offset of the start of the match or `nil` if
703 * there is no such submatch
704 * @example
705 * m = RE2::Regexp.new('ob (\d+)').partial_match("bob 123")
706 * m.begin(0) #=> 1
707 * m.begin(1) #=> 4
708 */
709 static VALUE re2_matchdata_begin(const VALUE self, VALUE n) {
710 re2_matchdata *m = unwrap_re2_matchdata(self);
711
712 re2::StringPiece *match = re2_matchdata_find_match(n, self);
713 if (match == nullptr) {
714 return Qnil;
715 } else {
716 long offset = match->data() - RSTRING_PTR(m->text);
717
718 return LONG2NUM(rb_str_sublen(m->text, offset));
719 }
720 }
721
722 /*
723 * Returns the offset of the character following the end of the nth element of
724 * the {RE2::MatchData}.
725 *
726 * @param [Integer, String, Symbol] n the name or number of the match
727 * @return [Integer, nil] the offset of the character following the end of the
728 * match or `nil` if there is no such match
729 * @example
730 * m = RE2::Regexp.new('ob (\d+) b').partial_match("bob 123 bob")
731 * m.end(0) #=> 9
732 * m.end(1) #=> 7
733 */
734 static VALUE re2_matchdata_end(const VALUE self, VALUE n) {
735 re2_matchdata *m = unwrap_re2_matchdata(self);
736
737 re2::StringPiece *match = re2_matchdata_find_match(n, self);
738 if (match == nullptr) {
739 return Qnil;
740 } else {
741 long offset = (match->data() - RSTRING_PTR(m->text)) + match->size();
742
743 return LONG2NUM(rb_str_sublen(m->text, offset));
744 }
745 }
746
747 /*
748 * Returns the portion of the original string before the match.
749 *
750 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
751 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
752 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
753 *
754 * @return [String] the portion of the original string before the match
755 * @example
756 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123 456")
757 * m.pre_match #=> "bob "
758 */
759 static VALUE re2_matchdata_pre_match(const VALUE self) {
760 re2_matchdata *m = unwrap_re2_matchdata(self);
761 re2_pattern *p = unwrap_re2_regexp(m->regexp);
762
763 re2::StringPiece *match = &m->matches[0];
764 if (match->data() == nullptr) {
765 return Qnil;
766 }
767
768 long offset = match->data() - RSTRING_PTR(m->text);
769
770 return encoded_str_new(RSTRING_PTR(m->text), offset,
771 p->pattern->options().encoding());
772 }
773
774 /*
775 * Returns the portion of the original string after the match.
776 *
777 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
778 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
779 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
780 *
781 * @return [String] the portion of the original string after the match
782 * @example
783 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123 456")
784 * m.post_match #=> " 456"
785 */
786 static VALUE re2_matchdata_post_match(const VALUE self) {
787 re2_matchdata *m = unwrap_re2_matchdata(self);
788 re2_pattern *p = unwrap_re2_regexp(m->regexp);
789
790 re2::StringPiece *match = &m->matches[0];
791 if (match->data() == nullptr) {
792 return Qnil;
793 }
794
795 long start = (match->data() - RSTRING_PTR(m->text)) + match->size();
796 long remaining = RSTRING_LEN(m->text) - start;
797
798 return encoded_str_new(RSTRING_PTR(m->text) + start, remaining,
799 p->pattern->options().encoding());
800 }
801
802 /*
803 * Returns a two-element array containing the beginning and ending offsets of
804 * the nth match.
805 *
806 * @param [Integer, String, Symbol] n the name or number of the match
807 * @return [Array<Integer>, nil] a two-element array with the beginning and
808 * ending offsets of the match or `nil` if there is no such match
809 * @example
810 * m = RE2::Regexp.new('ob (\d+)').partial_match("bob 123")
811 * m.offset(0) #=> [1, 7]
812 * m.offset(1) #=> [4, 7]
813 */
814 static VALUE re2_matchdata_offset(const VALUE self, VALUE n) {
815 re2_matchdata *m = unwrap_re2_matchdata(self);
816
817 re2::StringPiece *match = re2_matchdata_find_match(n, self);
818 if (match == nullptr) {
819 return Qnil;
820 }
821
822 long start = match->data() - RSTRING_PTR(m->text);
823 long end_pos = start + match->size();
824
825 VALUE array = rb_ary_new2(2);
826 rb_ary_push(array, LONG2NUM(rb_str_sublen(m->text, start)));
827 rb_ary_push(array, LONG2NUM(rb_str_sublen(m->text, end_pos)));
828
829 return array;
830 }
831
832 /*
833 * Returns the length of the nth match in characters. This is equivalent to
834 * `m[n].length` but without allocating a new string.
835 *
836 * @param [Integer, String, Symbol] n the name or number of the match
837 * @return [Integer, nil] the length of the match or `nil` if there is no such
838 * match
839 * @example
840 * m = RE2::Regexp.new('(?P<word>\w+) (?P<number>\d+)').partial_match("alice 123")
841 * m.match_length(0) #=> 9
842 * m.match_length(1) #=> 5
843 * m.match_length(:number) #=> 3
844 */
845 static VALUE re2_matchdata_match_length(const VALUE self, VALUE n) {
846 re2_matchdata *m = unwrap_re2_matchdata(self);
847
848 re2::StringPiece *match = re2_matchdata_find_match(n, self);
849 if (match == nullptr) {
850 return Qnil;
851 }
852
853 long start = match->data() - RSTRING_PTR(m->text);
854 long end_pos = start + match->size();
855 long char_len = rb_str_sublen(m->text, end_pos) - rb_str_sublen(m->text, start);
856
857 return LONG2NUM(char_len);
858 }
859
860 /*
861 * Returns the {RE2::Regexp} used in the match.
862 *
863 * @return [RE2::Regexp] the regular expression used in the match
864 * @example
865 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
866 * m.regexp #=> #<RE2::Regexp /(\d+)/>
867 */
868 static VALUE re2_matchdata_regexp(const VALUE self) {
869 re2_matchdata *m = unwrap_re2_matchdata(self);
870
871 return m->regexp;
872 }
873
874 /*
875 * Returns the {RE2::Regexp} used in the {RE2::Scanner}.
876 *
877 * @return [RE2::Regexp] the regular expression used in the {RE2::Scanner}
878 * @example
879 * c = RE2::Regexp.new('(\d+)').scan("bob 123")
880 * c.regexp #=> #<RE2::Regexp /(\d+)/>
881 */
882 static VALUE re2_scanner_regexp(const VALUE self) {
883 re2_scanner *c = unwrap_re2_scanner(self);
884
885 return c->regexp;
886 }
887
888 static VALUE re2_regexp_allocate(VALUE klass) {
889 re2_pattern *p;
890
891 return TypedData_Make_Struct(klass, re2_pattern, &re2_regexp_data_type, p);
892 }
893
894 /*
895 * Returns the array of matches including the overall match, submatches and any
896 * `nil`s.
897 *
898 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
899 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
900 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
901 *
902 * @return [Array<String, nil>] the array of matches
903 * @example
904 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
905 * m.to_a #=> ["123", "123"]
906 */
907 static VALUE re2_matchdata_to_a(const VALUE self) {
908 re2_matchdata *m = unwrap_re2_matchdata(self);
909 re2_pattern *p = unwrap_re2_regexp(m->regexp);
910
911 VALUE array = rb_ary_new2(m->number_of_matches);
912 for (int i = 0; i < m->number_of_matches; ++i) {
913 re2::StringPiece *match = &m->matches[i];
914
915 if (match->data() == nullptr) {
916 rb_ary_push(array, Qnil);
917 } else {
918 rb_ary_push(array, encoded_str_new(match->data(), match->size(),
919 p->pattern->options().encoding()));
920 }
921 }
922
923 return array;
924 }
925
926 static VALUE re2_matchdata_nth_match(int nth, const VALUE self) {
927 re2_matchdata *m = unwrap_re2_matchdata(self);
928 re2_pattern *p = unwrap_re2_regexp(m->regexp);
929
930 if (nth < 0 || nth >= m->number_of_matches) {
931 return Qnil;
932 } else {
933 re2::StringPiece *match = &m->matches[nth];
934
935 if (match->data() == nullptr) {
936 return Qnil;
937 } else {
938 return encoded_str_new(match->data(), match->size(),
939 p->pattern->options().encoding());
940 }
941 }
942 }
943
944 static VALUE re2_matchdata_named_match(const std::string &name, const VALUE self) {
945 re2_matchdata *m = unwrap_re2_matchdata(self);
946 re2_pattern *p = unwrap_re2_regexp(m->regexp);
947
948 const auto& groups = p->pattern->NamedCapturingGroups();
949 auto search = groups.find(name);
950
951 if (search != groups.end()) {
952 return re2_matchdata_nth_match(search->second, self);
953 } else {
954 return Qnil;
955 }
956 }
957
958 /*
959 * Retrieve zero, one or more matches by index or name.
960 *
961 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
962 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
963 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
964 *
965 * @overload [](index)
966 * Access a particular match by index.
967 *
968 * @param [Integer] index the index of the match to fetch
969 * @return [String, nil] the specified match or `nil` if it isn't present
970 * @example
971 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
972 * m[0] #=> "123"
973 *
974 * @overload [](start, length)
975 * Access a range of matches by starting index and length.
976 *
977 * @param [Integer] start the index from which to start
978 * @param [Integer] length the number of elements to fetch
979 * @return [Array<String, nil>] the specified matches
980 * @example
981 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
982 * m[0, 1] #=> ["123"]
983 *
984 * @overload [](range)
985 * Access a range of matches by index.
986 *
987 * @param [Range] range the range of match indexes to fetch
988 * @return [Array<String, nil>] the specified matches
989 * @example
990 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
991 * m[0..1] #=> ["123", "123"]
992 *
993 * @overload [](name)
994 * Access a particular match by name.
995 *
996 * @param [String, Symbol] name the name of the match to fetch
997 * @return [String, nil] the specific match or `nil` if it isn't present
998 * @example
999 * m = RE2::Regexp.new('(?P<number>\d+)').partial_match("bob 123")
1000 * m["number"] #=> "123"
1001 * m[:number] #=> "123"
1002 */
1003 static VALUE re2_matchdata_aref(int argc, VALUE *argv, const VALUE self) {
1004 VALUE idx, rest;
1005 rb_scan_args(argc, argv, "11", &idx, &rest);
1006
1007 if (TYPE(idx) == T_STRING) {
1008 return re2_matchdata_named_match(
1009 std::string(RSTRING_PTR(idx), RSTRING_LEN(idx)), self);
1010 } else if (SYMBOL_P(idx)) {
1011 return re2_matchdata_named_match(rb_id2name(SYM2ID(idx)), self);
1012 } else if (!NIL_P(rest) || !RB_INTEGER_TYPE_P(idx) || NUM2INT(idx) < 0) {
1013 return rb_ary_aref(argc, argv, re2_matchdata_to_a(self));
1014 } else {
1015 return re2_matchdata_nth_match(NUM2INT(idx), self);
1016 }
1017 }
1018
1019 /*
1020 * Returns the entire matched string.
1021 *
1022 * @return [String] the entire matched string
1023 * @example
1024 * m = RE2::Regexp.new('(?P<number>\d+)').partial_match("bob 123")
1025 * m.to_s #=> "123"
1026 */
1027 static VALUE re2_matchdata_to_s(const VALUE self) {
1028 return re2_matchdata_nth_match(0, self);
1029 }
1030
1031 /*
1032 * Returns a printable version of the match.
1033 *
1034 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1035 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1036 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
1037 *
1038 * @return [String] a printable version of the match
1039 * @example
1040 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
1041 * m.inspect #=> "#<RE2::MatchData \"123\" 1:\"123\">"
1042 */
1043 static VALUE re2_matchdata_inspect(const VALUE self) {
1044 re2_matchdata *m = unwrap_re2_matchdata(self);
1045 re2_pattern *p = unwrap_re2_regexp(m->regexp);
1046
1047 std::ostringstream output;
1048 output << "#<RE2::MatchData";
1049
1050 for (int i = 0; i < m->number_of_matches; ++i) {
1051 output << " ";
1052
1053 if (i > 0) {
1054 output << i << ":";
1055 }
1056
1057 VALUE match = re2_matchdata_nth_match(i, self);
1058
1059 if (match == Qnil) {
1060 output << "nil";
1061 } else {
1062 output << "\"";
1063 output.write(RSTRING_PTR(match), RSTRING_LEN(match));
1064 output << "\"";
1065 }
1066 }
1067
1068 output << ">";
1069
1070 return encoded_str_new(output.str().data(), output.str().length(),
1071 p->pattern->options().encoding());
1072 }
1073
1074 /*
1075 * Returns the array of submatches.
1076 *
1077 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1078 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1079 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is
1080 * undefined).
1081 *
1082 * @return [Array<String, nil>] the array of submatches
1083 * @example
1084 * m = RE2::Regexp.new('(\d+)').partial_match("bob 123")
1085 * m.captures #=> ["123"]
1086 * m.deconstruct #=> ["123"]
1087 *
1088 * @example pattern matching
1089 * case RE2::Regexp.new('(\d+) (\d+)').partial_match("bob 123 456")
1090 * in x, y
1091 * puts "Matched #{x} #{y}"
1092 * else
1093 * puts "Unrecognised match"
1094 * end
1095 */
1096 static VALUE re2_matchdata_deconstruct(const VALUE self) {
1097 re2_matchdata *m = unwrap_re2_matchdata(self);
1098 re2_pattern *p = unwrap_re2_regexp(m->regexp);
1099
1100 VALUE array = rb_ary_new2(m->number_of_matches - 1);
1101 for (int i = 1; i < m->number_of_matches; ++i) {
1102 re2::StringPiece *match = &m->matches[i];
1103
1104 if (match->data() == nullptr) {
1105 rb_ary_push(array, Qnil);
1106 } else {
1107 rb_ary_push(array, encoded_str_new(match->data(), match->size(),
1108 p->pattern->options().encoding()));
1109 }
1110 }
1111
1112 return array;
1113 }
1114
1115 /*
1116 * Returns a hash of capturing group names to submatches for pattern matching.
1117 *
1118 * As this is used by Ruby's pattern matching, it will return an empty hash if given
1119 * more keys than there are capturing groups. Given keys will populate the hash in
1120 * order but an invalid name will cause the hash to be immediately returned.
1121 *
1122 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1123 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1124 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
1125 *
1126 * @return [Hash] a hash of capturing group names to submatches
1127 * @param [Array<Symbol>, nil] keys an array of `Symbol` capturing group names
1128 * or `nil` to return all names
1129 * @example
1130 * m = RE2::Regexp.new('(?P<numbers>\d+) (?P<letters>[a-zA-Z]+)').partial_match('123 abc')
1131 * m.deconstruct_keys(nil) #=> {numbers: "123", letters: "abc"}
1132 * m.deconstruct_keys([:numbers]) #=> {numbers: "123"}
1133 * m.deconstruct_keys([:fruit]) #=> {}
1134 * m.deconstruct_keys([:letters, :fruit]) #=> {letters: "abc"}
1135 *
1136 * @example pattern matching
1137 * case RE2::Regexp.new('(?P<numbers>\d+) (?P<letters>[a-zA-Z]+)').partial_match('123 abc')
1138 * in numbers:, letters:
1139 * puts "Numbers: #{numbers}, letters: #{letters}"
1140 * else
1141 * puts "Unrecognised match"
1142 * end
1143 */
1144 static VALUE re2_matchdata_deconstruct_keys(const VALUE self, const VALUE keys) {
1145 re2_matchdata *m = unwrap_re2_matchdata(self);
1146 re2_pattern *p = unwrap_re2_regexp(m->regexp);
1147
1148 const auto& groups = p->pattern->NamedCapturingGroups();
1149 VALUE capturing_groups = rb_hash_new();
1150
1151 if (NIL_P(keys)) {
1152 for (const auto& group : groups) {
1153 rb_hash_aset(capturing_groups,
1154 ID2SYM(rb_intern2(group.first.data(), group.first.size())),
1155 re2_matchdata_nth_match(group.second, self));
1156 }
1157 } else {
1158 Check_Type(keys, T_ARRAY);
1159
1160 if (p->pattern->NumberOfCapturingGroups() >= RARRAY_LEN(keys)) {
1161 for (int i = 0; i < RARRAY_LEN(keys); ++i) {
1162 VALUE key = rb_ary_entry(keys, i);
1163 Check_Type(key, T_SYMBOL);
1164 const char *name = rb_id2name(SYM2ID(key));
1165 auto search = groups.find(name);
1166
1167 if (search != groups.end()) {
1168 rb_hash_aset(capturing_groups, key, re2_matchdata_nth_match(search->second, self));
1169 } else {
1170 break;
1171 }
1172 }
1173 }
1174 }
1175
1176 return capturing_groups;
1177 }
1178
1179 /*
1180 * Returns a hash of capturing group names to matched strings.
1181 *
1182 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1183 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1184 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
1185 *
1186 * @overload named_captures
1187 * Returns a hash with string keys.
1188 *
1189 * @return [Hash] a hash of capturing group names to matching strings
1190 * @example
1191 * m = RE2::Regexp.new('(?P<numbers>\d+) (?P<letters>[a-zA-Z]+)').partial_match('123 abc')
1192 * m.named_captures #=> {"numbers" => "123", "letters" => "abc"}
1193 *
1194 * @overload named_captures(symbolize_names:)
1195 * Returns a hash with string or symbol keys.
1196 *
1197 * @param [Boolean] symbolize_names whether to return group names as symbols
1198 * @return [Hash] a hash of capturing group names to matching strings
1199 * @example
1200 * m = RE2::Regexp.new('(?P<numbers>\d+) (?P<letters>[a-zA-Z]+)').partial_match('123 abc')
1201 * m.named_captures
1202 * #=> {"numbers" => "123", "letters" => "abc"}
1203 * m.named_captures(symbolize_names: true) #=> {numbers: "123", letters: "abc"}
1204 */
1205 static VALUE re2_matchdata_named_captures(int argc, VALUE *argv, const VALUE self) {
1206 VALUE opts;
1207 rb_scan_args(argc, argv, "0:", &opts);
1208
1209 bool symbolize = false;
1210 if (!NIL_P(opts)) {
1211 VALUE sym = rb_hash_aref(opts, ID2SYM(id_symbolize_names));
1212 symbolize = RTEST(sym);
1213 }
1214
1215 re2_matchdata *m = unwrap_re2_matchdata(self);
1216 re2_pattern *p = unwrap_re2_regexp(m->regexp);
1217
1218 const auto& groups = p->pattern->NamedCapturingGroups();
1219 VALUE result = rb_hash_new();
1220
1221 for (const auto& group : groups) {
1222 VALUE key;
1223 if (symbolize) {
1224 key = ID2SYM(rb_intern2(group.first.data(), group.first.size()));
1225 } else {
1226 key = encoded_str_new(group.first.data(), group.first.size(),
1227 p->pattern->options().encoding());
1228 }
1229 rb_hash_aset(result, key, re2_matchdata_nth_match(group.second, self));
1230 }
1231
1232 return result;
1233 }
1234
1235 /*
1236 * Returns an array of names of named capturing groups. Names are returned in
1237 * alphabetical order rather than definition order, as RE2 stores named groups
1238 * internally in a sorted map.
1239 *
1240 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1241 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1242 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
1243 *
1244 * @return [Array<String>] an array of names of named capturing groups
1245 * @example
1246 * m = RE2::Regexp.new('(?P<numbers>\d+) (?P<letters>[a-zA-Z]+)').partial_match('123 abc')
1247 * m.names #=> ["letters", "numbers"]
1248 */
1249 static VALUE re2_matchdata_names(const VALUE self) {
1250 re2_matchdata *m = unwrap_re2_matchdata(self);
1251
1252 return re2_regexp_names(m->regexp);
1253 }
1254
1255 /*
1256 * Returns an array of match values at the given indices or names.
1257 *
1258 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1259 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1260 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
1261 *
1262 * @param [Integer, String, Symbol] indexes the indices or names of
1263 * the matches to fetch
1264 * @return [Array<String, nil>] the values at the given indices or names
1265 * @example
1266 * m = RE2::Regexp.new('(?P<a>\d+) (?P<b>\d+)').partial_match("123 456")
1267 * m.values_at(1, 2) #=> ["123", "456"]
1268 * m.values_at(:a, :b) #=> ["123", "456"]
1269 * m.values_at(1, :b) #=> ["123", "456"]
1270 */
1271 static VALUE re2_matchdata_values_at(int argc, VALUE *argv, const VALUE self) {
1272 unwrap_re2_matchdata(self);
1273
1274 VALUE result = rb_ary_new2(argc);
1275
1276 for (int i = 0; i < argc; ++i) {
1277 VALUE idx = argv[i];
1278
1279 if (TYPE(idx) == T_STRING) {
1280 rb_ary_push(result, re2_matchdata_named_match(
1281 std::string(RSTRING_PTR(idx), RSTRING_LEN(idx)), self));
1282 } else if (SYMBOL_P(idx)) {
1283 rb_ary_push(result, re2_matchdata_named_match(
1284 rb_id2name(SYM2ID(idx)), self));
1285 } else {
1286 rb_ary_push(result, re2_matchdata_nth_match(NUM2INT(idx), self));
1287 }
1288 }
1289
1290 return result;
1291 }
1292
1293 static VALUE re2_matchdata_initialize_copy(VALUE self, VALUE other) {
1294 re2_matchdata *self_m;
1295 re2_matchdata *other_m = unwrap_re2_matchdata(other);
1296
1297 TypedData_Get_Struct(self, re2_matchdata, &re2_matchdata_data_type, self_m);
1298
1299 if (self_m->matches) {
1300 delete[] self_m->matches;
1301 self_m->matches = nullptr;
1302 }
1303
1304 self_m->number_of_matches = other_m->number_of_matches;
1305 RB_OBJ_WRITE(self, &self_m->regexp, other_m->regexp);
1306 RB_OBJ_WRITE(self, &self_m->text, other_m->text);
1307
1308 if (other_m->matches) {
1309 self_m->matches = new(std::nothrow) re2::StringPiece[other_m->number_of_matches];
1310 if (self_m->matches == nullptr) {
1311 rb_raise(rb_eNoMemError,
1312 "not enough memory to allocate StringPiece for matches");
1313 }
1314 for (int i = 0; i < other_m->number_of_matches; ++i) {
1315 self_m->matches[i] = other_m->matches[i];
1316 }
1317 } else {
1318 self_m->matches = nullptr;
1319 }
1320
1321 return self;
1322 }
1323
1324 /*
1325 * Shorthand to compile a new {RE2::Regexp}.
1326 *
1327 * @see RE2::Regexp#initialize
1328 */
1329 static VALUE re2_re2(int argc, VALUE *argv, VALUE) {
1330 return rb_class_new_instance(argc, argv, re2_cRegexp);
1331 }
1332
1333 /*
1334 * Returns a new {RE2::Regexp} object with a compiled version of
1335 * `pattern` stored inside.
1336 *
1337 * @overload initialize(pattern)
1338 * Returns a new {RE2::Regexp} object with a compiled version of
1339 * `pattern` stored inside with the default options.
1340 *
1341 * @param [String] pattern the pattern to compile
1342 * @return [RE2::Regexp] a {RE2::Regexp} with the specified pattern
1343 * @raise [TypeError] if the given pattern can't be coerced to a `String`
1344 * @raise [NoMemoryError] if memory could not be allocated for the compiled
1345 * pattern
1346 *
1347 * @overload initialize(pattern, options)
1348 * Returns a new {RE2::Regexp} object with a compiled version of
1349 * `pattern` stored inside with the specified options.
1350 *
1351 * @param [String] pattern the pattern to compile
1352 * @param [Hash] options the options with which to compile the pattern
1353 * @option options [Boolean] :utf8 (true) text and pattern are UTF-8; otherwise Latin-1
1354 * @option options [Boolean] :posix_syntax (false) restrict regexps to POSIX egrep syntax
1355 * @option options [Boolean] :longest_match (false) search for longest match, not first match
1356 * @option options [Boolean] :log_errors (true) log syntax and execution errors to ERROR
1357 * @option options [Integer] :max_mem approx. max memory footprint of RE2
1358 * @option options [Boolean] :literal (false) interpret string as literal, not regexp
1359 * @option options [Boolean] :never_nl (false) never match `\n`, even if it is in regexp
1360 * @option options [Boolean] :case_sensitive (true) match is case-sensitive (regexp can override with `(?i)` unless in `posix_syntax` mode)
1361 * @option options [Boolean] :perl_classes (false) allow Perl's `\d` `\s` `\w` `\D` `\S` `\W` when in `posix_syntax` mode
1362 * @option options [Boolean] :word_boundary (false) allow `\b` `\B` (word boundary and not) when in `posix_syntax` mode
1363 * @option options [Boolean] :one_line (false) `^` and `$` only match beginning and end of text when in `posix_syntax` mode
1364 * @return [RE2::Regexp] a {RE2::Regexp} with the specified pattern and options
1365 * @raise [TypeError] if the given pattern can't be coerced to a `String`
1366 * @raise [NoMemoryError] if memory could not be allocated for the compiled pattern
1367 */
1368 static VALUE re2_regexp_initialize(int argc, VALUE *argv, VALUE self) {
1369 VALUE pattern, options;
1370 re2_pattern *p;
1371
1372 rb_scan_args(argc, argv, "11", &pattern, &options);
1373
1374 /* Ensure pattern is a string. */
1375 StringValue(pattern);
1376
1377 TypedData_Get_Struct(self, re2_pattern, &re2_regexp_data_type, p);
1378
1379 rb_check_frozen(self);
1380
1381 if (p->pattern) {
1382 delete p->pattern;
1383 p->pattern = nullptr;
1384 }
1385
1386 if (RTEST(options)) {
1387 RE2::Options re2_options;
1388 parse_re2_options(&re2_options, options);
1389
1390 p->pattern = new(std::nothrow) RE2(
1391 re2::StringPiece(RSTRING_PTR(pattern), RSTRING_LEN(pattern)), re2_options);
1392 } else {
1393 p->pattern = new(std::nothrow) RE2(
1394 re2::StringPiece(RSTRING_PTR(pattern), RSTRING_LEN(pattern)));
1395 }
1396
1397 if (p->pattern == nullptr) {
1398 rb_raise(rb_eNoMemError, "not enough memory to allocate RE2 object");
1399 }
1400
1401 rb_obj_freeze(self);
1402
1403 return self;
1404 }
1405
1406 static VALUE re2_regexp_initialize_copy(VALUE self, VALUE other) {
1407 re2_pattern *self_p;
1408 re2_pattern *other_p = unwrap_re2_regexp(other);
1409
1410 TypedData_Get_Struct(self, re2_pattern, &re2_regexp_data_type, self_p);
1411
1412 rb_check_frozen(self);
1413
1414 if (self_p->pattern) {
1415 delete self_p->pattern;
1416 self_p->pattern = nullptr;
1417 }
1418
1419 self_p->pattern = new(std::nothrow) RE2(other_p->pattern->pattern(),
1420 other_p->pattern->options());
1421 if (self_p->pattern == nullptr) {
1422 rb_raise(rb_eNoMemError, "not enough memory to allocate RE2 object");
1423 }
1424
1425 rb_obj_freeze(self);
1426
1427 return self;
1428 }
1429
1430 /*
1431 * Returns a printable version of the regular expression.
1432 *
1433 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1434 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1435 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is
1436 * undefined).
1437 *
1438 * @return [String] a printable version of the regular expression
1439 * @example
1440 * re2 = RE2::Regexp.new("woo?")
1441 * re2.inspect #=> "#<RE2::Regexp /woo?/>"
1442 */
1443 static VALUE re2_regexp_inspect(const VALUE self) {
1444 re2_pattern *p = unwrap_re2_regexp(self);
1445
1446 std::ostringstream output;
1447
1448 output << "#<RE2::Regexp /" << p->pattern->pattern() << "/>";
1449
1450 return encoded_str_new(output.str().data(), output.str().length(),
1451 p->pattern->options().encoding());
1452 }
1453
1454 /*
1455 * Returns a string version of the regular expression.
1456 *
1457 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1458 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1459 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
1460 *
1461 * @return [String] a string version of the regular expression
1462 * @example
1463 * re2 = RE2::Regexp.new("woo?")
1464 * re2.to_s #=> "woo?"
1465 */
1466 static VALUE re2_regexp_to_s(const VALUE self) {
1467 re2_pattern *p = unwrap_re2_regexp(self);
1468
1469 return encoded_str_new(p->pattern->pattern().data(),
1470 p->pattern->pattern().size(),
1471 p->pattern->options().encoding());
1472 }
1473
1474 /*
1475 * Returns whether or not the regular expression was compiled successfully.
1476 *
1477 * @return [Boolean] whether or not compilation was successful
1478 * @example
1479 * re2 = RE2::Regexp.new("woo?")
1480 * re2.ok? #=> true
1481 */
1482 static VALUE re2_regexp_ok(const VALUE self) {
1483 re2_pattern *p = unwrap_re2_regexp(self);
1484
1485 return BOOL2RUBY(p->pattern->ok());
1486 }
1487
1488 /*
1489 * Returns whether or not the regular expression was compiled with the `utf8`
1490 * option set to `true`.
1491 *
1492 * @return [Boolean] the `utf8` option
1493 * @example
1494 * re2 = RE2::Regexp.new("woo?", utf8: true)
1495 * re2.utf8? #=> true
1496 */
1497 static VALUE re2_regexp_utf8(const VALUE self) {
1498 re2_pattern *p = unwrap_re2_regexp(self);
1499
1500 return BOOL2RUBY(p->pattern->options().encoding() == RE2::Options::EncodingUTF8);
1501 }
1502
1503 /*
1504 * Returns whether or not the regular expression was compiled with the
1505 * `posix_syntax` option set to `true`.
1506 *
1507 * @return [Boolean] the `posix_syntax` option
1508 * @example
1509 * re2 = RE2::Regexp.new("woo?", posix_syntax: true)
1510 * re2.posix_syntax? #=> true
1511 */
1512 static VALUE re2_regexp_posix_syntax(const VALUE self) {
1513 re2_pattern *p = unwrap_re2_regexp(self);
1514
1515 return BOOL2RUBY(p->pattern->options().posix_syntax());
1516 }
1517
1518 /*
1519 * Returns whether or not the regular expression was compiled with the
1520 * `longest_match` option set to `true`.
1521 *
1522 * @return [Boolean] the `longest_match` option
1523 * @example
1524 * re2 = RE2::Regexp.new("woo?", longest_match: true)
1525 * re2.longest_match? #=> true
1526 */
1527 static VALUE re2_regexp_longest_match(const VALUE self) {
1528 re2_pattern *p = unwrap_re2_regexp(self);
1529
1530 return BOOL2RUBY(p->pattern->options().longest_match());
1531 }
1532
1533 /*
1534 * Returns whether or not the regular expression was compiled with the
1535 * `log_errors` option set to `true`.
1536 *
1537 * @return [Boolean] the `log_errors` option
1538 * @example
1539 * re2 = RE2::Regexp.new("woo?", log_errors: true)
1540 * re2.log_errors? #=> true
1541 */
1542 static VALUE re2_regexp_log_errors(const VALUE self) {
1543 re2_pattern *p = unwrap_re2_regexp(self);
1544
1545 return BOOL2RUBY(p->pattern->options().log_errors());
1546 }
1547
1548 /*
1549 * Returns the `max_mem` setting for the regular expression.
1550 *
1551 * @return [Integer] the `max_mem` option
1552 * @example
1553 * re2 = RE2::Regexp.new("woo?", max_mem: 1024)
1554 * re2.max_mem #=> 1024
1555 */
1556 static VALUE re2_regexp_max_mem(const VALUE self) {
1557 re2_pattern *p = unwrap_re2_regexp(self);
1558
1559 return INT2FIX(p->pattern->options().max_mem());
1560 }
1561
1562 /*
1563 * Returns whether or not the regular expression was compiled with the
1564 * `literal` option set to `true`.
1565 *
1566 * @return [Boolean] the `literal` option
1567 * @example
1568 * re2 = RE2::Regexp.new("woo?", literal: true)
1569 * re2.literal? #=> true
1570 */
1571 static VALUE re2_regexp_literal(const VALUE self) {
1572 re2_pattern *p = unwrap_re2_regexp(self);
1573
1574 return BOOL2RUBY(p->pattern->options().literal());
1575 }
1576
1577 /*
1578 * Returns whether or not the regular expression was compiled with the
1579 * `never_nl` option set to `true`.
1580 *
1581 * @return [Boolean] the `never_nl` option
1582 * @example
1583 * re2 = RE2::Regexp.new("woo?", never_nl: true)
1584 * re2.never_nl? #=> true
1585 */
1586 static VALUE re2_regexp_never_nl(const VALUE self) {
1587 re2_pattern *p = unwrap_re2_regexp(self);
1588
1589 return BOOL2RUBY(p->pattern->options().never_nl());
1590 }
1591
1592 /*
1593 * Returns whether or not the regular expression was compiled with the
1594 * `case_sensitive` option set to `true`.
1595 *
1596 * @return [Boolean] the `case_sensitive` option
1597 * @example
1598 * re2 = RE2::Regexp.new("woo?", case_sensitive: true)
1599 * re2.case_sensitive? #=> true
1600 */
1601 static VALUE re2_regexp_case_sensitive(const VALUE self) {
1602 re2_pattern *p = unwrap_re2_regexp(self);
1603
1604 return BOOL2RUBY(p->pattern->options().case_sensitive());
1605 }
1606
1607 /*
1608 * Returns whether or not the regular expression was compiled with the
1609 * `case_sensitive` option set to `false`.
1610 *
1611 * @return [Boolean] the inverse of the `case_sensitive` option
1612 * @example
1613 * re2 = RE2::Regexp.new("woo?", case_sensitive: true)
1614 * re2.case_insensitive? #=> false
1615 * re2.casefold? #=> false
1616 */
1617 static VALUE re2_regexp_case_insensitive(const VALUE self) {
1618 return BOOL2RUBY(re2_regexp_case_sensitive(self) != Qtrue);
1619 }
1620
1621 /*
1622 * Returns whether or not the regular expression was compiled with the
1623 * perl_classes option set to `true`.
1624 *
1625 * @return [Boolean] the `perl_classes` option
1626 * @example
1627 * re2 = RE2::Regexp.new("woo?", perl_classes: true)
1628 * re2.perl_classes? #=> true
1629 */
1630 static VALUE re2_regexp_perl_classes(const VALUE self) {
1631 re2_pattern *p = unwrap_re2_regexp(self);
1632
1633 return BOOL2RUBY(p->pattern->options().perl_classes());
1634 }
1635
1636 /*
1637 * Returns whether or not the regular expression was compiled with the
1638 * `word_boundary` option set to `true`.
1639 *
1640 * @return [Boolean] the `word_boundary` option
1641 * @example
1642 * re2 = RE2::Regexp.new("woo?", word_boundary: true)
1643 * re2.word_boundary? #=> true
1644 */
1645 static VALUE re2_regexp_word_boundary(const VALUE self) {
1646 re2_pattern *p = unwrap_re2_regexp(self);
1647
1648 return BOOL2RUBY(p->pattern->options().word_boundary());
1649 }
1650
1651 /*
1652 * Returns whether or not the regular expression was compiled with the
1653 * `one_line` option set to `true`.
1654 *
1655 * @return [Boolean] the `one_line` option
1656 * @example
1657 * re2 = RE2::Regexp.new("woo?", one_line: true)
1658 * re2.one_line? #=> true
1659 */
1660 static VALUE re2_regexp_one_line(const VALUE self) {
1661 re2_pattern *p = unwrap_re2_regexp(self);
1662
1663 return BOOL2RUBY(p->pattern->options().one_line());
1664 }
1665
1666 /*
1667 * If the {RE2::Regexp} could not be created properly, returns an error string
1668 * otherwise returns `nil`.
1669 *
1670 * @return [String, nil] the error string or `nil`
1671 */
1672 static VALUE re2_regexp_error(const VALUE self) {
1673 re2_pattern *p = unwrap_re2_regexp(self);
1674
1675 if (p->pattern->ok()) {
1676 return Qnil;
1677 } else {
1678 return rb_str_new(p->pattern->error().data(), p->pattern->error().size());
1679 }
1680 }
1681
1682 /*
1683 * If the {RE2::Regexp} could not be created properly, returns
1684 * the offending portion of the regexp otherwise returns `nil`.
1685 *
1686 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1687 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1688 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
1689 *
1690 * @return [String, nil] the offending portion of the regexp or `nil`
1691 */
1692 static VALUE re2_regexp_error_arg(const VALUE self) {
1693 re2_pattern *p = unwrap_re2_regexp(self);
1694
1695 if (p->pattern->ok()) {
1696 return Qnil;
1697 } else {
1698 return encoded_str_new(p->pattern->error_arg().data(),
1699 p->pattern->error_arg().size(),
1700 p->pattern->options().encoding());
1701 }
1702 }
1703
1704 /*
1705 * Returns the program size, a very approximate measure
1706 * of a regexp's "cost". Larger numbers are more expensive
1707 * than smaller numbers.
1708 *
1709 * @return [Integer] the regexp "cost"
1710 */
1711 static VALUE re2_regexp_program_size(const VALUE self) {
1712 re2_pattern *p = unwrap_re2_regexp(self);
1713
1714 return INT2FIX(p->pattern->ProgramSize());
1715 }
1716
1717 /*
1718 * Returns a hash of the options currently set for the {RE2::Regexp}.
1719 *
1720 * @return [Hash] the options
1721 */
1722 static VALUE re2_regexp_options(const VALUE self) {
1723 re2_pattern *p = unwrap_re2_regexp(self);
1724 VALUE options = rb_hash_new();
1725
1726 rb_hash_aset(options, ID2SYM(id_utf8),
1727 BOOL2RUBY(p->pattern->options().encoding() == RE2::Options::EncodingUTF8));
1728
1729 rb_hash_aset(options, ID2SYM(id_posix_syntax),
1730 BOOL2RUBY(p->pattern->options().posix_syntax()));
1731
1732 rb_hash_aset(options, ID2SYM(id_longest_match),
1733 BOOL2RUBY(p->pattern->options().longest_match()));
1734
1735 rb_hash_aset(options, ID2SYM(id_log_errors),
1736 BOOL2RUBY(p->pattern->options().log_errors()));
1737
1738 rb_hash_aset(options, ID2SYM(id_max_mem),
1739 INT2FIX(p->pattern->options().max_mem()));
1740
1741 rb_hash_aset(options, ID2SYM(id_literal),
1742 BOOL2RUBY(p->pattern->options().literal()));
1743
1744 rb_hash_aset(options, ID2SYM(id_never_nl),
1745 BOOL2RUBY(p->pattern->options().never_nl()));
1746
1747 rb_hash_aset(options, ID2SYM(id_case_sensitive),
1748 BOOL2RUBY(p->pattern->options().case_sensitive()));
1749
1750 rb_hash_aset(options, ID2SYM(id_perl_classes),
1751 BOOL2RUBY(p->pattern->options().perl_classes()));
1752
1753 rb_hash_aset(options, ID2SYM(id_word_boundary),
1754 BOOL2RUBY(p->pattern->options().word_boundary()));
1755
1756 rb_hash_aset(options, ID2SYM(id_one_line),
1757 BOOL2RUBY(p->pattern->options().one_line()));
1758
1759 /* This is a read-only hash after all... */
1760 rb_obj_freeze(options);
1761
1762 return options;
1763 }
1764
1765 /*
1766 * Returns the number of capturing subpatterns, or -1 if the regexp
1767 * wasn't valid on construction. The overall match (`$0`) does not
1768 * count: if the regexp is `"(a)(b)"`, returns 2.
1769 *
1770 * @return [Integer] the number of capturing subpatterns
1771 */
1772 static VALUE re2_regexp_number_of_capturing_groups(const VALUE self) {
1773 re2_pattern *p = unwrap_re2_regexp(self);
1774
1775 return INT2FIX(p->pattern->NumberOfCapturingGroups());
1776 }
1777
1778 /*
1779 * Returns a hash of names to capturing indices of groups.
1780 *
1781 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
1782 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
1783 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
1784 *
1785 * @return [Hash] a hash of names to capturing indices
1786 */
1787 static VALUE re2_regexp_named_capturing_groups(const VALUE self) {
1788 re2_pattern *p = unwrap_re2_regexp(self);
1789 const auto& groups = p->pattern->NamedCapturingGroups();
1790 VALUE capturing_groups = rb_hash_new();
1791
1792 for (const auto& group : groups) {
1793 rb_hash_aset(capturing_groups,
1794 encoded_str_new(group.first.data(), group.first.size(),
1795 p->pattern->options().encoding()),
1796 INT2FIX(group.second));
1797 }
1798
1799 return capturing_groups;
1800 }
1801
1802 /*
1803 * General matching: match the pattern against the given `text` using
1804 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L562-L588
1805 * `Match`} and return a {RE2::MatchData} instance with the specified number of
1806 * submatches (defaults to the total number of capturing groups) or a boolean
1807 * (if no submatches are required).
1808 *
1809 * The number of submatches has a significant impact on performance: requesting
1810 * one submatch is much faster than requesting more than one and requesting
1811 * zero submatches is faster still.
1812 *
1813 * @overload match(text)
1814 * Returns a {RE2::MatchData} containing the matching pattern and all
1815 * submatches resulting from looking for the regexp in `text` if the pattern
1816 * contains capturing groups.
1817 *
1818 * Returns either `true` or `false` indicating whether a successful match was
1819 * made if the pattern contains no capturing groups.
1820 *
1821 * @param [String] text the text to search
1822 * @return [RE2::MatchData, nil] if the pattern contains capturing groups
1823 * @return [Boolean] if the pattern does not contain capturing groups
1824 * @raise [NoMemoryError] if there was not enough memory to allocate the submatches
1825 * @raise [TypeError] if given text that cannot be coerced to a `String`
1826 * @example Matching with capturing groups
1827 * r = RE2::Regexp.new('w(o)(o)')
1828 * r.match('woo') #=> #<RE2::MatchData "woo" 1:"o" 2:"o">
1829 * @example Matching without capturing groups
1830 * r = RE2::Regexp.new('woo')
1831 * r.match('woo') #=> true
1832 *
1833 * @overload match(text, options)
1834 * See `match(text)` but with customisable offsets for starting and ending
1835 * matches, optional anchoring to the start or both ends of the text and a
1836 * specific number of submatches to extract (padded with `nil`s if
1837 * necessary).
1838 *
1839 * @param [String] text the text to search
1840 * @param [Hash] options the options with which to perform the match
1841 * @option options [Integer] :startpos (0) offset at which to start matching
1842 * @option options [Integer] :endpos offset at which to stop matching, defaults to the text length
1843 * @option options [Symbol] :anchor (:unanchored) one of :unanchored, :anchor_start, :anchor_both to anchor the match
1844 * @option options [Integer] :submatches how many submatches to extract (0 is
1845 * fastest), defaults to the number of capturing groups
1846 * @return [RE2::MatchData, nil] if extracting any submatches
1847 * @return [Boolean] if not extracting any submatches
1848 * @raise [ArgumentError] if given a negative number of submatches, invalid
1849 * anchor or invalid startpos, endpos pair
1850 * @raise [NoMemoryError] if there was not enough memory to allocate the matches
1851 * @raise [TypeError] if given non-String text, non-numeric number of
1852 * submatches, non-symbol anchor or non-hash options
1853 * @raise [RE2::Regexp::UnsupportedError] if given an endpos argument on a
1854 * version of RE2 that does not support it
1855 * @example Matching with capturing groups
1856 * r = RE2::Regexp.new('w(o)(o)')
1857 * r.match('woo', submatches: 1) #=> #<RE2::MatchData "woo" 1:"o">
1858 * r.match('woo', submatches: 3) #=> #<RE2::MatchData "woo" 1:"o" 2:"o" 3:nil>
1859 * r.match('woot', anchor: :anchor_both, submatches: 0)
1860 * #=> false
1861 * r.match('woot', anchor: :anchor_start, submatches: 0)
1862 * #=> true
1863 * @example Matching without capturing groups
1864 * r = RE2::Regexp.new('wo+')
1865 * r.match('woot', anchor: :anchor_both) #=> false
1866 * r.match('woot', anchor: :anchor_start) #=> true
1867 *
1868 * @overload match(text, submatches)
1869 * @deprecated Legacy syntax for matching against `text` with a specific
1870 * number of submatches to extract. Use `match(text, submatches: n)` instead.
1871 *
1872 * @param [String] text the text to search
1873 * @param [Integer] submatches the number of submatches to extract
1874 * @return [RE2::MatchData, nil] if extracting any submatches
1875 * @return [Boolean] if not extracting any submatches
1876 * @raise [NoMemoryError] if there was not enough memory to allocate the submatches
1877 * @raise [TypeError] if given non-numeric number of submatches
1878 * @example
1879 * r = RE2::Regexp.new('w(o)(o)')
1880 * r.match('woo', 0) #=> true
1881 * r.match('woo', 1) #=> #<RE2::MatchData "woo" 1:"o">
1882 * r.match('woo', 2) #=> #<RE2::MatchData "woo" 1:"o" 2:"o">
1883 */
1884 static VALUE re2_regexp_match(int argc, VALUE *argv, const VALUE self) {
1885 re2_pattern *p;
1886 re2_matchdata *m;
1887 VALUE text, options;
1888
1889 rb_scan_args(argc, argv, "11", &text, &options);
1890
1891 /* Coerce and freeze text to prevent mutation. */
1892 StringValue(text);
1893 text = rb_str_new_frozen(text);
1894
1895 p = unwrap_re2_regexp(self);
1896
1897 int n;
1898 size_t startpos = 0;
1899 size_t endpos = RSTRING_LEN(text);
1900 RE2::Anchor anchor = RE2::UNANCHORED;
1901
1902 if (RTEST(options)) {
1903 if (RB_INTEGER_TYPE_P(options)) {
1904 n = NUM2INT(options);
1905
1906 if (n < 0) {
1907 rb_raise(rb_eArgError, "number of matches should be >= 0");
1908 }
1909 } else {
1910 if (TYPE(options) != T_HASH) {
1911 options = rb_Hash(options);
1912 }
1913
1914 VALUE endpos_option = rb_hash_aref(options, ID2SYM(id_endpos));
1915 if (!NIL_P(endpos_option)) {
1916 #ifdef HAVE_ENDPOS_ARGUMENT
1917 ssize_t endpos_value = NUM2SSIZET(endpos_option);
1918
1919 if (endpos_value < 0) {
1920 rb_raise(rb_eArgError, "endpos should be >= 0");
1921 }
1922
1923 endpos = static_cast<size_t>(endpos_value);
1924 #else
1925 rb_raise(re2_eRegexpUnsupportedError, "current version of RE2::Match() does not support endpos argument");
1926 #endif
1927 }
1928
1929 VALUE anchor_option = rb_hash_aref(options, ID2SYM(id_anchor));
1930 if (!NIL_P(anchor_option)) {
1931 Check_Type(anchor_option, T_SYMBOL);
1932
1933 ID id_anchor_option = SYM2ID(anchor_option);
1934 if (id_anchor_option == id_unanchored) {
1935 anchor = RE2::UNANCHORED;
1936 } else if (id_anchor_option == id_anchor_start) {
1937 anchor = RE2::ANCHOR_START;
1938 } else if (id_anchor_option == id_anchor_both) {
1939 anchor = RE2::ANCHOR_BOTH;
1940 } else {
1941 rb_raise(rb_eArgError, "anchor should be one of: :unanchored, :anchor_start, :anchor_both");
1942 }
1943 }
1944
1945 VALUE submatches_option = rb_hash_aref(options, ID2SYM(id_submatches));
1946 if (!NIL_P(submatches_option)) {
1947 n = NUM2INT(submatches_option);
1948
1949 if (n < 0) {
1950 rb_raise(rb_eArgError, "number of matches should be >= 0");
1951 }
1952 } else {
1953 if (!p->pattern->ok()) {
1954 return Qnil;
1955 }
1956
1957 n = p->pattern->NumberOfCapturingGroups();
1958 }
1959
1960 VALUE startpos_option = rb_hash_aref(options, ID2SYM(id_startpos));
1961 if (!NIL_P(startpos_option)) {
1962 ssize_t startpos_value = NUM2SSIZET(startpos_option);
1963
1964 if (startpos_value < 0) {
1965 rb_raise(rb_eArgError, "startpos should be >= 0");
1966 }
1967
1968 startpos = static_cast<size_t>(startpos_value);
1969 }
1970 }
1971 } else {
1972 if (!p->pattern->ok()) {
1973 return Qnil;
1974 }
1975
1976 n = p->pattern->NumberOfCapturingGroups();
1977 }
1978
1979 if (startpos > endpos) {
1980 rb_raise(rb_eArgError, "startpos should be <= endpos");
1981 }
1982
1983 #ifndef HAVE_ENDPOS_ARGUMENT
1984 /* Old RE2's Match() takes int startpos. Reject values that would overflow. */
1985 if (startpos > INT_MAX) {
1986 rb_raise(rb_eRangeError, "startpos should be <= %d", INT_MAX);
1987 }
1988 #endif
1989
1990 if (n == 0) {
1991 bool matched = re2_match_without_gvl(
1992 p->pattern, text, startpos, endpos, anchor, 0, 0);
1993 RB_GC_GUARD(text);
1994
1995 return BOOL2RUBY(matched);
1996 } else {
1997 if (n == INT_MAX) {
1998 rb_raise(rb_eRangeError, "number of matches should be < %d", INT_MAX);
1999 }
2000
2001 /* Because match returns the whole match as well. */
2002 n += 1;
2003
2004 re2::StringPiece *matches = new(std::nothrow) re2::StringPiece[n];
2005 if (matches == nullptr) {
2006 rb_raise(rb_eNoMemError,
2007 "not enough memory to allocate StringPieces for matches");
2008 }
2009
2010 bool matched = re2_match_without_gvl(
2011 p->pattern, text, startpos, endpos, anchor, matches, n);
2012 RB_GC_GUARD(text);
2013
2014 if (matched) {
2015 VALUE matchdata = rb_class_new_instance(0, 0, re2_cMatchData);
2016 TypedData_Get_Struct(matchdata, re2_matchdata, &re2_matchdata_data_type, m);
2017
2018 RB_OBJ_WRITE(matchdata, &m->regexp, self);
2019 RB_OBJ_WRITE(matchdata, &m->text, text);
2020 m->matches = matches;
2021 m->number_of_matches = n;
2022
2023 return matchdata;
2024 } else {
2025 delete[] matches;
2026
2027 return Qnil;
2028 }
2029 }
2030 }
2031
2032 /*
2033 * Returns true if the pattern matches any substring of the given text using
2034 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L413-L427
2035 * `PartialMatch`}.
2036 *
2037 * @param [String] text the text to search
2038 * @return [Boolean] whether the match was successful
2039 * @raise [TypeError] if text cannot be coerced to a `String`
2040 */
2041 static VALUE re2_regexp_match_p(const VALUE self, VALUE text) {
2042 StringValue(text);
2043 text = rb_str_new_frozen(text);
2044
2045 re2_pattern *p = unwrap_re2_regexp(self);
2046 bool matched = re2_match_without_gvl(
2047 p->pattern, text, 0, RSTRING_LEN(text), RE2::UNANCHORED, 0, 0);
2048 RB_GC_GUARD(text);
2049
2050 return BOOL2RUBY(matched);
2051 }
2052
2053 /*
2054 * Returns true if the pattern matches the given text using
2055 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L376-L411
2056 * `FullMatch`}.
2057 *
2058 * @param [String] text the text to search
2059 * @return [Boolean] whether the match was successful
2060 * @raise [TypeError] if text cannot be coerced to a `String`
2061 */
2062 static VALUE re2_regexp_full_match_p(const VALUE self, VALUE text) {
2063 StringValue(text);
2064 text = rb_str_new_frozen(text);
2065
2066 re2_pattern *p = unwrap_re2_regexp(self);
2067 bool matched = re2_match_without_gvl(
2068 p->pattern, text, 0, RSTRING_LEN(text), RE2::ANCHOR_BOTH, 0, 0);
2069 RB_GC_GUARD(text);
2070
2071 return BOOL2RUBY(matched);
2072 }
2073
2074 /*
2075 * Returns a {RE2::Scanner} for scanning the given text incrementally with
2076 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L447-L463
2077 * `FindAndConsume`}.
2078 *
2079 * @param [text] text the text to scan incrementally
2080 * @return [RE2::Scanner] an `Enumerable` {RE2::Scanner} object
2081 * @raise [TypeError] if `text` cannot be coerced to a `String`
2082 * @example
2083 * c = RE2::Regexp.new('(\w+)').scan("Foo bar baz")
2084 * #=> #<RE2::Scanner:0x0000000000000001>
2085 */
2086 static VALUE re2_regexp_scan(const VALUE self, VALUE text) {
2087 StringValue(text);
2088 text = rb_str_new_frozen(text);
2089
2090 re2_pattern *p = unwrap_re2_regexp(self);
2091 re2_scanner *c;
2092 VALUE scanner = rb_class_new_instance(0, 0, re2_cScanner);
2093 TypedData_Get_Struct(scanner, re2_scanner, &re2_scanner_data_type, c);
2094
2095 RB_OBJ_WRITE(scanner, &c->regexp, self);
2096 RB_OBJ_WRITE(scanner, &c->text, text);
2097 c->input = new(std::nothrow) re2::StringPiece(
2098 RSTRING_PTR(c->text), RSTRING_LEN(c->text));
2099 if (c->input == nullptr) {
2100 rb_raise(rb_eNoMemError,
2101 "not enough memory to allocate StringPiece for input");
2102 }
2103
2104 if (p->pattern->ok()) {
2105 c->number_of_capturing_groups = p->pattern->NumberOfCapturingGroups();
2106 } else {
2107 c->number_of_capturing_groups = 0;
2108 }
2109
2110 c->eof = false;
2111
2112 return scanner;
2113 }
2114
2115 /*
2116 * Returns whether the underlying RE2 version supports passing an `endpos`
2117 * argument to
2118 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L562-L588
2119 * Match}. If not, {RE2::Regexp#match} will raise an error if attempting to
2120 * pass an `endpos`.
2121 *
2122 * @return [Boolean] whether the underlying
2123 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L562-L588
2124 * Match} has an endpos argument
2125 */
2126 static VALUE re2_regexp_match_has_endpos_argument_p(VALUE) {
2127 #ifdef HAVE_ENDPOS_ARGUMENT
2128 return Qtrue;
2129 #else
2130 return Qfalse;
2131 #endif
2132 }
2133
2134 /*
2135 * Returns a copy of `str` with the first occurrence `pattern` replaced with
2136 * `rewrite` using
2137 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L465-L480
2138 * `Replace`}.
2139 *
2140 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
2141 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
2142 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
2143 *
2144 * @param [String] str the string to modify
2145 * @param [String, RE2::Regexp] pattern a regexp matching text to be replaced
2146 * @param [String] rewrite the string to replace with
2147 * @return [String] the resulting string
2148 * @raise [TypeError] if the given rewrite or pattern (if not provided as a
2149 * {RE2::Regexp}) cannot be coerced to `String`s
2150 * @example
2151 * RE2.replace("hello there", "hello", "howdy") #=> "howdy there"
2152 * re2 = RE2::Regexp.new("hel+o")
2153 * RE2.replace("hello there", re2, "yo") #=> "yo there"
2154 */
2155 static VALUE re2_replace(VALUE, VALUE str, VALUE pattern,
2156 VALUE rewrite) {
2157 re2_pattern *p = nullptr;
2158
2159 /* Coerce and freeze all arguments before any C++ allocations so that any
2160 * Ruby exceptions (via longjmp) cannot bypass C++ destructors and leak
2161 * memory, and later coercions cannot mutate earlier strings.
2162 */
2163 StringValue(str);
2164 str = rb_str_new_frozen(str);
2165 if (rb_obj_is_kind_of(pattern, re2_cRegexp)) {
2166 p = unwrap_re2_regexp(pattern);
2167 } else {
2168 StringValue(pattern);
2169 pattern = rb_str_new_frozen(pattern);
2170 }
2171 StringValue(rewrite);
2172 rewrite = rb_str_new_frozen(rewrite);
2173
2174 /* Take a copy of str so it can be modified in-place by RE2::Replace. */
2175 std::string str_as_string(RSTRING_PTR(str), RSTRING_LEN(str));
2176
2177 nogvl_replace_arg arg;
2178 arg.str = &str_as_string;
2179 if (p) {
2180 arg.pattern = p->pattern;
2181 } else {
2182 arg.pattern = nullptr;
2183 arg.string_pattern = re2::StringPiece(
2184 RSTRING_PTR(pattern), RSTRING_LEN(pattern));
2185 }
2186 arg.rewrite = re2::StringPiece(
2187 RSTRING_PTR(rewrite), RSTRING_LEN(rewrite));
2188
2189 #ifdef _WIN32
2190 nogvl_replace(&arg);
2191 #else
2192 rb_thread_call_without_gvl(nogvl_replace, &arg, NULL, NULL);
2193 #endif
2194
2195 RB_GC_GUARD(rewrite);
2196 RB_GC_GUARD(pattern);
2197
2198 if (p) {
2199 return encoded_str_new(str_as_string.data(), str_as_string.size(),
2200 p->pattern->options().encoding());
2201 } else {
2202 return encoded_str_new(str_as_string.data(), str_as_string.size(),
2203 RE2::Options::EncodingUTF8);
2204 }
2205 }
2206
2207 /*
2208 * Return a copy of `str` with `pattern` replaced by `rewrite` using
2209 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L482-L497
2210 * `GlobalReplace`}.
2211 *
2212 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
2213 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
2214 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
2215 *
2216 * @param [String] str the string to modify
2217 * @param [String, RE2::Regexp] pattern a regexp matching text to be replaced
2218 * @param [String] rewrite the string to replace with
2219 * @raise [TypeError] if the given rewrite or pattern (if not provided as a
2220 * {RE2::Regexp}) cannot be coerced to `String`s
2221 * @return [String] the resulting string
2222 * @example
2223 * re2 = RE2::Regexp.new("oo?")
2224 * RE2.global_replace("whoops-doops", re2, "e") #=> "wheps-deps"
2225 * RE2.global_replace("hello there", "e", "i") #=> "hillo thiri"
2226 */
2227 static VALUE re2_global_replace(VALUE, VALUE str, VALUE pattern,
2228 VALUE rewrite) {
2229 re2_pattern *p = nullptr;
2230
2231 /* Coerce and freeze all arguments before any C++ allocations so that any
2232 * Ruby exceptions (via longjmp) cannot bypass C++ destructors and leak
2233 * memory, and later coercions cannot mutate earlier strings.
2234 */
2235 StringValue(str);
2236 str = rb_str_new_frozen(str);
2237 if (rb_obj_is_kind_of(pattern, re2_cRegexp)) {
2238 p = unwrap_re2_regexp(pattern);
2239 } else {
2240 StringValue(pattern);
2241 pattern = rb_str_new_frozen(pattern);
2242 }
2243 StringValue(rewrite);
2244 rewrite = rb_str_new_frozen(rewrite);
2245
2246 /* Take a copy of str so it can be modified in-place by
2247 * RE2::GlobalReplace.
2248 */
2249 std::string str_as_string(RSTRING_PTR(str), RSTRING_LEN(str));
2250
2251 nogvl_replace_arg arg;
2252 arg.str = &str_as_string;
2253 if (p) {
2254 arg.pattern = p->pattern;
2255 } else {
2256 arg.pattern = nullptr;
2257 arg.string_pattern = re2::StringPiece(
2258 RSTRING_PTR(pattern), RSTRING_LEN(pattern));
2259 }
2260 arg.rewrite = re2::StringPiece(
2261 RSTRING_PTR(rewrite), RSTRING_LEN(rewrite));
2262
2263 #ifdef _WIN32
2264 nogvl_global_replace(&arg);
2265 #else
2266 rb_thread_call_without_gvl(nogvl_global_replace, &arg, NULL, NULL);
2267 #endif
2268
2269 RB_GC_GUARD(rewrite);
2270 RB_GC_GUARD(pattern);
2271
2272 if (p) {
2273 return encoded_str_new(str_as_string.data(), str_as_string.size(),
2274 p->pattern->options().encoding());
2275 } else {
2276 return encoded_str_new(str_as_string.data(), str_as_string.size(),
2277 RE2::Options::EncodingUTF8);
2278 }
2279 }
2280
2281 /*
2282 * If `pattern` matches `text`, returns a copy of `rewrite` with substitutions
2283 * using
2284 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L499-L510
2285 * `Extract`}. Non-matching portions of `text` are ignored.
2286 *
2287 * Note RE2 only supports UTF-8 and ISO-8859-1 encoding so strings will be
2288 * returned in UTF-8 by default or ISO-8859-1 if the `:utf8` option for the
2289 * {RE2::Regexp} is set to `false` (any other encoding's behaviour is undefined).
2290 *
2291 * @param [String] text the string from which to extract
2292 * @param [String, RE2::Regexp] pattern a regexp matching the text
2293 * @param [String] rewrite the rewrite string with `\1`-style substitutions
2294 * @return [String, nil] the extracted string on a successful match or nil if
2295 * there is no match
2296 * @raise [TypeError] if the given rewrite or pattern (if not provided as a
2297 * {RE2::Regexp}) cannot be coerced to `String`s
2298 * @example
2299 * RE2.extract("[email protected]", '(\w+)@(\w+)', '\2-\1')
2300 * #=> "example-alice"
2301 * RE2.extract("no match", '(\d+)', '\1') #=> nil
2302 */
2303 static VALUE re2_extract(VALUE, VALUE text, VALUE pattern,
2304 VALUE rewrite) {
2305 re2_pattern *p = nullptr;
2306
2307 /* Coerce and freeze all arguments before any C++ allocations so that any
2308 * Ruby exceptions (via longjmp) cannot bypass C++ destructors and leak
2309 * memory, and later coercions cannot mutate earlier strings.
2310 */
2311 StringValue(text);
2312 text = rb_str_new_frozen(text);
2313 if (rb_obj_is_kind_of(pattern, re2_cRegexp)) {
2314 p = unwrap_re2_regexp(pattern);
2315 } else {
2316 StringValue(pattern);
2317 pattern = rb_str_new_frozen(pattern);
2318 }
2319 StringValue(rewrite);
2320 rewrite = rb_str_new_frozen(rewrite);
2321
2322 std::string out;
2323
2324 nogvl_extract_arg arg;
2325 arg.text = re2::StringPiece(RSTRING_PTR(text), RSTRING_LEN(text));
2326 if (p) {
2327 arg.pattern = p->pattern;
2328 } else {
2329 arg.pattern = nullptr;
2330 arg.string_pattern = re2::StringPiece(
2331 RSTRING_PTR(pattern), RSTRING_LEN(pattern));
2332 }
2333 arg.rewrite = re2::StringPiece(
2334 RSTRING_PTR(rewrite), RSTRING_LEN(rewrite));
2335 arg.out = &out;
2336 arg.extracted = false;
2337
2338 #ifdef _WIN32
2339 nogvl_extract(&arg);
2340 #else
2341 rb_thread_call_without_gvl(nogvl_extract, &arg, NULL, NULL);
2342 #endif
2343
2344 RB_GC_GUARD(text);
2345 RB_GC_GUARD(rewrite);
2346 RB_GC_GUARD(pattern);
2347
2348 if (arg.extracted) {
2349 return encoded_str_new(out.data(), out.size(),
2350 p ? p->pattern->options().encoding()
2351 : RE2::Options::EncodingUTF8);
2352 } else {
2353 return Qnil;
2354 }
2355 }
2356
2357 /*
2358 * Returns a version of `str` with all potentially meaningful regexp characters
2359 * escaped using
2360 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/re2.h#L512-L518
2361 * `QuoteMeta`}. The returned string, used as a regular expression, will
2362 * exactly match the original string.
2363 *
2364 * @param [String] unquoted the unquoted string
2365 * @raise [TypeError] if the given unquoted string cannot be coerced to a `String`
2366 * @return [String] the escaped string
2367 * @example
2368 * RE2.escape("1.5-2.0?") #=> "1\\.5\\-2\\.0\\?"
2369 * RE2.quote("1.5-2.0?") #=> "1\\.5\\-2\\.0\\?"
2370 * RE2::Regexp.escape("1.5-2.0?") #=> "1\\.5\\-2\\.0\\?"
2371 * RE2::Regexp.quote("1.5-2.0?") #=> "1\\.5\\-2\\.0\\?"
2372 */
2373 static VALUE re2_escape(VALUE, VALUE unquoted) {
2374 StringValue(unquoted);
2375
2376 std::string quoted_string = RE2::QuoteMeta(
2377 re2::StringPiece(RSTRING_PTR(unquoted), RSTRING_LEN(unquoted)));
2378
2379 return rb_str_new(quoted_string.data(), quoted_string.size());
2380 }
2381
2382 static void re2_set_free(void *ptr) {
2383 re2_set *s = static_cast<re2_set *>(ptr);
2384 if (s->set) {
2385 delete s->set;
2386 }
2387 xfree(s);
2388 }
2389
2390 static size_t re2_set_memsize(const void *ptr) {
2391 const re2_set *s = static_cast<const re2_set *>(ptr);
2392 size_t size = sizeof(*s);
2393 if (s->set) {
2394 size += sizeof(*s->set);
2395 }
2396
2397 return size;
2398 }
2399
2400 static const rb_data_type_t re2_set_data_type = {
2401 "RE2::Set",
2402 {
2403 0,
2404 re2_set_free,
2405 re2_set_memsize,
2406 },
2407 0,
2408 0,
2409 // IMPORTANT: WB_PROTECTED objects must only use the RB_OBJ_WRITE()
2410 // macro to update VALUE references, as to trigger write barriers.
2411 RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FROZEN_SHAREABLE
2412 };
2413
2414 static re2_set *unwrap_re2_set(VALUE self) {
2415 re2_set *s;
2416 TypedData_Get_Struct(self, re2_set, &re2_set_data_type, s);
2417 if (!s->set) {
2418 rb_raise(rb_eTypeError, "uninitialized RE2::Set");
2419 }
2420 return s;
2421 }
2422
2423 static VALUE re2_set_allocate(VALUE klass) {
2424 re2_set *s;
2425 VALUE result = TypedData_Make_Struct(klass, re2_set, &re2_set_data_type, s);
2426
2427 return result;
2428 }
2429
2430 static VALUE re2_set_initialize_copy(VALUE, VALUE) {
2431 rb_raise(rb_eTypeError, "cannot copy RE2::Set");
2432 }
2433
2434 /*
2435 * Returns a new {RE2::Set} object, a collection of patterns that can be
2436 * searched for simultaneously.
2437 *
2438 * @return [RE2::Set]
2439 *
2440 * @overload initialize
2441 * Returns a new {RE2::Set} object for unanchored patterns with the default
2442 * options.
2443 *
2444 * @raise [NoMemoryError] if memory could not be allocated for the compiled pattern
2445 * @return [RE2::Set]
2446 *
2447 * @overload initialize(anchor)
2448 * Returns a new {RE2::Set} object for the specified anchor with the default
2449 * options.
2450 *
2451 * @param [Symbol] anchor one of `:unanchored`, `:anchor_start`, `:anchor_both`
2452 * @raise [ArgumentError] if anchor is not `:unanchored`, `:anchor_start` or `:anchor_both`
2453 * @raise [NoMemoryError] if memory could not be allocated for the compiled pattern
2454 *
2455 * @overload initialize(anchor, options)
2456 * Returns a new {RE2::Set} object with the specified options.
2457 *
2458 * @param [Symbol] anchor one of `:unanchored`, `:anchor_start`, `:anchor_both`
2459 * @param [Hash] options the options with which to compile the pattern
2460 * @option options [Boolean] :utf8 (true) text and pattern are UTF-8; otherwise Latin-1
2461 * @option options [Boolean] :posix_syntax (false) restrict regexps to POSIX egrep syntax
2462 * @option options [Boolean] :longest_match (false) search for longest match, not first match
2463 * @option options [Boolean] :log_errors (true) log syntax and execution errors to ERROR
2464 * @option options [Integer] :max_mem approx. max memory footprint of RE2
2465 * @option options [Boolean] :literal (false) interpret string as literal, not regexp
2466 * @option options [Boolean] :never_nl (false) never match `\n`, even if it is in regexp
2467 * @option options [Boolean] :case_sensitive (true) match is case-sensitive (regexp can override with `(?i)` unless in `posix_syntax` mode)
2468 * @option options [Boolean] :perl_classes (false) allow Perl's `\d` `\s` `\w` `\D` `\S` `\W` when in `posix_syntax` mode
2469 * @option options [Boolean] :word_boundary (false) allow `\b` `\B` (word boundary and not) when in `posix_syntax` mode
2470 * @option options [Boolean] :one_line (false) `^` and `$` only match beginning and end of text when in `posix_syntax` mode
2471 * @return [RE2::Set] a {RE2::Set} with the specified anchor and options
2472 * @raise [ArgumentError] if `anchor` is not one of the accepted choices
2473 * @raise [NoMemoryError] if memory could not be allocated for the compiled pattern
2474 */
2475 static VALUE re2_set_initialize(int argc, VALUE *argv, VALUE self) {
2476 VALUE anchor, options;
2477 re2_set *s;
2478
2479 rb_scan_args(argc, argv, "02", &anchor, &options);
2480 TypedData_Get_Struct(self, re2_set, &re2_set_data_type, s);
2481
2482 RE2::Anchor re2_anchor = RE2::UNANCHORED;
2483
2484 if (!NIL_P(anchor)) {
2485 Check_Type(anchor, T_SYMBOL);
2486 ID id_anchor_arg = SYM2ID(anchor);
2487 if (id_anchor_arg == id_unanchored) {
2488 re2_anchor = RE2::UNANCHORED;
2489 } else if (id_anchor_arg == id_anchor_start) {
2490 re2_anchor = RE2::ANCHOR_START;
2491 } else if (id_anchor_arg == id_anchor_both) {
2492 re2_anchor = RE2::ANCHOR_BOTH;
2493 } else {
2494 rb_raise(rb_eArgError, "anchor should be one of: :unanchored, :anchor_start, :anchor_both");
2495 }
2496 }
2497
2498 RE2::Options re2_options;
2499
2500 if (RTEST(options)) {
2501 parse_re2_options(&re2_options, options);
2502 }
2503
2504 rb_check_frozen(self);
2505
2506 if (s->set) {
2507 delete s->set;
2508 s->set = nullptr;
2509 }
2510
2511 s->set = new(std::nothrow) RE2::Set(re2_options, re2_anchor);
2512 if (s->set == nullptr) {
2513 rb_raise(rb_eNoMemError, "not enough memory to allocate RE2::Set object");
2514 }
2515
2516 return self;
2517 }
2518
2519 /*
2520 * Adds a pattern to the set. Returns the index that will identify the pattern
2521 * in the output of {RE2::Set#match}. Cannot be called after {RE2::Set#compile}
2522 * has been called.
2523 *
2524 * @param [String] pattern the regex pattern
2525 * @return [Integer] the index of the pattern in the set
2526 * @raise [ArgumentError] if called after compile or the pattern is rejected
2527 * @example
2528 * set = RE2::Set.new
2529 * set.add("abc") #=> 0
2530 * set.add("def") #=> 1
2531 */
2532 static VALUE re2_set_add(VALUE self, VALUE pattern) {
2533 StringValue(pattern);
2534
2535 re2_set *s = unwrap_re2_set(self);
2536 rb_check_frozen(self);
2537
2538 int index;
2539 VALUE msg;
2540
2541 {
2542 std::string err;
2543 index = s->set->Add(
2544 re2::StringPiece(RSTRING_PTR(pattern), RSTRING_LEN(pattern)), &err);
2545 msg = rb_str_new(err.data(), err.size());
2546 }
2547
2548 if (index < 0) {
2549 rb_raise(rb_eArgError,
2550 "str rejected by RE2::Set->Add(): %s", RSTRING_PTR(msg));
2551 }
2552
2553 return INT2FIX(index);
2554 }
2555
2556 /*
2557 * Compiles a {RE2::Set} so it can be used to match against. Must be called
2558 * after {RE2::Set#add} and before {RE2::Set#match}.
2559 *
2560 * @return [Boolean] whether compilation was a success
2561 * @example
2562 * set = RE2::Set.new
2563 * set.add("abc")
2564 * set.compile #=> true
2565 */
2566 static VALUE re2_set_compile(VALUE self) {
2567 re2_set *s = unwrap_re2_set(self);
2568 rb_check_frozen(self);
2569
2570 bool compiled = s->set->Compile();
2571
2572 if (compiled) {
2573 rb_obj_freeze(self);
2574 }
2575
2576 return BOOL2RUBY(compiled);
2577 }
2578
2579 /*
2580 * Returns the size of the {RE2::Set}.
2581 *
2582 * @return [Integer] the number of patterns in the set
2583 * @example
2584 * set = RE2::Set.new
2585 * set.add("abc")
2586 * set.size #=> 1
2587 */
2588 static VALUE re2_set_size(VALUE self) {
2589 #ifdef HAVE_SET_SIZE
2590 re2_set *s = unwrap_re2_set(self);
2591
2592 return INT2FIX(s->set->Size());
2593 #else
2594 rb_raise(re2_eSetUnsupportedError, "current version of RE2::Set does not have Size method");
2595 #endif
2596 }
2597
2598 /*
2599 * Returns whether the underlying RE2 version outputs error information from
2600 * {https://github.com/google/re2/blob/bc0faab533e2b27b85b8ad312abf061e33ed6b5d/re2/set.h#L62-L65
2601 * `RE2::Set::Match`}. If not, {RE2::Set#match} will raise an error if attempting to set
2602 * its `:exception` option to `true`.
2603 *
2604 * @return [Boolean] whether the underlying RE2 outputs error information from {RE2::Set} matches
2605 */
2606 static VALUE re2_set_match_raises_errors_p(VALUE) {
2607 #ifdef HAVE_ERROR_INFO_ARGUMENT
2608 return Qtrue;
2609 #else
2610 return Qfalse;
2611 #endif
2612 }
2613
2614 /*
2615 * Returns whether the underlying RE2 version has a Set::Size method.
2616 *
2617 * @return [Boolean] whether the underlying RE2 has a Set::Size method
2618 */
2619 static VALUE re2_set_size_p(VALUE) {
2620 #ifdef HAVE_SET_SIZE
2621 return Qtrue;
2622 #else
2623 return Qfalse;
2624 #endif
2625 }
2626
2627 /*
2628 * Matches the given text against patterns in the set, returning an array of
2629 * integer indices of the matching patterns if matched or an empty array if
2630 * there are no matches.
2631 *
2632 * @return [Array<Integer>]
2633 *
2634 * @overload match(str)
2635 * Returns an array of integer indices of patterns matching the given string
2636 * (if any). Raises exceptions if there are any errors while matching.
2637 *
2638 * @param [String] str the text to match against
2639 * @return [Array<Integer>] the indices of matching regexps
2640 * @raise [MatchError] if an error occurs while matching
2641 * @raise [UnsupportedError] if the underlying version of RE2 does not output error information
2642 * @example
2643 * set = RE2::Set.new
2644 * set.add("abc")
2645 * set.add("def")
2646 * set.compile
2647 * set.match("abcdef") #=> [0, 1]
2648 *
2649 * @overload match(str, options)
2650 * Returns an array of integer indices of patterns matching the given string
2651 * (if any). Raises exceptions if there are any errors while matching and the
2652 * `:exception` option is set to true.
2653 *
2654 * @param [String] str the text to match against
2655 * @param [Hash] options the options with which to match
2656 * @option options [Boolean] :exception (true) whether to raise exceptions with RE2's error information (not supported on ABI version 0 of RE2)
2657 * @return [Array<Integer>] the indices of matching regexps
2658 * @raise [MatchError] if an error occurs while matching
2659 * @raise [UnsupportedError] if the underlying version of RE2 does not output error information
2660 * @example
2661 * set = RE2::Set.new
2662 * set.add("abc")
2663 * set.add("def")
2664 * set.compile
2665 * set.match("abcdef", exception: true) #=> [0, 1]
2666 */
2667 static VALUE re2_set_match(int argc, VALUE *argv, const VALUE self) {
2668 VALUE str, options;
2669 bool raise_exception = true;
2670 rb_scan_args(argc, argv, "11", &str, &options);
2671
2672 StringValue(str);
2673 str = rb_str_new_frozen(str);
2674
2675 re2_set *s = unwrap_re2_set(self);
2676
2677 if (RTEST(options)) {
2678 Check_Type(options, T_HASH);
2679
2680 VALUE exception_option = rb_hash_aref(options, ID2SYM(id_exception));
2681 if (!NIL_P(exception_option)) {
2682 raise_exception = RTEST(exception_option);
2683 }
2684 }
2685
2686 std::vector<int> v;
2687
2688 if (raise_exception) {
2689 #ifdef HAVE_ERROR_INFO_ARGUMENT
2690 RE2::Set::ErrorInfo e;
2691 nogvl_set_match_arg arg;
2692 arg.set = s->set;
2693 arg.text = re2::StringPiece(RSTRING_PTR(str), RSTRING_LEN(str));
2694 arg.v = &v;
2695 arg.error_info = &e;
2696 arg.matched = false;
2697
2698 #ifdef _WIN32
2699 nogvl_set_match(&arg);
2700 #else
2701 rb_thread_call_without_gvl(nogvl_set_match, &arg, NULL, NULL);
2702 #endif
2703 RB_GC_GUARD(str);
2704
2705 bool match_failed = !arg.matched;
2706 VALUE result = rb_ary_new2(v.size());
2707
2708 if (match_failed) {
2709 switch (e.kind) {
2710 case RE2::Set::kNoError:
2711 break;
2712 case RE2::Set::kNotCompiled:
2713 rb_raise(re2_eSetMatchError, "#match must not be called before #compile");
2714 case RE2::Set::kOutOfMemory:
2715 rb_raise(re2_eSetMatchError, "The DFA ran out of memory");
2716 case RE2::Set::kInconsistent:
2717 rb_raise(re2_eSetMatchError, "RE2::Prog internal error");
2718 default: // Just in case a future version of libre2 adds new ErrorKinds
2719 rb_raise(re2_eSetMatchError, "Unknown RE2::Set::ErrorKind: %d", e.kind);
2720 }
2721 } else {
2722 for (int index : v) {
2723 rb_ary_push(result, INT2FIX(index));
2724 }
2725 }
2726
2727 return result;
2728 #else
2729 rb_raise(re2_eSetUnsupportedError, "current version of RE2::Set::Match() does not output error information, :exception option can only be set to false");
2730 #endif
2731 } else {
2732 nogvl_set_match_arg arg;
2733 arg.set = s->set;
2734 arg.text = re2::StringPiece(RSTRING_PTR(str), RSTRING_LEN(str));
2735 arg.v = &v;
2736 #ifdef HAVE_ERROR_INFO_ARGUMENT
2737 arg.error_info = nullptr;
2738 #endif
2739 arg.matched = false;
2740
2741 #ifdef _WIN32
2742 nogvl_set_match(&arg);
2743 #else
2744 rb_thread_call_without_gvl(nogvl_set_match, &arg, NULL, NULL);
2745 #endif
2746 RB_GC_GUARD(str);
2747
2748 VALUE result = rb_ary_new2(v.size());
2749
2750 if (arg.matched) {
2751 for (int index : v) {
2752 rb_ary_push(result, INT2FIX(index));
2753 }
2754 }
2755
2756 return result;
2757 }
2758 }
2759
2760 extern "C" void Init_re2(void) {
2761 rb_ext_ractor_safe(true);
2762
2763 re2_mRE2 = rb_define_module("RE2");
2764 re2_cRegexp = rb_define_class_under(re2_mRE2, "Regexp", rb_cObject);
2765 re2_eRegexpUnsupportedError = rb_define_class_under(re2_cRegexp,
2766 "UnsupportedError", rb_const_get(rb_cObject, rb_intern("StandardError")));
2767 re2_cMatchData = rb_define_class_under(re2_mRE2, "MatchData", rb_cObject);
2768 re2_cScanner = rb_define_class_under(re2_mRE2, "Scanner", rb_cObject);
2769 re2_cSet = rb_define_class_under(re2_mRE2, "Set", rb_cObject);
2770 re2_eSetMatchError = rb_define_class_under(re2_cSet, "MatchError",
2771 rb_const_get(rb_cObject, rb_intern("StandardError")));
2772 re2_eSetUnsupportedError = rb_define_class_under(re2_cSet, "UnsupportedError",
2773 rb_const_get(rb_cObject, rb_intern("StandardError")));
2774
2775 rb_define_alloc_func(re2_cRegexp,
2776 reinterpret_cast<VALUE (*)(VALUE)>(re2_regexp_allocate));
2777 rb_define_alloc_func(re2_cMatchData,
2778 reinterpret_cast<VALUE (*)(VALUE)>(re2_matchdata_allocate));
2779 rb_define_alloc_func(re2_cScanner,
2780 reinterpret_cast<VALUE (*)(VALUE)>(re2_scanner_allocate));
2781 rb_define_alloc_func(re2_cSet,
2782 reinterpret_cast<VALUE (*)(VALUE)>(re2_set_allocate));
2783
2784 rb_define_method(re2_cMatchData, "string",
2785 RUBY_METHOD_FUNC(re2_matchdata_string), 0);
2786 rb_define_method(re2_cMatchData, "regexp",
2787 RUBY_METHOD_FUNC(re2_matchdata_regexp), 0);
2788 rb_define_method(re2_cMatchData, "to_a",
2789 RUBY_METHOD_FUNC(re2_matchdata_to_a), 0);
2790 rb_define_method(re2_cMatchData, "size",
2791 RUBY_METHOD_FUNC(re2_matchdata_size), 0);
2792 rb_define_method(re2_cMatchData, "length",
2793 RUBY_METHOD_FUNC(re2_matchdata_size), 0);
2794 rb_define_method(re2_cMatchData, "begin",
2795 RUBY_METHOD_FUNC(re2_matchdata_begin), 1);
2796 rb_define_method(re2_cMatchData, "end",
2797 RUBY_METHOD_FUNC(re2_matchdata_end), 1);
2798 rb_define_method(re2_cMatchData, "pre_match",
2799 RUBY_METHOD_FUNC(re2_matchdata_pre_match), 0);
2800 rb_define_method(re2_cMatchData, "post_match",
2801 RUBY_METHOD_FUNC(re2_matchdata_post_match), 0);
2802 rb_define_method(re2_cMatchData, "offset",
2803 RUBY_METHOD_FUNC(re2_matchdata_offset), 1);
2804 rb_define_method(re2_cMatchData, "match_length",
2805 RUBY_METHOD_FUNC(re2_matchdata_match_length), 1);
2806 rb_define_method(re2_cMatchData, "[]", RUBY_METHOD_FUNC(re2_matchdata_aref),
2807 -1);
2808 rb_define_method(re2_cMatchData, "to_s",
2809 RUBY_METHOD_FUNC(re2_matchdata_to_s), 0);
2810 rb_define_method(re2_cMatchData, "inspect",
2811 RUBY_METHOD_FUNC(re2_matchdata_inspect), 0);
2812 rb_define_method(re2_cMatchData, "deconstruct",
2813 RUBY_METHOD_FUNC(re2_matchdata_deconstruct), 0);
2814 rb_define_method(re2_cMatchData, "captures",
2815 RUBY_METHOD_FUNC(re2_matchdata_deconstruct), 0);
2816 rb_define_method(re2_cMatchData, "named_captures",
2817 RUBY_METHOD_FUNC(re2_matchdata_named_captures), -1);
2818 rb_define_method(re2_cMatchData, "names",
2819 RUBY_METHOD_FUNC(re2_matchdata_names), 0);
2820 rb_define_method(re2_cMatchData, "values_at",
2821 RUBY_METHOD_FUNC(re2_matchdata_values_at), -1);
2822 rb_define_method(re2_cMatchData, "deconstruct_keys",
2823 RUBY_METHOD_FUNC(re2_matchdata_deconstruct_keys), 1);
2824 rb_define_method(re2_cMatchData, "initialize_copy",
2825 RUBY_METHOD_FUNC(re2_matchdata_initialize_copy), 1);
2826
2827 rb_define_method(re2_cScanner, "string",
2828 RUBY_METHOD_FUNC(re2_scanner_string), 0);
2829 rb_define_method(re2_cScanner, "eof?",
2830 RUBY_METHOD_FUNC(re2_scanner_eof), 0);
2831 rb_define_method(re2_cScanner, "regexp",
2832 RUBY_METHOD_FUNC(re2_scanner_regexp), 0);
2833 rb_define_method(re2_cScanner, "scan",
2834 RUBY_METHOD_FUNC(re2_scanner_scan), 0);
2835 rb_define_method(re2_cScanner, "rewind",
2836 RUBY_METHOD_FUNC(re2_scanner_rewind), 0);
2837 rb_define_method(re2_cScanner, "initialize_copy",
2838 RUBY_METHOD_FUNC(re2_scanner_initialize_copy), 1);
2839
2840 rb_define_singleton_method(re2_cRegexp, "match_has_endpos_argument?",
2841 RUBY_METHOD_FUNC(re2_regexp_match_has_endpos_argument_p), 0);
2842 rb_define_method(re2_cRegexp, "initialize",
2843 RUBY_METHOD_FUNC(re2_regexp_initialize), -1);
2844 rb_define_method(re2_cRegexp, "initialize_copy",
2845 RUBY_METHOD_FUNC(re2_regexp_initialize_copy), 1);
2846 rb_define_method(re2_cRegexp, "ok?", RUBY_METHOD_FUNC(re2_regexp_ok), 0);
2847 rb_define_method(re2_cRegexp, "error", RUBY_METHOD_FUNC(re2_regexp_error),
2848 0);
2849 rb_define_method(re2_cRegexp, "error_arg",
2850 RUBY_METHOD_FUNC(re2_regexp_error_arg), 0);
2851 rb_define_method(re2_cRegexp, "program_size",
2852 RUBY_METHOD_FUNC(re2_regexp_program_size), 0);
2853 rb_define_method(re2_cRegexp, "options",
2854 RUBY_METHOD_FUNC(re2_regexp_options), 0);
2855 rb_define_method(re2_cRegexp, "number_of_capturing_groups",
2856 RUBY_METHOD_FUNC(re2_regexp_number_of_capturing_groups), 0);
2857 rb_define_method(re2_cRegexp, "named_capturing_groups",
2858 RUBY_METHOD_FUNC(re2_regexp_named_capturing_groups), 0);
2859 rb_define_method(re2_cRegexp, "named_captures",
2860 RUBY_METHOD_FUNC(re2_regexp_named_capturing_groups), 0);
2861 rb_define_method(re2_cRegexp, "names",
2862 RUBY_METHOD_FUNC(re2_regexp_names), 0);
2863 rb_define_method(re2_cRegexp, "match", RUBY_METHOD_FUNC(re2_regexp_match),
2864 -1);
2865 rb_define_method(re2_cRegexp, "match?", RUBY_METHOD_FUNC(re2_regexp_match_p),
2866 1);
2867 rb_define_method(re2_cRegexp, "partial_match?",
2868 RUBY_METHOD_FUNC(re2_regexp_match_p), 1);
2869 rb_define_method(re2_cRegexp, "=~", RUBY_METHOD_FUNC(re2_regexp_match_p), 1);
2870 rb_define_method(re2_cRegexp, "===", RUBY_METHOD_FUNC(re2_regexp_match_p), 1);
2871 rb_define_method(re2_cRegexp, "full_match?",
2872 RUBY_METHOD_FUNC(re2_regexp_full_match_p), 1);
2873 rb_define_method(re2_cRegexp, "scan",
2874 RUBY_METHOD_FUNC(re2_regexp_scan), 1);
2875 rb_define_method(re2_cRegexp, "to_s", RUBY_METHOD_FUNC(re2_regexp_to_s), 0);
2876 rb_define_method(re2_cRegexp, "to_str", RUBY_METHOD_FUNC(re2_regexp_to_s),
2877 0);
2878 rb_define_method(re2_cRegexp, "pattern", RUBY_METHOD_FUNC(re2_regexp_to_s),
2879 0);
2880 rb_define_method(re2_cRegexp, "source", RUBY_METHOD_FUNC(re2_regexp_to_s),
2881 0);
2882 rb_define_method(re2_cRegexp, "inspect",
2883 RUBY_METHOD_FUNC(re2_regexp_inspect), 0);
2884 rb_define_method(re2_cRegexp, "utf8?", RUBY_METHOD_FUNC(re2_regexp_utf8),
2885 0);
2886 rb_define_method(re2_cRegexp, "posix_syntax?",
2887 RUBY_METHOD_FUNC(re2_regexp_posix_syntax), 0);
2888 rb_define_method(re2_cRegexp, "longest_match?",
2889 RUBY_METHOD_FUNC(re2_regexp_longest_match), 0);
2890 rb_define_method(re2_cRegexp, "log_errors?",
2891 RUBY_METHOD_FUNC(re2_regexp_log_errors), 0);
2892 rb_define_method(re2_cRegexp, "max_mem",
2893 RUBY_METHOD_FUNC(re2_regexp_max_mem), 0);
2894 rb_define_method(re2_cRegexp, "literal?",
2895 RUBY_METHOD_FUNC(re2_regexp_literal), 0);
2896 rb_define_method(re2_cRegexp, "never_nl?",
2897 RUBY_METHOD_FUNC(re2_regexp_never_nl), 0);
2898 rb_define_method(re2_cRegexp, "case_sensitive?",
2899 RUBY_METHOD_FUNC(re2_regexp_case_sensitive), 0);
2900 rb_define_method(re2_cRegexp, "case_insensitive?",
2901 RUBY_METHOD_FUNC(re2_regexp_case_insensitive), 0);
2902 rb_define_method(re2_cRegexp, "casefold?",
2903 RUBY_METHOD_FUNC(re2_regexp_case_insensitive), 0);
2904 rb_define_method(re2_cRegexp, "perl_classes?",
2905 RUBY_METHOD_FUNC(re2_regexp_perl_classes), 0);
2906 rb_define_method(re2_cRegexp, "word_boundary?",
2907 RUBY_METHOD_FUNC(re2_regexp_word_boundary), 0);
2908 rb_define_method(re2_cRegexp, "one_line?",
2909 RUBY_METHOD_FUNC(re2_regexp_one_line), 0);
2910
2911 rb_define_singleton_method(re2_cSet, "match_raises_errors?",
2912 RUBY_METHOD_FUNC(re2_set_match_raises_errors_p), 0);
2913 rb_define_singleton_method(re2_cSet, "size?",
2914 RUBY_METHOD_FUNC(re2_set_size_p), 0);
2915 rb_define_method(re2_cSet, "initialize",
2916 RUBY_METHOD_FUNC(re2_set_initialize), -1);
2917 rb_define_method(re2_cSet, "initialize_copy",
2918 RUBY_METHOD_FUNC(re2_set_initialize_copy), 1);
2919 rb_define_method(re2_cSet, "add", RUBY_METHOD_FUNC(re2_set_add), 1);
2920 rb_define_method(re2_cSet, "compile", RUBY_METHOD_FUNC(re2_set_compile), 0);
2921 rb_define_method(re2_cSet, "match", RUBY_METHOD_FUNC(re2_set_match), -1);
2922 rb_define_method(re2_cSet, "size", RUBY_METHOD_FUNC(re2_set_size), 0);
2923 rb_define_method(re2_cSet, "length", RUBY_METHOD_FUNC(re2_set_size), 0);
2924
2925 rb_define_module_function(re2_mRE2, "replace",
2926 RUBY_METHOD_FUNC(re2_replace), 3);
2927 rb_define_module_function(re2_mRE2, "Replace",
2928 RUBY_METHOD_FUNC(re2_replace), 3);
2929 rb_define_module_function(re2_mRE2, "global_replace",
2930 RUBY_METHOD_FUNC(re2_global_replace), 3);
2931 rb_define_module_function(re2_mRE2, "GlobalReplace",
2932 RUBY_METHOD_FUNC(re2_global_replace), 3);
2933 rb_define_module_function(re2_mRE2, "extract",
2934 RUBY_METHOD_FUNC(re2_extract), 3);
2935 rb_define_module_function(re2_mRE2, "QuoteMeta",
2936 RUBY_METHOD_FUNC(re2_escape), 1);
2937 rb_define_module_function(re2_mRE2, "escape",
2938 RUBY_METHOD_FUNC(re2_escape), 1);
2939 rb_define_module_function(re2_mRE2, "quote",
2940 RUBY_METHOD_FUNC(re2_escape), 1);
2941 rb_define_singleton_method(re2_cRegexp, "escape",
2942 RUBY_METHOD_FUNC(re2_escape), 1);
2943 rb_define_singleton_method(re2_cRegexp, "quote",
2944 RUBY_METHOD_FUNC(re2_escape), 1);
2945
2946 // (see RE2::Regexp#initialize)
2947 rb_define_singleton_method(re2_cRegexp, "compile",
2948 RUBY_METHOD_FUNC(rb_class_new_instance), -1);
2949
2950 rb_define_module_function(rb_mKernel, "RE2", RUBY_METHOD_FUNC(re2_re2), -1);
2951
2952 /* Create the symbols used in options. */
2953 id_utf8 = rb_intern("utf8");
2954 id_posix_syntax = rb_intern("posix_syntax");
2955 id_longest_match = rb_intern("longest_match");
2956 id_log_errors = rb_intern("log_errors");
2957 id_max_mem = rb_intern("max_mem");
2958 id_literal = rb_intern("literal");
2959 id_never_nl = rb_intern("never_nl");
2960 id_case_sensitive = rb_intern("case_sensitive");
2961 id_perl_classes = rb_intern("perl_classes");
2962 id_word_boundary = rb_intern("word_boundary");
2963 id_one_line = rb_intern("one_line");
2964 id_unanchored = rb_intern("unanchored");
2965 id_anchor = rb_intern("anchor");
2966 id_anchor_start = rb_intern("anchor_start");
2967 id_anchor_both = rb_intern("anchor_both");
2968 id_exception = rb_intern("exception");
2969 id_submatches = rb_intern("submatches");
2970 id_startpos = rb_intern("startpos");
2971 id_endpos = rb_intern("endpos");
2972 id_symbolize_names = rb_intern("symbolize_names");
2973 }