chiark / gitweb /
Merge from existing archive branch
[pcre3.git] / pcrecpp.cc
1 // Copyright (c) 2010, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: Sanjay Ghemawat
31
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <ctype.h>
39 #include <limits.h>      /* for SHRT_MIN, USHRT_MAX, etc */
40 #include <string.h>      /* for memcpy */
41 #include <assert.h>
42 #include <errno.h>
43 #include <string>
44 #include <algorithm>
45
46 #include "pcrecpp_internal.h"
47 #include "pcre.h"
48 #include "pcrecpp.h"
49 #include "pcre_stringpiece.h"
50
51
52 namespace pcrecpp {
53
54 // Maximum number of args we can set
55 static const int kMaxArgs = 16;
56 static const int kVecSize = (1 + kMaxArgs) * 3;  // results + PCRE workspace
57
58 // Special object that stands-in for no argument
59 Arg RE::no_arg((void*)NULL);
60
61 // This is for ABI compatibility with old versions of pcre (pre-7.6),
62 // which defined a global no_arg variable instead of putting it in the
63 // RE class.  This works on GCC >= 3, at least.  It definitely works
64 // for ELF, but may not for other object formats (Mach-O, for
65 // instance, does not support aliases.)  We could probably have a more
66 // inclusive test if we ever needed it.  (Note that not only the
67 // __attribute__ syntax, but also __USER_LABEL_PREFIX__, are
68 // gnu-specific.)
69 #if defined(__GNUC__) && __GNUC__ >= 3 && defined(__ELF__) && !defined(__INTEL_COMPILER)
70 # define ULP_AS_STRING(x)            ULP_AS_STRING_INTERNAL(x)
71 # define ULP_AS_STRING_INTERNAL(x)   #x
72 # define USER_LABEL_PREFIX_STR       ULP_AS_STRING(__USER_LABEL_PREFIX__)
73 extern Arg no_arg
74   __attribute__((alias(USER_LABEL_PREFIX_STR "_ZN7pcrecpp2RE6no_argE")));
75 #endif
76
77 // If a regular expression has no error, its error_ field points here
78 static const string empty_string;
79
80 // If the user doesn't ask for any options, we just use this one
81 static RE_Options default_options;
82
83 // PCRE6.x compatible API
84 void RE::Init(const char *c_pat, const RE_Options* options) {
85   const string cxx_pat(c_pat);
86   Init(cxx_pat, options);
87 }
88
89 void RE::Init(const string& pat, const RE_Options* options) {
90   pattern_ = pat;
91   if (options == NULL) {
92     options_ = default_options;
93   } else {
94     options_ = *options;
95   }
96   error_ = &empty_string;
97   re_full_ = NULL;
98   re_partial_ = NULL;
99
100   re_partial_ = Compile(UNANCHORED);
101   if (re_partial_ != NULL) {
102     re_full_ = Compile(ANCHOR_BOTH);
103   }
104 }
105
106 void RE::Cleanup() {
107   if (re_full_ != NULL)         (*pcre_free)(re_full_);
108   if (re_partial_ != NULL)      (*pcre_free)(re_partial_);
109   if (error_ != &empty_string)  delete error_;
110 }
111
112
113 RE::~RE() {
114   Cleanup();
115 }
116
117
118 pcre* RE::Compile(Anchor anchor) {
119   // First, convert RE_Options into pcre options
120   int pcre_options = 0;
121   pcre_options = options_.all_options();
122
123   // Special treatment for anchoring.  This is needed because at
124   // runtime pcre only provides an option for anchoring at the
125   // beginning of a string (unless you use offset).
126   //
127   // There are three types of anchoring we want:
128   //    UNANCHORED      Compile the original pattern, and use
129   //                    a pcre unanchored match.
130   //    ANCHOR_START    Compile the original pattern, and use
131   //                    a pcre anchored match.
132   //    ANCHOR_BOTH     Tack a "\z" to the end of the original pattern
133   //                    and use a pcre anchored match.
134
135   const char* compile_error;
136   int eoffset;
137   pcre* re;
138   if (anchor != ANCHOR_BOTH) {
139     re = pcre_compile(pattern_.c_str(), pcre_options,
140                       &compile_error, &eoffset, NULL);
141   } else {
142     // Tack a '\z' at the end of RE.  Parenthesize it first so that
143     // the '\z' applies to all top-level alternatives in the regexp.
144     string wrapped = "(?:";  // A non-counting grouping operator
145     wrapped += pattern_;
146     wrapped += ")\\z";
147     re = pcre_compile(wrapped.c_str(), pcre_options,
148                       &compile_error, &eoffset, NULL);
149   }
150   if (re == NULL) {
151     if (error_ == &empty_string) error_ = new string(compile_error);
152   }
153   return re;
154 }
155
156 /***** Matching interfaces *****/
157
158 bool RE::FullMatch(const StringPiece& text,
159                    const Arg& ptr1,
160                    const Arg& ptr2,
161                    const Arg& ptr3,
162                    const Arg& ptr4,
163                    const Arg& ptr5,
164                    const Arg& ptr6,
165                    const Arg& ptr7,
166                    const Arg& ptr8,
167                    const Arg& ptr9,
168                    const Arg& ptr10,
169                    const Arg& ptr11,
170                    const Arg& ptr12,
171                    const Arg& ptr13,
172                    const Arg& ptr14,
173                    const Arg& ptr15,
174                    const Arg& ptr16) const {
175   const Arg* args[kMaxArgs];
176   int n = 0;
177   if (&ptr1  == &no_arg) { goto done; } args[n++] = &ptr1;
178   if (&ptr2  == &no_arg) { goto done; } args[n++] = &ptr2;
179   if (&ptr3  == &no_arg) { goto done; } args[n++] = &ptr3;
180   if (&ptr4  == &no_arg) { goto done; } args[n++] = &ptr4;
181   if (&ptr5  == &no_arg) { goto done; } args[n++] = &ptr5;
182   if (&ptr6  == &no_arg) { goto done; } args[n++] = &ptr6;
183   if (&ptr7  == &no_arg) { goto done; } args[n++] = &ptr7;
184   if (&ptr8  == &no_arg) { goto done; } args[n++] = &ptr8;
185   if (&ptr9  == &no_arg) { goto done; } args[n++] = &ptr9;
186   if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
187   if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
188   if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
189   if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
190   if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
191   if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
192   if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
193  done:
194
195   int consumed;
196   int vec[kVecSize];
197   return DoMatchImpl(text, ANCHOR_BOTH, &consumed, args, n, vec, kVecSize);
198 }
199
200 bool RE::PartialMatch(const StringPiece& text,
201                       const Arg& ptr1,
202                       const Arg& ptr2,
203                       const Arg& ptr3,
204                       const Arg& ptr4,
205                       const Arg& ptr5,
206                       const Arg& ptr6,
207                       const Arg& ptr7,
208                       const Arg& ptr8,
209                       const Arg& ptr9,
210                       const Arg& ptr10,
211                       const Arg& ptr11,
212                       const Arg& ptr12,
213                       const Arg& ptr13,
214                       const Arg& ptr14,
215                       const Arg& ptr15,
216                       const Arg& ptr16) const {
217   const Arg* args[kMaxArgs];
218   int n = 0;
219   if (&ptr1  == &no_arg) { goto done; } args[n++] = &ptr1;
220   if (&ptr2  == &no_arg) { goto done; } args[n++] = &ptr2;
221   if (&ptr3  == &no_arg) { goto done; } args[n++] = &ptr3;
222   if (&ptr4  == &no_arg) { goto done; } args[n++] = &ptr4;
223   if (&ptr5  == &no_arg) { goto done; } args[n++] = &ptr5;
224   if (&ptr6  == &no_arg) { goto done; } args[n++] = &ptr6;
225   if (&ptr7  == &no_arg) { goto done; } args[n++] = &ptr7;
226   if (&ptr8  == &no_arg) { goto done; } args[n++] = &ptr8;
227   if (&ptr9  == &no_arg) { goto done; } args[n++] = &ptr9;
228   if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
229   if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
230   if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
231   if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
232   if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
233   if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
234   if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
235  done:
236
237   int consumed;
238   int vec[kVecSize];
239   return DoMatchImpl(text, UNANCHORED, &consumed, args, n, vec, kVecSize);
240 }
241
242 bool RE::Consume(StringPiece* input,
243                  const Arg& ptr1,
244                  const Arg& ptr2,
245                  const Arg& ptr3,
246                  const Arg& ptr4,
247                  const Arg& ptr5,
248                  const Arg& ptr6,
249                  const Arg& ptr7,
250                  const Arg& ptr8,
251                  const Arg& ptr9,
252                  const Arg& ptr10,
253                  const Arg& ptr11,
254                  const Arg& ptr12,
255                  const Arg& ptr13,
256                  const Arg& ptr14,
257                  const Arg& ptr15,
258                  const Arg& ptr16) const {
259   const Arg* args[kMaxArgs];
260   int n = 0;
261   if (&ptr1  == &no_arg) { goto done; } args[n++] = &ptr1;
262   if (&ptr2  == &no_arg) { goto done; } args[n++] = &ptr2;
263   if (&ptr3  == &no_arg) { goto done; } args[n++] = &ptr3;
264   if (&ptr4  == &no_arg) { goto done; } args[n++] = &ptr4;
265   if (&ptr5  == &no_arg) { goto done; } args[n++] = &ptr5;
266   if (&ptr6  == &no_arg) { goto done; } args[n++] = &ptr6;
267   if (&ptr7  == &no_arg) { goto done; } args[n++] = &ptr7;
268   if (&ptr8  == &no_arg) { goto done; } args[n++] = &ptr8;
269   if (&ptr9  == &no_arg) { goto done; } args[n++] = &ptr9;
270   if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
271   if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
272   if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
273   if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
274   if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
275   if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
276   if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
277  done:
278
279   int consumed;
280   int vec[kVecSize];
281   if (DoMatchImpl(*input, ANCHOR_START, &consumed,
282                   args, n, vec, kVecSize)) {
283     input->remove_prefix(consumed);
284     return true;
285   } else {
286     return false;
287   }
288 }
289
290 bool RE::FindAndConsume(StringPiece* input,
291                         const Arg& ptr1,
292                         const Arg& ptr2,
293                         const Arg& ptr3,
294                         const Arg& ptr4,
295                         const Arg& ptr5,
296                         const Arg& ptr6,
297                         const Arg& ptr7,
298                         const Arg& ptr8,
299                         const Arg& ptr9,
300                         const Arg& ptr10,
301                         const Arg& ptr11,
302                         const Arg& ptr12,
303                         const Arg& ptr13,
304                         const Arg& ptr14,
305                         const Arg& ptr15,
306                         const Arg& ptr16) const {
307   const Arg* args[kMaxArgs];
308   int n = 0;
309   if (&ptr1  == &no_arg) { goto done; } args[n++] = &ptr1;
310   if (&ptr2  == &no_arg) { goto done; } args[n++] = &ptr2;
311   if (&ptr3  == &no_arg) { goto done; } args[n++] = &ptr3;
312   if (&ptr4  == &no_arg) { goto done; } args[n++] = &ptr4;
313   if (&ptr5  == &no_arg) { goto done; } args[n++] = &ptr5;
314   if (&ptr6  == &no_arg) { goto done; } args[n++] = &ptr6;
315   if (&ptr7  == &no_arg) { goto done; } args[n++] = &ptr7;
316   if (&ptr8  == &no_arg) { goto done; } args[n++] = &ptr8;
317   if (&ptr9  == &no_arg) { goto done; } args[n++] = &ptr9;
318   if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
319   if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
320   if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
321   if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
322   if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
323   if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
324   if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
325  done:
326
327   int consumed;
328   int vec[kVecSize];
329   if (DoMatchImpl(*input, UNANCHORED, &consumed,
330                   args, n, vec, kVecSize)) {
331     input->remove_prefix(consumed);
332     return true;
333   } else {
334     return false;
335   }
336 }
337
338 bool RE::Replace(const StringPiece& rewrite,
339                  string *str) const {
340   int vec[kVecSize];
341   int matches = TryMatch(*str, 0, UNANCHORED, true, vec, kVecSize);
342   if (matches == 0)
343     return false;
344
345   string s;
346   if (!Rewrite(&s, rewrite, *str, vec, matches))
347     return false;
348
349   assert(vec[0] >= 0);
350   assert(vec[1] >= 0);
351   str->replace(vec[0], vec[1] - vec[0], s);
352   return true;
353 }
354
355 // Returns PCRE_NEWLINE_CRLF, PCRE_NEWLINE_CR, or PCRE_NEWLINE_LF.
356 // Note that PCRE_NEWLINE_CRLF is defined to be P_N_CR | P_N_LF.
357 // Modified by PH to add PCRE_NEWLINE_ANY and PCRE_NEWLINE_ANYCRLF.
358
359 static int NewlineMode(int pcre_options) {
360   // TODO: if we can make it threadsafe, cache this var
361   int newline_mode = 0;
362   /* if (newline_mode) return newline_mode; */  // do this once it's cached
363   if (pcre_options & (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|
364                       PCRE_NEWLINE_ANY|PCRE_NEWLINE_ANYCRLF)) {
365     newline_mode = (pcre_options &
366                     (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|
367                      PCRE_NEWLINE_ANY|PCRE_NEWLINE_ANYCRLF));
368   } else {
369     int newline;
370     pcre_config(PCRE_CONFIG_NEWLINE, &newline);
371     if (newline == 10)
372       newline_mode = PCRE_NEWLINE_LF;
373     else if (newline == 13)
374       newline_mode = PCRE_NEWLINE_CR;
375     else if (newline == 3338)
376       newline_mode = PCRE_NEWLINE_CRLF;
377     else if (newline == -1)
378       newline_mode = PCRE_NEWLINE_ANY;
379     else if (newline == -2)
380       newline_mode = PCRE_NEWLINE_ANYCRLF;
381     else
382       assert(NULL == "Unexpected return value from pcre_config(NEWLINE)");
383   }
384   return newline_mode;
385 }
386
387 int RE::GlobalReplace(const StringPiece& rewrite,
388                       string *str) const {
389   int count = 0;
390   int vec[kVecSize];
391   string out;
392   int start = 0;
393   bool last_match_was_empty_string = false;
394
395   while (start <= static_cast<int>(str->length())) {
396     // If the previous match was for the empty string, we shouldn't
397     // just match again: we'll match in the same way and get an
398     // infinite loop.  Instead, we do the match in a special way:
399     // anchored -- to force another try at the same position --
400     // and with a flag saying that this time, ignore empty matches.
401     // If this special match returns, that means there's a non-empty
402     // match at this position as well, and we can continue.  If not,
403     // we do what perl does, and just advance by one.
404     // Notice that perl prints '@@@' for this;
405     //    perl -le '$_ = "aa"; s/b*|aa/@/g; print'
406     int matches;
407     if (last_match_was_empty_string) {
408       matches = TryMatch(*str, start, ANCHOR_START, false, vec, kVecSize);
409       if (matches <= 0) {
410         int matchend = start + 1;     // advance one character.
411         // If the current char is CR and we're in CRLF mode, skip LF too.
412         // Note it's better to call pcre_fullinfo() than to examine
413         // all_options(), since options_ could have changed bewteen
414         // compile-time and now, but this is simpler and safe enough.
415         // Modified by PH to add ANY and ANYCRLF.
416         if (matchend < static_cast<int>(str->length()) &&
417             (*str)[start] == '\r' && (*str)[matchend] == '\n' &&
418             (NewlineMode(options_.all_options()) == PCRE_NEWLINE_CRLF ||
419              NewlineMode(options_.all_options()) == PCRE_NEWLINE_ANY ||
420              NewlineMode(options_.all_options()) == PCRE_NEWLINE_ANYCRLF)) {
421           matchend++;
422         }
423         // We also need to advance more than one char if we're in utf8 mode.
424 #ifdef SUPPORT_UTF8
425         if (options_.utf8()) {
426           while (matchend < static_cast<int>(str->length()) &&
427                  ((*str)[matchend] & 0xc0) == 0x80)
428             matchend++;
429         }
430 #endif
431         if (start < static_cast<int>(str->length()))
432           out.append(*str, start, matchend - start);
433         start = matchend;
434         last_match_was_empty_string = false;
435         continue;
436       }
437     } else {
438       matches = TryMatch(*str, start, UNANCHORED, true, vec, kVecSize);
439       if (matches <= 0)
440         break;
441     }
442     int matchstart = vec[0], matchend = vec[1];
443     assert(matchstart >= start);
444     assert(matchend >= matchstart);
445     out.append(*str, start, matchstart - start);
446     Rewrite(&out, rewrite, *str, vec, matches);
447     start = matchend;
448     count++;
449     last_match_was_empty_string = (matchstart == matchend);
450   }
451
452   if (count == 0)
453     return 0;
454
455   if (start < static_cast<int>(str->length()))
456     out.append(*str, start, str->length() - start);
457   swap(out, *str);
458   return count;
459 }
460
461 bool RE::Extract(const StringPiece& rewrite,
462                  const StringPiece& text,
463                  string *out) const {
464   int vec[kVecSize];
465   int matches = TryMatch(text, 0, UNANCHORED, true, vec, kVecSize);
466   if (matches == 0)
467     return false;
468   out->erase();
469   return Rewrite(out, rewrite, text, vec, matches);
470 }
471
472 /*static*/ string RE::QuoteMeta(const StringPiece& unquoted) {
473   string result;
474
475   // Escape any ascii character not in [A-Za-z_0-9].
476   //
477   // Note that it's legal to escape a character even if it has no
478   // special meaning in a regular expression -- so this function does
479   // that.  (This also makes it identical to the perl function of the
480   // same name; see `perldoc -f quotemeta`.)  The one exception is
481   // escaping NUL: rather than doing backslash + NUL, like perl does,
482   // we do '\0', because pcre itself doesn't take embedded NUL chars.
483   for (int ii = 0; ii < unquoted.size(); ++ii) {
484     // Note that using 'isalnum' here raises the benchmark time from
485     // 32ns to 58ns:
486     if (unquoted[ii] == '\0') {
487       result += "\\0";
488     } else if ((unquoted[ii] < 'a' || unquoted[ii] > 'z') &&
489                (unquoted[ii] < 'A' || unquoted[ii] > 'Z') &&
490                (unquoted[ii] < '0' || unquoted[ii] > '9') &&
491                unquoted[ii] != '_' &&
492                // If this is the part of a UTF8 or Latin1 character, we need
493                // to copy this byte without escaping.  Experimentally this is
494                // what works correctly with the regexp library.
495                !(unquoted[ii] & 128)) {
496       result += '\\';
497       result += unquoted[ii];
498     } else {
499       result += unquoted[ii];
500     }
501   }
502
503   return result;
504 }
505
506 /***** Actual matching and rewriting code *****/
507
508 int RE::TryMatch(const StringPiece& text,
509                  int startpos,
510                  Anchor anchor,
511                  bool empty_ok,
512                  int *vec,
513                  int vecsize) const {
514   pcre* re = (anchor == ANCHOR_BOTH) ? re_full_ : re_partial_;
515   if (re == NULL) {
516     //fprintf(stderr, "Matching against invalid re: %s\n", error_->c_str());
517     return 0;
518   }
519
520   pcre_extra extra = { 0, 0, 0, 0, 0, 0, 0, 0 };
521   if (options_.match_limit() > 0) {
522     extra.flags |= PCRE_EXTRA_MATCH_LIMIT;
523     extra.match_limit = options_.match_limit();
524   }
525   if (options_.match_limit_recursion() > 0) {
526     extra.flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;
527     extra.match_limit_recursion = options_.match_limit_recursion();
528   }
529
530   // int options = 0;
531   // Changed by PH as a result of bugzilla #1288
532   int options = (options_.all_options() & PCRE_NO_UTF8_CHECK);
533
534   if (anchor != UNANCHORED)
535     options |= PCRE_ANCHORED;
536   if (!empty_ok)
537     options |= PCRE_NOTEMPTY;
538
539   int rc = pcre_exec(re,              // The regular expression object
540                      &extra,
541                      (text.data() == NULL) ? "" : text.data(),
542                      text.size(),
543                      startpos,
544                      options,
545                      vec,
546                      vecsize);
547
548   // Handle errors
549   if (rc == PCRE_ERROR_NOMATCH) {
550     return 0;
551   } else if (rc < 0) {
552     //fprintf(stderr, "Unexpected return code: %d when matching '%s'\n",
553     //        re, pattern_.c_str());
554     return 0;
555   } else if (rc == 0) {
556     // pcre_exec() returns 0 as a special case when the number of
557     // capturing subpatterns exceeds the size of the vector.
558     // When this happens, there is a match and the output vector
559     // is filled, but we miss out on the positions of the extra subpatterns.
560     rc = vecsize / 2;
561   }
562
563   return rc;
564 }
565
566 bool RE::DoMatchImpl(const StringPiece& text,
567                      Anchor anchor,
568                      int* consumed,
569                      const Arg* const* args,
570                      int n,
571                      int* vec,
572                      int vecsize) const {
573   assert((1 + n) * 3 <= vecsize);  // results + PCRE workspace
574   int matches = TryMatch(text, 0, anchor, true, vec, vecsize);
575   assert(matches >= 0);  // TryMatch never returns negatives
576   if (matches == 0)
577     return false;
578
579   *consumed = vec[1];
580
581   if (n == 0 || args == NULL) {
582     // We are not interested in results
583     return true;
584   }
585
586   if (NumberOfCapturingGroups() < n) {
587     // RE has fewer capturing groups than number of arg pointers passed in
588     return false;
589   }
590
591   // If we got here, we must have matched the whole pattern.
592   // We do not need (can not do) any more checks on the value of 'matches' here
593   // -- see the comment for TryMatch.
594   for (int i = 0; i < n; i++) {
595     const int start = vec[2*(i+1)];
596     const int limit = vec[2*(i+1)+1];
597     if (!args[i]->Parse(text.data() + start, limit-start)) {
598       // TODO: Should we indicate what the error was?
599       return false;
600     }
601   }
602
603   return true;
604 }
605
606 bool RE::DoMatch(const StringPiece& text,
607                  Anchor anchor,
608                  int* consumed,
609                  const Arg* const args[],
610                  int n) const {
611   assert(n >= 0);
612   size_t const vecsize = (1 + n) * 3;  // results + PCRE workspace
613                                        // (as for kVecSize)
614   int space[21];   // use stack allocation for small vecsize (common case)
615   int* vec = vecsize <= 21 ? space : new int[vecsize];
616   bool retval = DoMatchImpl(text, anchor, consumed, args, n, vec, (int)vecsize);
617   if (vec != space) delete [] vec;
618   return retval;
619 }
620
621 bool RE::Rewrite(string *out, const StringPiece &rewrite,
622                  const StringPiece &text, int *vec, int veclen) const {
623   for (const char *s = rewrite.data(), *end = s + rewrite.size();
624        s < end; s++) {
625     int c = *s;
626     if (c == '\\') {
627       c = *++s;
628       if (isdigit(c)) {
629         int n = (c - '0');
630         if (n >= veclen) {
631           //fprintf(stderr, requested group %d in regexp %.*s\n",
632           //        n, rewrite.size(), rewrite.data());
633           return false;
634         }
635         int start = vec[2 * n];
636         if (start >= 0)
637           out->append(text.data() + start, vec[2 * n + 1] - start);
638       } else if (c == '\\') {
639         *out += '\\';
640       } else {
641         //fprintf(stderr, "invalid rewrite pattern: %.*s\n",
642         //        rewrite.size(), rewrite.data());
643         return false;
644       }
645     } else {
646       *out += c;
647     }
648   }
649   return true;
650 }
651
652 // Return the number of capturing subpatterns, or -1 if the
653 // regexp wasn't valid on construction.
654 int RE::NumberOfCapturingGroups() const {
655   if (re_partial_ == NULL) return -1;
656
657   int result;
658   int pcre_retval = pcre_fullinfo(re_partial_,  // The regular expression object
659                                   NULL,         // We did not study the pattern
660                                   PCRE_INFO_CAPTURECOUNT,
661                                   &result);
662   assert(pcre_retval == 0);
663   return result;
664 }
665
666 /***** Parsers for various types *****/
667
668 bool Arg::parse_null(const char* str, int n, void* dest) {
669   (void)str;
670   (void)n;
671   // We fail if somebody asked us to store into a non-NULL void* pointer
672   return (dest == NULL);
673 }
674
675 bool Arg::parse_string(const char* str, int n, void* dest) {
676   if (dest == NULL) return true;
677   reinterpret_cast<string*>(dest)->assign(str, n);
678   return true;
679 }
680
681 bool Arg::parse_stringpiece(const char* str, int n, void* dest) {
682   if (dest == NULL) return true;
683   reinterpret_cast<StringPiece*>(dest)->set(str, n);
684   return true;
685 }
686
687 bool Arg::parse_char(const char* str, int n, void* dest) {
688   if (n != 1) return false;
689   if (dest == NULL) return true;
690   *(reinterpret_cast<char*>(dest)) = str[0];
691   return true;
692 }
693
694 bool Arg::parse_uchar(const char* str, int n, void* dest) {
695   if (n != 1) return false;
696   if (dest == NULL) return true;
697   *(reinterpret_cast<unsigned char*>(dest)) = str[0];
698   return true;
699 }
700
701 // Largest number spec that we are willing to parse
702 static const int kMaxNumberLength = 32;
703
704 // REQUIRES "buf" must have length at least kMaxNumberLength+1
705 // REQUIRES "n > 0"
706 // Copies "str" into "buf" and null-terminates if necessary.
707 // Returns one of:
708 //      a. "str" if no termination is needed
709 //      b. "buf" if the string was copied and null-terminated
710 //      c. "" if the input was invalid and has no hope of being parsed
711 static const char* TerminateNumber(char* buf, const char* str, int n) {
712   if ((n > 0) && isspace(*str)) {
713     // We are less forgiving than the strtoxxx() routines and do not
714     // allow leading spaces.
715     return "";
716   }
717
718   // See if the character right after the input text may potentially
719   // look like a digit.
720   if (isdigit(str[n]) ||
721       ((str[n] >= 'a') && (str[n] <= 'f')) ||
722       ((str[n] >= 'A') && (str[n] <= 'F'))) {
723     if (n > kMaxNumberLength) return ""; // Input too big to be a valid number
724     memcpy(buf, str, n);
725     buf[n] = '\0';
726     return buf;
727   } else {
728     // We can parse right out of the supplied string, so return it.
729     return str;
730   }
731 }
732
733 bool Arg::parse_long_radix(const char* str,
734                            int n,
735                            void* dest,
736                            int radix) {
737   if (n == 0) return false;
738   char buf[kMaxNumberLength+1];
739   str = TerminateNumber(buf, str, n);
740   char* end;
741   errno = 0;
742   long r = strtol(str, &end, radix);
743   if (end != str + n) return false;   // Leftover junk
744   if (errno) return false;
745   if (dest == NULL) return true;
746   *(reinterpret_cast<long*>(dest)) = r;
747   return true;
748 }
749
750 bool Arg::parse_ulong_radix(const char* str,
751                             int n,
752                             void* dest,
753                             int radix) {
754   if (n == 0) return false;
755   char buf[kMaxNumberLength+1];
756   str = TerminateNumber(buf, str, n);
757   if (str[0] == '-') return false;    // strtoul() on a negative number?!
758   char* end;
759   errno = 0;
760   unsigned long r = strtoul(str, &end, radix);
761   if (end != str + n) return false;   // Leftover junk
762   if (errno) return false;
763   if (dest == NULL) return true;
764   *(reinterpret_cast<unsigned long*>(dest)) = r;
765   return true;
766 }
767
768 bool Arg::parse_short_radix(const char* str,
769                             int n,
770                             void* dest,
771                             int radix) {
772   long r;
773   if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
774   if (r < SHRT_MIN || r > SHRT_MAX) return false;       // Out of range
775   if (dest == NULL) return true;
776   *(reinterpret_cast<short*>(dest)) = static_cast<short>(r);
777   return true;
778 }
779
780 bool Arg::parse_ushort_radix(const char* str,
781                              int n,
782                              void* dest,
783                              int radix) {
784   unsigned long r;
785   if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
786   if (r > USHRT_MAX) return false;                      // Out of range
787   if (dest == NULL) return true;
788   *(reinterpret_cast<unsigned short*>(dest)) = static_cast<unsigned short>(r);
789   return true;
790 }
791
792 bool Arg::parse_int_radix(const char* str,
793                           int n,
794                           void* dest,
795                           int radix) {
796   long r;
797   if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
798   if (r < INT_MIN || r > INT_MAX) return false;         // Out of range
799   if (dest == NULL) return true;
800   *(reinterpret_cast<int*>(dest)) = r;
801   return true;
802 }
803
804 bool Arg::parse_uint_radix(const char* str,
805                            int n,
806                            void* dest,
807                            int radix) {
808   unsigned long r;
809   if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
810   if (r > UINT_MAX) return false;                       // Out of range
811   if (dest == NULL) return true;
812   *(reinterpret_cast<unsigned int*>(dest)) = r;
813   return true;
814 }
815
816 bool Arg::parse_longlong_radix(const char* str,
817                                int n,
818                                void* dest,
819                                int radix) {
820 #ifndef HAVE_LONG_LONG
821   return false;
822 #else
823   if (n == 0) return false;
824   char buf[kMaxNumberLength+1];
825   str = TerminateNumber(buf, str, n);
826   char* end;
827   errno = 0;
828 #if defined HAVE_STRTOQ
829   long long r = strtoq(str, &end, radix);
830 #elif defined HAVE_STRTOLL
831   long long r = strtoll(str, &end, radix);
832 #elif defined HAVE__STRTOI64
833   long long r = _strtoi64(str, &end, radix);
834 #elif defined HAVE_STRTOIMAX
835   long long r = strtoimax(str, &end, radix);
836 #else
837 #error parse_longlong_radix: cannot convert input to a long-long
838 #endif
839   if (end != str + n) return false;   // Leftover junk
840   if (errno) return false;
841   if (dest == NULL) return true;
842   *(reinterpret_cast<long long*>(dest)) = r;
843   return true;
844 #endif   /* HAVE_LONG_LONG */
845 }
846
847 bool Arg::parse_ulonglong_radix(const char* str,
848                                 int n,
849                                 void* dest,
850                                 int radix) {
851 #ifndef HAVE_UNSIGNED_LONG_LONG
852   return false;
853 #else
854   if (n == 0) return false;
855   char buf[kMaxNumberLength+1];
856   str = TerminateNumber(buf, str, n);
857   if (str[0] == '-') return false;    // strtoull() on a negative number?!
858   char* end;
859   errno = 0;
860 #if defined HAVE_STRTOQ
861   unsigned long long r = strtouq(str, &end, radix);
862 #elif defined HAVE_STRTOLL
863   unsigned long long r = strtoull(str, &end, radix);
864 #elif defined HAVE__STRTOI64
865   unsigned long long r = _strtoui64(str, &end, radix);
866 #elif defined HAVE_STRTOIMAX
867   unsigned long long r = strtoumax(str, &end, radix);
868 #else
869 #error parse_ulonglong_radix: cannot convert input to a long-long
870 #endif
871   if (end != str + n) return false;   // Leftover junk
872   if (errno) return false;
873   if (dest == NULL) return true;
874   *(reinterpret_cast<unsigned long long*>(dest)) = r;
875   return true;
876 #endif   /* HAVE_UNSIGNED_LONG_LONG */
877 }
878
879 bool Arg::parse_double(const char* str, int n, void* dest) {
880   if (n == 0) return false;
881   static const int kMaxLength = 200;
882   char buf[kMaxLength];
883   if (n >= kMaxLength) return false;
884   memcpy(buf, str, n);
885   buf[n] = '\0';
886   errno = 0;
887   char* end;
888   double r = strtod(buf, &end);
889   if (end != buf + n) return false;   // Leftover junk
890   if (errno) return false;
891   if (dest == NULL) return true;
892   *(reinterpret_cast<double*>(dest)) = r;
893   return true;
894 }
895
896 bool Arg::parse_float(const char* str, int n, void* dest) {
897   double r;
898   if (!parse_double(str, n, &r)) return false;
899   if (dest == NULL) return true;
900   *(reinterpret_cast<float*>(dest)) = static_cast<float>(r);
901   return true;
902 }
903
904
905 #define DEFINE_INTEGER_PARSERS(name)                                    \
906   bool Arg::parse_##name(const char* str, int n, void* dest) {          \
907     return parse_##name##_radix(str, n, dest, 10);                      \
908   }                                                                     \
909   bool Arg::parse_##name##_hex(const char* str, int n, void* dest) {    \
910     return parse_##name##_radix(str, n, dest, 16);                      \
911   }                                                                     \
912   bool Arg::parse_##name##_octal(const char* str, int n, void* dest) {  \
913     return parse_##name##_radix(str, n, dest, 8);                       \
914   }                                                                     \
915   bool Arg::parse_##name##_cradix(const char* str, int n, void* dest) { \
916     return parse_##name##_radix(str, n, dest, 0);                       \
917   }
918
919 DEFINE_INTEGER_PARSERS(short)      /*                                   */
920 DEFINE_INTEGER_PARSERS(ushort)     /*                                   */
921 DEFINE_INTEGER_PARSERS(int)        /* Don't use semicolons after these  */
922 DEFINE_INTEGER_PARSERS(uint)       /* statements because they can cause */
923 DEFINE_INTEGER_PARSERS(long)       /* compiler warnings if the checking */
924 DEFINE_INTEGER_PARSERS(ulong)      /* level is turned up high enough.   */
925 DEFINE_INTEGER_PARSERS(longlong)   /*                                   */
926 DEFINE_INTEGER_PARSERS(ulonglong)  /*                                   */
927
928 #undef DEFINE_INTEGER_PARSERS
929
930 }   // namespace pcrecpp