Regex.cpp 5.3 KB

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