/[pcre]/code/trunk/pcrecpp.cc
ViewVC logotype

Diff of /code/trunk/pcrecpp.cc

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 77 by nigel, Sat Feb 24 21:40:45 2007 UTC revision 199 by ph10, Tue Jul 31 14:39:09 2007 UTC
# Line 29  Line 29 
29  //  //
30  // Author: Sanjay Ghemawat  // Author: Sanjay Ghemawat
31    
32    #ifdef HAVE_CONFIG_H
33    #include <config.h>
34    #endif
35    
36  #include <stdlib.h>  #include <stdlib.h>
37  #include <stdio.h>  #include <stdio.h>
38  #include <ctype.h>  #include <ctype.h>
# Line 36  Line 40 
40  #include <assert.h>  #include <assert.h>
41  #include <errno.h>  #include <errno.h>
42  #include <string>  #include <string>
43  #include "config.h"  #include <algorithm>
44  // We need this to compile the proper dll on windows/msys.  This is copied  
45  // from pcre_internal.h.  It would probably be better just to include that.  #include "pcrecpp_internal.h"
46  #define PCRE_DEFINITION  /* Win32 __declspec(export) trigger for .dll */  #include <pcre.h>
 #include "pcre.h"  
 #include "pcre_stringpiece.h"  
47  #include "pcrecpp.h"  #include "pcrecpp.h"
48    #include "pcre_stringpiece.h"
49    
50    
51  namespace pcrecpp {  namespace pcrecpp {
# Line 52  static const int kMaxArgs = 16; Line 55  static const int kMaxArgs = 16;
55  static const int kVecSize = (1 + kMaxArgs) * 3;  // results + PCRE workspace  static const int kVecSize = (1 + kMaxArgs) * 3;  // results + PCRE workspace
56    
57  // Special object that stands-in for no argument  // Special object that stands-in for no argument
58  Arg no_arg((void*)NULL);  PCRECPP_EXP_DECL Arg no_arg((void*)NULL);
59    
60  // If a regular expression has no error, its error_ field points here  // If a regular expression has no error, its error_ field points here
61  static const string empty_string;  static const string empty_string;
# Line 60  static const string empty_string; Line 63  static const string empty_string;
63  // If the user doesn't ask for any options, we just use this one  // If the user doesn't ask for any options, we just use this one
64  static RE_Options default_options;  static RE_Options default_options;
65    
66  void RE::Init(const char* pat, const RE_Options* options) {  void RE::Init(const string& pat, const RE_Options* options) {
67    pattern_ = pat;    pattern_ = pat;
68    if (options == NULL) {    if (options == NULL) {
69      options_ = default_options;      options_ = default_options;
# Line 73  void RE::Init(const char* pat, const RE_ Line 76  void RE::Init(const char* pat, const RE_
76    
77    re_partial_ = Compile(UNANCHORED);    re_partial_ = Compile(UNANCHORED);
78    if (re_partial_ != NULL) {    if (re_partial_ != NULL) {
79      // Check for complicated patterns.  The following change is      re_full_ = Compile(ANCHOR_BOTH);
     // conservative in that it may treat some "simple" patterns  
     // as "complex" (e.g., if the vertical bar is in a character  
     // class or is escaped).  But it seems good enough.  
     if (strchr(pat, '|') == NULL) {  
       // Simple pattern: we can use position-based checks to perform  
       // fully anchored matches  
       re_full_ = re_partial_;  
     } else {  
       // We need a special pattern for anchored matches  
       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() {  RE::~RE() {
91    if (re_full_ != NULL && re_full_ != re_partial_) (*pcre_free)(re_full_);    Cleanup();
   if (re_partial_ != NULL)                         (*pcre_free)(re_partial_);  
   if (error_ != &empty_string)                     delete error_;  
92  }  }
93    
94    
95  pcre* RE::Compile(Anchor anchor) {  pcre* RE::Compile(Anchor anchor) {
96    // First, convert RE_Options into pcre options    // First, convert RE_Options into pcre options
97    int pcre_options = 0;    int pcre_options = 0;
98    if (options_.utf8())    pcre_options = options_.all_options();
     pcre_options |= PCRE_UTF8;  
99    
100    // Special treatment for anchoring.  This is needed because at    // Special treatment for anchoring.  This is needed because at
101    // runtime pcre only provides an option for anchoring at the    // runtime pcre only provides an option for anchoring at the
# Line 332  bool RE::Replace(const StringPiece& rewr Line 329  bool RE::Replace(const StringPiece& rewr
329    return true;    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    static int NewlineMode(int pcre_options) {
335      // TODO: if we can make it threadsafe, cache this var
336      int newline_mode = 0;
337      /* if (newline_mode) return newline_mode; */  // do this once it's cached
338      if (pcre_options & (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF)) {
339        newline_mode = (pcre_options &
340                        (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF));
341      } else {
342        int newline;
343        pcre_config(PCRE_CONFIG_NEWLINE, &newline);
344        if (newline == 10)
345          newline_mode = PCRE_NEWLINE_LF;
346        else if (newline == 13)
347          newline_mode = PCRE_NEWLINE_CR;
348        else if (newline == 3338)
349          newline_mode = PCRE_NEWLINE_CRLF;
350        else
351          assert("" == "Unexpected return value from pcre_config(NEWLINE)");
352      }
353      return newline_mode;
354    }
355    
356  int RE::GlobalReplace(const StringPiece& rewrite,  int RE::GlobalReplace(const StringPiece& rewrite,
357                        string *str) const {                        string *str) const {
358    int count = 0;    int count = 0;
# Line 350  int RE::GlobalReplace(const StringPiece& Line 371  int RE::GlobalReplace(const StringPiece&
371      if (matchstart == matchend && matchstart == lastend) {      if (matchstart == matchend && matchstart == lastend) {
372        // advance one character if we matched an empty string at the same        // advance one character if we matched an empty string at the same
373        // place as the last match occurred        // place as the last match occurred
374        if (start < static_cast<int>(str->length()))        matchend = start + 1;
375          out.push_back((*str)[start]);        // If the current char is CR and we're in CRLF mode, skip LF too.
376        start++;        // Note it's better to call pcre_fullinfo() than to examine
377          // all_options(), since options_ could have changed bewteen
378          // compile-time and now, but this is simpler and safe enough.
379          if (start+1 < static_cast<int>(str->length()) &&
380              (*str)[start] == '\r' && (*str)[start+1] == '\n' &&
381              NewlineMode(options_.all_options()) == PCRE_NEWLINE_CRLF) {
382            matchend++;
383          }
384          // We also need to advance more than one char if we're in utf8 mode.
385    #ifdef SUPPORT_UTF8
386          if (options_.utf8()) {
387            while (matchend < static_cast<int>(str->length()) &&
388                   ((*str)[matchend] & 0xc0) == 0x80)
389              matchend++;
390          }
391    #endif
392          if (matchend <= static_cast<int>(str->length()))
393            out.append(*str, start, matchend - start);
394          start = matchend;
395      } else {      } else {
396        out.append(*str, start, matchstart - start);        out.append(*str, start, matchstart - start);
397        Rewrite(&out, rewrite, *str, vec, matches);        Rewrite(&out, rewrite, *str, vec, matches);
# Line 378  bool RE::Extract(const StringPiece& rewr Line 417  bool RE::Extract(const StringPiece& rewr
417    int matches = TryMatch(text, 0, UNANCHORED, vec, kVecSize);    int matches = TryMatch(text, 0, UNANCHORED, vec, kVecSize);
418    if (matches == 0)    if (matches == 0)
419      return false;      return false;
420    out->clear();    out->erase();
421    return Rewrite(out, rewrite, text, vec, matches);    return Rewrite(out, rewrite, text, vec, matches);
422  }  }
423    
424    /*static*/ string RE::QuoteMeta(const StringPiece& unquoted) {
425      string result;
426    
427      // Escape any ascii character not in [A-Za-z_0-9].
428      //
429      // Note that it's legal to escape a character even if it has no
430      // special meaning in a regular expression -- so this function does
431      // that.  (This also makes it identical to the perl function of the
432      // same name; see `perldoc -f quotemeta`.)
433      for (int ii = 0; ii < unquoted.size(); ++ii) {
434        // Note that using 'isalnum' here raises the benchmark time from
435        // 32ns to 58ns:
436        if ((unquoted[ii] < 'a' || unquoted[ii] > 'z') &&
437            (unquoted[ii] < 'A' || unquoted[ii] > 'Z') &&
438            (unquoted[ii] < '0' || unquoted[ii] > '9') &&
439            unquoted[ii] != '_' &&
440            // If this is the part of a UTF8 or Latin1 character, we need
441            // to copy this byte without escaping.  Experimentally this is
442            // what works correctly with the regexp library.
443            !(unquoted[ii] & 128)) {
444          result += '\\';
445        }
446        result += unquoted[ii];
447      }
448    
449      return result;
450    }
451    
452  /***** Actual matching and rewriting code *****/  /***** Actual matching and rewriting code *****/
453    
454  int RE::TryMatch(const StringPiece& text,  int RE::TryMatch(const StringPiece& text,
# Line 395  int RE::TryMatch(const StringPiece& text Line 462  int RE::TryMatch(const StringPiece& text
462      return 0;      return 0;
463    }    }
464    
465    pcre_extra extra = { 0 };    pcre_extra extra = { 0, 0, 0, 0, 0, 0 };
466    if (options_.match_limit() > 0) {    if (options_.match_limit() > 0) {
467      extra.flags = PCRE_EXTRA_MATCH_LIMIT;      extra.flags |= PCRE_EXTRA_MATCH_LIMIT;
468      extra.match_limit = options_.match_limit();      extra.match_limit = options_.match_limit();
469    }    }
470      if (options_.match_limit_recursion() > 0) {
471        extra.flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;
472        extra.match_limit_recursion = options_.match_limit_recursion();
473      }
474    int rc = pcre_exec(re,              // The regular expression object    int rc = pcre_exec(re,              // The regular expression object
475                       &extra,                       &extra,
476                       text.data(),                       (text.data() == NULL) ? "" : text.data(),
477                       text.size(),                       text.size(),
478                       startpos,                       startpos,
479                       (anchor == UNANCHORED) ? 0 : PCRE_ANCHORED,                       (anchor == UNANCHORED) ? 0 : PCRE_ANCHORED,
# Line 424  int RE::TryMatch(const StringPiece& text Line 495  int RE::TryMatch(const StringPiece& text
495      rc = vecsize / 2;      rc = vecsize / 2;
496    }    }
497    
   if ((anchor == ANCHOR_BOTH) && (re_full_ == re_partial_)) {  
     // We need an extra check to make sure that the match extended  
     // to the end of the input string  
     assert(vec[0] == 0);                 // PCRE_ANCHORED forces starting match  
     if (vec[1] != text.size()) return 0; // Did not get ending match  
   }  
   
498    return rc;    return rc;
499  }  }
500    
# Line 449  bool RE::DoMatchImpl(const StringPiece& Line 513  bool RE::DoMatchImpl(const StringPiece&
513    
514    *consumed = vec[1];    *consumed = vec[1];
515    
516    if (args == NULL) {    if (n == 0 || args == NULL) {
517      // We are not interested in results      // We are not interested in results
518      return true;      return true;
519    }    }
520    
521      if (NumberOfCapturingGroups() < n) {
522        // RE has fewer capturing groups than number of arg pointers passed in
523        return false;
524      }
525    
526    // If we got here, we must have matched the whole pattern.    // If we got here, we must have matched the whole pattern.
527    // We do not need (can not do) any more checks on the value of 'matches' here    // We do not need (can not do) any more checks on the value of 'matches' here
528    // -- see the comment for TryMatch.    // -- see the comment for TryMatch.
# Line 517  bool RE::Rewrite(string *out, const Stri Line 586  bool RE::Rewrite(string *out, const Stri
586    
587  // Return the number of capturing subpatterns, or -1 if the  // Return the number of capturing subpatterns, or -1 if the
588  // regexp wasn't valid on construction.  // regexp wasn't valid on construction.
589  int RE::NumberOfCapturingGroups() {  int RE::NumberOfCapturingGroups() const {
590    if (re_partial_ == NULL) return -1;    if (re_partial_ == NULL) return -1;
591    
592    int result;    int result;
# Line 613  bool Arg::parse_ulong_radix(const char* Line 682  bool Arg::parse_ulong_radix(const char*
682    if (n == 0) return false;    if (n == 0) return false;
683    char buf[kMaxNumberLength+1];    char buf[kMaxNumberLength+1];
684    str = TerminateNumber(buf, str, n);    str = TerminateNumber(buf, str, n);
685      if (str[0] == '-') return false;    // strtoul() on a negative number?!
686    char* end;    char* end;
687    errno = 0;    errno = 0;
688    unsigned long r = strtoul(str, &end, radix);    unsigned long r = strtoul(str, &end, radix);
# Line 702  bool Arg::parse_ulonglong_radix(const ch Line 772  bool Arg::parse_ulonglong_radix(const ch
772    if (n == 0) return false;    if (n == 0) return false;
773    char buf[kMaxNumberLength+1];    char buf[kMaxNumberLength+1];
774    str = TerminateNumber(buf, str, n);    str = TerminateNumber(buf, str, n);
775      if (str[0] == '-') return false;    // strtoull() on a negative number?!
776    char* end;    char* end;
777    errno = 0;    errno = 0;
778  #if defined HAVE_STRTOQ  #if defined HAVE_STRTOQ
# Line 756  bool Arg::parse_float(const char* str, i Line 827  bool Arg::parse_float(const char* str, i
827      return parse_##name##_radix(str, n, dest, 0);                       \      return parse_##name##_radix(str, n, dest, 0);                       \
828    }    }
829    
830  DEFINE_INTEGER_PARSERS(short);  DEFINE_INTEGER_PARSERS(short)      /*                                   */
831  DEFINE_INTEGER_PARSERS(ushort);  DEFINE_INTEGER_PARSERS(ushort)     /*                                   */
832  DEFINE_INTEGER_PARSERS(int);  DEFINE_INTEGER_PARSERS(int)        /* Don't use semicolons after these  */
833  DEFINE_INTEGER_PARSERS(uint);  DEFINE_INTEGER_PARSERS(uint)       /* statements because they can cause */
834  DEFINE_INTEGER_PARSERS(long);  DEFINE_INTEGER_PARSERS(long)       /* compiler warnings if the checking */
835  DEFINE_INTEGER_PARSERS(ulong);  DEFINE_INTEGER_PARSERS(ulong)      /* level is turned up high enough.   */
836  DEFINE_INTEGER_PARSERS(longlong);  DEFINE_INTEGER_PARSERS(longlong)   /*                                   */
837  DEFINE_INTEGER_PARSERS(ulonglong);  DEFINE_INTEGER_PARSERS(ulonglong)  /*                                   */
838    
839  #undef DEFINE_INTEGER_PARSERS  #undef DEFINE_INTEGER_PARSERS
840    

Legend:
Removed from v.77  
changed lines
  Added in v.199

webmaster@exim.org
ViewVC Help
Powered by ViewVC 1.1.12