blob: 48caab1315264d9fdb92c881b6dc3e9d368d2cea [file] [log] [blame]
Torok Edwine14d4cd2009-08-30 08:24:09 +00001//===-- 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//===----------------------------------------------------------------------===//
Chris Lattner1ce83622009-09-24 20:15:51 +000013
Torok Edwine14d4cd2009-08-30 08:24:09 +000014#include "llvm/Support/Regex.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallVector.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000016#include "llvm/ADT/StringRef.h"
Yaron Keren075759a2015-03-30 15:42:36 +000017#include "llvm/ADT/Twine.h"
Torok Edwine14d4cd2009-08-30 08:24:09 +000018#include <string>
Jonas Devlieghere2b8b90a2018-03-12 11:01:05 +000019
20// Important this comes last because it defines "_REGEX_H_". At least on
21// Darwin, if included before any header that (transitively) includes
22// xlocale.h, this will cause trouble, because of missing regex-related types.
23#include "regex_impl.h"
24
Torok Edwine14d4cd2009-08-30 08:24:09 +000025using namespace llvm;
Chris Lattner1ce83622009-09-24 20:15:51 +000026
Chandler Carruth1ab16f82016-09-01 09:31:02 +000027Regex::Regex() : preg(nullptr), error(REG_BADPAT) {}
George Rimara9ff0722016-09-01 08:00:28 +000028
Benjamin Kramer92d89982010-07-14 22:38:02 +000029Regex::Regex(StringRef regex, unsigned Flags) {
Torok Edwine14d4cd2009-08-30 08:24:09 +000030 unsigned flags = 0;
Chris Lattnerf08d2db2009-09-24 21:47:32 +000031 preg = new llvm_regex();
Torok Edwine14d4cd2009-08-30 08:24:09 +000032 preg->re_endp = regex.end();
Jonas Devlieghere2b8b90a2018-03-12 11:01:05 +000033 if (Flags & IgnoreCase)
Torok Edwine14d4cd2009-08-30 08:24:09 +000034 flags |= REG_ICASE;
Torok Edwine14d4cd2009-08-30 08:24:09 +000035 if (Flags & Newline)
36 flags |= REG_NEWLINE;
Eli Bendersky10f22d72012-11-28 19:00:02 +000037 if (!(Flags & BasicRegex))
38 flags |= REG_EXTENDED;
39 error = llvm_regcomp(preg, regex.data(), flags|REG_PEND);
Torok Edwine14d4cd2009-08-30 08:24:09 +000040}
41
George Rimard8dfeec2016-09-02 08:44:46 +000042Regex::Regex(Regex &&regex) {
43 preg = regex.preg;
44 error = regex.error;
45 regex.preg = nullptr;
46 regex.error = REG_BADPAT;
47}
48
Chris Lattner1ce83622009-09-24 20:15:51 +000049Regex::~Regex() {
David Blaikie7a238042014-01-02 19:04:59 +000050 if (preg) {
51 llvm_regfree(preg);
52 delete preg;
53 }
Torok Edwine14d4cd2009-08-30 08:24:09 +000054}
55
George Burgess IVb71bc442017-04-18 01:04:05 +000056bool Regex::isValid(std::string &Error) const {
Chris Lattner37d80152009-09-26 21:27:04 +000057 if (!error)
58 return true;
Jonas Devlieghere2b8b90a2018-03-12 11:01:05 +000059
Craig Topperc10719f2014-04-07 04:17:22 +000060 size_t len = llvm_regerror(error, preg, nullptr, 0);
Jonas Devlieghere2b8b90a2018-03-12 11:01:05 +000061
Alexey Samsonov96dd18c2013-08-08 17:32:45 +000062 Error.resize(len - 1);
Chris Lattner37d80152009-09-26 21:27:04 +000063 llvm_regerror(error, preg, &Error[0], len);
64 return false;
65}
66
67/// getNumMatches - In a valid regex, return the number of parenthesized
68/// matches it contains.
69unsigned Regex::getNumMatches() const {
70 return preg->re_nsub;
71}
72
Benjamin Kramer92d89982010-07-14 22:38:02 +000073bool Regex::match(StringRef String, SmallVectorImpl<StringRef> *Matches){
George Rimard8dfeec2016-09-02 08:44:46 +000074 if (error)
75 return false;
76
Torok Edwine14d4cd2009-08-30 08:24:09 +000077 unsigned nmatch = Matches ? preg->re_nsub+1 : 0;
78
Torok Edwine14d4cd2009-08-30 08:24:09 +000079 // pmatch needs to have at least one element.
Chris Lattnerf08d2db2009-09-24 21:47:32 +000080 SmallVector<llvm_regmatch_t, 8> pm;
Torok Edwine14d4cd2009-08-30 08:24:09 +000081 pm.resize(nmatch > 0 ? nmatch : 1);
82 pm[0].rm_so = 0;
83 pm[0].rm_eo = String.size();
84
85 int rc = llvm_regexec(preg, String.data(), nmatch, pm.data(), REG_STARTEND);
86
87 if (rc == REG_NOMATCH)
88 return false;
89 if (rc != 0) {
90 // regexec can fail due to invalid pattern or running out of memory.
91 error = rc;
92 return false;
93 }
94
95 // There was a match.
96
97 if (Matches) { // match position requested
Chris Lattner37d80152009-09-26 21:27:04 +000098 Matches->clear();
Jonas Devlieghere2b8b90a2018-03-12 11:01:05 +000099
Chris Lattner1ce83622009-09-24 20:15:51 +0000100 for (unsigned i = 0; i != nmatch; ++i) {
Torok Edwine14d4cd2009-08-30 08:24:09 +0000101 if (pm[i].rm_so == -1) {
102 // this group didn't match
103 Matches->push_back(StringRef());
104 continue;
105 }
Chris Lattner0687ec72011-04-09 06:29:24 +0000106 assert(pm[i].rm_eo >= pm[i].rm_so);
Torok Edwine14d4cd2009-08-30 08:24:09 +0000107 Matches->push_back(StringRef(String.data()+pm[i].rm_so,
108 pm[i].rm_eo-pm[i].rm_so));
109 }
110 }
111
112 return true;
113}
Daniel Dunbareb857112010-02-17 20:08:42 +0000114
115std::string Regex::sub(StringRef Repl, StringRef String,
116 std::string *Error) {
117 SmallVector<StringRef, 8> Matches;
118
119 // Reset error, if given.
120 if (Error && !Error->empty()) *Error = "";
121
122 // Return the input if there was no match.
123 if (!match(String, &Matches))
124 return String;
125
126 // Otherwise splice in the replacement string, starting with the prefix before
127 // the match.
128 std::string Res(String.begin(), Matches[0].begin());
129
130 // Then the replacement string, honoring possible substitutions.
131 while (!Repl.empty()) {
132 // Skip to the next escape.
133 std::pair<StringRef, StringRef> Split = Repl.split('\\');
134
135 // Add the skipped substring.
136 Res += Split.first;
137
138 // Check for terminimation and trailing backslash.
139 if (Split.second.empty()) {
140 if (Repl.size() != Split.first.size() &&
141 Error && Error->empty())
142 *Error = "replacement string contained trailing backslash";
143 break;
144 }
145
146 // Otherwise update the replacement string and interpret escapes.
147 Repl = Split.second;
148
149 // FIXME: We should have a StringExtras function for mapping C99 escapes.
150 switch (Repl[0]) {
151 // Treat all unrecognized characters as self-quoting.
152 default:
153 Res += Repl[0];
154 Repl = Repl.substr(1);
155 break;
156
157 // Single character escapes.
158 case 't':
159 Res += '\t';
160 Repl = Repl.substr(1);
161 break;
162 case 'n':
163 Res += '\n';
164 Repl = Repl.substr(1);
165 break;
166
167 // Decimal escapes are backreferences.
168 case '0': case '1': case '2': case '3': case '4':
169 case '5': case '6': case '7': case '8': case '9': {
170 // Extract the backreference number.
171 StringRef Ref = Repl.slice(0, Repl.find_first_not_of("0123456789"));
172 Repl = Repl.substr(Ref.size());
173
174 unsigned RefValue;
175 if (!Ref.getAsInteger(10, RefValue) &&
176 RefValue < Matches.size())
177 Res += Matches[RefValue];
178 else if (Error && Error->empty())
Yaron Keren075759a2015-03-30 15:42:36 +0000179 *Error = ("invalid backreference string '" + Twine(Ref) + "'").str();
Daniel Dunbareb857112010-02-17 20:08:42 +0000180 break;
181 }
182 }
183 }
184
185 // And finally the suffix.
186 Res += StringRef(Matches[0].end(), String.end() - Matches[0].end());
187
188 return Res;
189}
Peter Collingbournefe8cd752013-08-05 17:47:59 +0000190
Alp Tokerd0d1a742013-12-12 02:51:58 +0000191// These are the special characters matched in functions like "p_ere_exp".
192static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
193
Peter Collingbournefe8cd752013-08-05 17:47:59 +0000194bool Regex::isLiteralERE(StringRef Str) {
195 // Check for regex metacharacters. This list was derived from our regex
196 // implementation in regcomp.c and double checked against the POSIX extended
197 // regular expression specification.
Alp Tokerd0d1a742013-12-12 02:51:58 +0000198 return Str.find_first_of(RegexMetachars) == StringRef::npos;
Peter Collingbournefe8cd752013-08-05 17:47:59 +0000199}
Hans Wennborg6f4f77b2013-12-12 00:06:41 +0000200
201std::string Regex::escape(StringRef String) {
202 std::string RegexStr;
Hans Wennborg6f4f77b2013-12-12 00:06:41 +0000203 for (unsigned i = 0, e = String.size(); i != e; ++i) {
Alp Tokerd0d1a742013-12-12 02:51:58 +0000204 if (strchr(RegexMetachars, String[i]))
Hans Wennborg6f4f77b2013-12-12 00:06:41 +0000205 RegexStr += '\\';
Alp Tokerd0d1a742013-12-12 02:51:58 +0000206 RegexStr += String[i];
Hans Wennborg6f4f77b2013-12-12 00:06:41 +0000207 }
208
209 return RegexStr;
210}