~ubuntu-branches/ubuntu/trusty/mongodb/trusty-proposed

« back to all changes in this revision

Viewing changes to pcre-7.4/pcrecpp.cc

  • Committer: Bazaar Package Importer
  • Author(s): Antonin Kral
  • Date: 2010-01-29 19:48:45 UTC
  • Revision ID: james.westby@ubuntu.com-20100129194845-8wbmkf626fwcavc9
Tags: upstream-1.3.1
ImportĀ upstreamĀ versionĀ 1.3.1

Show diffs side-by-side

added added

removed removed

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