Home | History | Annotate | Download | only in Support
      1 //===-- Regex.cpp - Regular Expression matcher implementation -------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements a POSIX regular expression matcher.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm/Support/Regex.h"
     15 #include "regex_impl.h"
     16 #include "llvm/ADT/SmallVector.h"
     17 #include "llvm/ADT/StringRef.h"
     18 #include "llvm/ADT/Twine.h"
     19 #include <string>
     20 using namespace llvm;
     21 
     22 Regex::Regex(StringRef regex, unsigned Flags) {
     23   unsigned flags = 0;
     24   preg = new llvm_regex();
     25   preg->re_endp = regex.end();
     26   if (Flags & IgnoreCase)
     27     flags |= REG_ICASE;
     28   if (Flags & Newline)
     29     flags |= REG_NEWLINE;
     30   if (!(Flags & BasicRegex))
     31     flags |= REG_EXTENDED;
     32   error = llvm_regcomp(preg, regex.data(), flags|REG_PEND);
     33 }
     34 
     35 Regex::~Regex() {
     36   if (preg) {
     37     llvm_regfree(preg);
     38     delete preg;
     39   }
     40 }
     41 
     42 bool Regex::isValid(std::string &Error) {
     43   if (!error)
     44     return true;
     45 
     46   size_t len = llvm_regerror(error, preg, nullptr, 0);
     47 
     48   Error.resize(len - 1);
     49   llvm_regerror(error, preg, &Error[0], len);
     50   return false;
     51 }
     52 
     53 /// getNumMatches - In a valid regex, return the number of parenthesized
     54 /// matches it contains.
     55 unsigned Regex::getNumMatches() const {
     56   return preg->re_nsub;
     57 }
     58 
     59 bool Regex::match(StringRef String, SmallVectorImpl<StringRef> *Matches){
     60   unsigned nmatch = Matches ? preg->re_nsub+1 : 0;
     61 
     62   // pmatch needs to have at least one element.
     63   SmallVector<llvm_regmatch_t, 8> pm;
     64   pm.resize(nmatch > 0 ? nmatch : 1);
     65   pm[0].rm_so = 0;
     66   pm[0].rm_eo = String.size();
     67 
     68   int rc = llvm_regexec(preg, String.data(), nmatch, pm.data(), REG_STARTEND);
     69 
     70   if (rc == REG_NOMATCH)
     71     return false;
     72   if (rc != 0) {
     73     // regexec can fail due to invalid pattern or running out of memory.
     74     error = rc;
     75     return false;
     76   }
     77 
     78   // There was a match.
     79 
     80   if (Matches) { // match position requested
     81     Matches->clear();
     82 
     83     for (unsigned i = 0; i != nmatch; ++i) {
     84       if (pm[i].rm_so == -1) {
     85         // this group didn't match
     86         Matches->push_back(StringRef());
     87         continue;
     88       }
     89       assert(pm[i].rm_eo >= pm[i].rm_so);
     90       Matches->push_back(StringRef(String.data()+pm[i].rm_so,
     91                                    pm[i].rm_eo-pm[i].rm_so));
     92     }
     93   }
     94 
     95   return true;
     96 }
     97 
     98 std::string Regex::sub(StringRef Repl, StringRef String,
     99                        std::string *Error) {
    100   SmallVector<StringRef, 8> Matches;
    101 
    102   // Reset error, if given.
    103   if (Error && !Error->empty()) *Error = "";
    104 
    105   // Return the input if there was no match.
    106   if (!match(String, &Matches))
    107     return String;
    108 
    109   // Otherwise splice in the replacement string, starting with the prefix before
    110   // the match.
    111   std::string Res(String.begin(), Matches[0].begin());
    112 
    113   // Then the replacement string, honoring possible substitutions.
    114   while (!Repl.empty()) {
    115     // Skip to the next escape.
    116     std::pair<StringRef, StringRef> Split = Repl.split('\\');
    117 
    118     // Add the skipped substring.
    119     Res += Split.first;
    120 
    121     // Check for terminimation and trailing backslash.
    122     if (Split.second.empty()) {
    123       if (Repl.size() != Split.first.size() &&
    124           Error && Error->empty())
    125         *Error = "replacement string contained trailing backslash";
    126       break;
    127     }
    128 
    129     // Otherwise update the replacement string and interpret escapes.
    130     Repl = Split.second;
    131 
    132     // FIXME: We should have a StringExtras function for mapping C99 escapes.
    133     switch (Repl[0]) {
    134       // Treat all unrecognized characters as self-quoting.
    135     default:
    136       Res += Repl[0];
    137       Repl = Repl.substr(1);
    138       break;
    139 
    140       // Single character escapes.
    141     case 't':
    142       Res += '\t';
    143       Repl = Repl.substr(1);
    144       break;
    145     case 'n':
    146       Res += '\n';
    147       Repl = Repl.substr(1);
    148       break;
    149 
    150       // Decimal escapes are backreferences.
    151     case '0': case '1': case '2': case '3': case '4':
    152     case '5': case '6': case '7': case '8': case '9': {
    153       // Extract the backreference number.
    154       StringRef Ref = Repl.slice(0, Repl.find_first_not_of("0123456789"));
    155       Repl = Repl.substr(Ref.size());
    156 
    157       unsigned RefValue;
    158       if (!Ref.getAsInteger(10, RefValue) &&
    159           RefValue < Matches.size())
    160         Res += Matches[RefValue];
    161       else if (Error && Error->empty())
    162         *Error = ("invalid backreference string '" + Twine(Ref) + "'").str();
    163       break;
    164     }
    165     }
    166   }
    167 
    168   // And finally the suffix.
    169   Res += StringRef(Matches[0].end(), String.end() - Matches[0].end());
    170 
    171   return Res;
    172 }
    173 
    174 // These are the special characters matched in functions like "p_ere_exp".
    175 static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
    176 
    177 bool Regex::isLiteralERE(StringRef Str) {
    178   // Check for regex metacharacters.  This list was derived from our regex
    179   // implementation in regcomp.c and double checked against the POSIX extended
    180   // regular expression specification.
    181   return Str.find_first_of(RegexMetachars) == StringRef::npos;
    182 }
    183 
    184 std::string Regex::escape(StringRef String) {
    185   std::string RegexStr;
    186   for (unsigned i = 0, e = String.size(); i != e; ++i) {
    187     if (strchr(RegexMetachars, String[i]))
    188       RegexStr += '\\';
    189     RegexStr += String[i];
    190   }
    191 
    192   return RegexStr;
    193 }
    194