1 //===-- Regex.cpp - Regular Expression matcher implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a POSIX regular expression matcher.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/Regex.h"
15 #include "regex_impl.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/raw_ostream.h"
22 Regex::Regex(StringRef regex, unsigned Flags) {
24 preg = new llvm_regex();
25 preg->re_endp = regex.end();
26 if (Flags & IgnoreCase)
30 if (!(Flags & BasicRegex))
31 flags |= REG_EXTENDED;
32 error = llvm_regcomp(preg, regex.data(), flags|REG_PEND);
42 bool Regex::isValid(std::string &Error) {
46 size_t len = llvm_regerror(error, preg, NULL, 0);
48 Error.resize(len - 1);
49 llvm_regerror(error, preg, &Error[0], len);
53 /// getNumMatches - In a valid regex, return the number of parenthesized
54 /// matches it contains.
55 unsigned Regex::getNumMatches() const {
59 bool Regex::match(StringRef String, SmallVectorImpl<StringRef> *Matches){
60 unsigned nmatch = Matches ? preg->re_nsub+1 : 0;
62 // pmatch needs to have at least one element.
63 SmallVector<llvm_regmatch_t, 8> pm;
64 pm.resize(nmatch > 0 ? nmatch : 1);
66 pm[0].rm_eo = String.size();
68 int rc = llvm_regexec(preg, String.data(), nmatch, pm.data(), REG_STARTEND);
70 if (rc == REG_NOMATCH)
73 // regexec can fail due to invalid pattern or running out of memory.
80 if (Matches) { // match position requested
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());
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));
98 std::string Regex::sub(StringRef Repl, StringRef String,
100 SmallVector<StringRef, 8> Matches;
102 // Reset error, if given.
103 if (Error && !Error->empty()) *Error = "";
105 // Return the input if there was no match.
106 if (!match(String, &Matches))
109 // Otherwise splice in the replacement string, starting with the prefix before
111 std::string Res(String.begin(), Matches[0].begin());
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('\\');
118 // Add the skipped substring.
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";
129 // Otherwise update the replacement string and interpret escapes.
132 // FIXME: We should have a StringExtras function for mapping C99 escapes.
134 // Treat all unrecognized characters as self-quoting.
137 Repl = Repl.substr(1);
140 // Single character escapes.
143 Repl = Repl.substr(1);
147 Repl = Repl.substr(1);
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());
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 '" + Ref.str() + "'";
168 // And finally the suffix.
169 Res += StringRef(Matches[0].end(), String.end() - Matches[0].end());
174 // These are the special characters matched in functions like "p_ere_exp".
175 static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
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;
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]))
189 RegexStr += String[i];