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