blob: 60ce528e577cdf17dfc92e855963a491bbcb2998 [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 "regex_impl.h"
16#include "llvm/ADT/SmallVector.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000017#include "llvm/ADT/StringRef.h"
Yaron Keren075759a2015-03-30 15:42:36 +000018#include "llvm/ADT/Twine.h"
Torok Edwine14d4cd2009-08-30 08:24:09 +000019#include <string>
Torok Edwine14d4cd2009-08-30 08:24:09 +000020using namespace llvm;
Chris Lattner1ce83622009-09-24 20:15:51 +000021
George Rimara9ff0722016-09-01 08:00:28 +000022Regex::Regex() : error(REG_BADPAT), preg(nullptr) {}
23
Benjamin Kramer92d89982010-07-14 22:38:02 +000024Regex::Regex(StringRef regex, unsigned Flags) {
Torok Edwine14d4cd2009-08-30 08:24:09 +000025 unsigned flags = 0;
Chris Lattnerf08d2db2009-09-24 21:47:32 +000026 preg = new llvm_regex();
Torok Edwine14d4cd2009-08-30 08:24:09 +000027 preg->re_endp = regex.end();
28 if (Flags & IgnoreCase)
29 flags |= REG_ICASE;
Torok Edwine14d4cd2009-08-30 08:24:09 +000030 if (Flags & Newline)
31 flags |= REG_NEWLINE;
Eli Bendersky10f22d72012-11-28 19:00:02 +000032 if (!(Flags & BasicRegex))
33 flags |= REG_EXTENDED;
34 error = llvm_regcomp(preg, regex.data(), flags|REG_PEND);
Torok Edwine14d4cd2009-08-30 08:24:09 +000035}
36
Chris Lattner1ce83622009-09-24 20:15:51 +000037Regex::~Regex() {
David Blaikie7a238042014-01-02 19:04:59 +000038 if (preg) {
39 llvm_regfree(preg);
40 delete preg;
41 }
Torok Edwine14d4cd2009-08-30 08:24:09 +000042}
43
Chris Lattner37d80152009-09-26 21:27:04 +000044bool Regex::isValid(std::string &Error) {
45 if (!error)
46 return true;
47
Craig Topperc10719f2014-04-07 04:17:22 +000048 size_t len = llvm_regerror(error, preg, nullptr, 0);
Chris Lattner37d80152009-09-26 21:27:04 +000049
Alexey Samsonov96dd18c2013-08-08 17:32:45 +000050 Error.resize(len - 1);
Chris Lattner37d80152009-09-26 21:27:04 +000051 llvm_regerror(error, preg, &Error[0], len);
52 return false;
53}
54
55/// getNumMatches - In a valid regex, return the number of parenthesized
56/// matches it contains.
57unsigned Regex::getNumMatches() const {
58 return preg->re_nsub;
59}
60
Benjamin Kramer92d89982010-07-14 22:38:02 +000061bool Regex::match(StringRef String, SmallVectorImpl<StringRef> *Matches){
Torok Edwine14d4cd2009-08-30 08:24:09 +000062 unsigned nmatch = Matches ? preg->re_nsub+1 : 0;
63
Torok Edwine14d4cd2009-08-30 08:24:09 +000064 // pmatch needs to have at least one element.
Chris Lattnerf08d2db2009-09-24 21:47:32 +000065 SmallVector<llvm_regmatch_t, 8> pm;
Torok Edwine14d4cd2009-08-30 08:24:09 +000066 pm.resize(nmatch > 0 ? nmatch : 1);
67 pm[0].rm_so = 0;
68 pm[0].rm_eo = String.size();
69
70 int rc = llvm_regexec(preg, String.data(), nmatch, pm.data(), REG_STARTEND);
71
72 if (rc == REG_NOMATCH)
73 return false;
74 if (rc != 0) {
75 // regexec can fail due to invalid pattern or running out of memory.
76 error = rc;
77 return false;
78 }
79
80 // There was a match.
81
82 if (Matches) { // match position requested
Chris Lattner37d80152009-09-26 21:27:04 +000083 Matches->clear();
84
Chris Lattner1ce83622009-09-24 20:15:51 +000085 for (unsigned i = 0; i != nmatch; ++i) {
Torok Edwine14d4cd2009-08-30 08:24:09 +000086 if (pm[i].rm_so == -1) {
87 // this group didn't match
88 Matches->push_back(StringRef());
89 continue;
90 }
Chris Lattner0687ec72011-04-09 06:29:24 +000091 assert(pm[i].rm_eo >= pm[i].rm_so);
Torok Edwine14d4cd2009-08-30 08:24:09 +000092 Matches->push_back(StringRef(String.data()+pm[i].rm_so,
93 pm[i].rm_eo-pm[i].rm_so));
94 }
95 }
96
97 return true;
98}
Daniel Dunbareb857112010-02-17 20:08:42 +000099
100std::string Regex::sub(StringRef Repl, StringRef String,
101 std::string *Error) {
102 SmallVector<StringRef, 8> Matches;
103
104 // Reset error, if given.
105 if (Error && !Error->empty()) *Error = "";
106
107 // Return the input if there was no match.
108 if (!match(String, &Matches))
109 return String;
110
111 // Otherwise splice in the replacement string, starting with the prefix before
112 // the match.
113 std::string Res(String.begin(), Matches[0].begin());
114
115 // Then the replacement string, honoring possible substitutions.
116 while (!Repl.empty()) {
117 // Skip to the next escape.
118 std::pair<StringRef, StringRef> Split = Repl.split('\\');
119
120 // Add the skipped substring.
121 Res += Split.first;
122
123 // Check for terminimation and trailing backslash.
124 if (Split.second.empty()) {
125 if (Repl.size() != Split.first.size() &&
126 Error && Error->empty())
127 *Error = "replacement string contained trailing backslash";
128 break;
129 }
130
131 // Otherwise update the replacement string and interpret escapes.
132 Repl = Split.second;
133
134 // FIXME: We should have a StringExtras function for mapping C99 escapes.
135 switch (Repl[0]) {
136 // Treat all unrecognized characters as self-quoting.
137 default:
138 Res += Repl[0];
139 Repl = Repl.substr(1);
140 break;
141
142 // Single character escapes.
143 case 't':
144 Res += '\t';
145 Repl = Repl.substr(1);
146 break;
147 case 'n':
148 Res += '\n';
149 Repl = Repl.substr(1);
150 break;
151
152 // Decimal escapes are backreferences.
153 case '0': case '1': case '2': case '3': case '4':
154 case '5': case '6': case '7': case '8': case '9': {
155 // Extract the backreference number.
156 StringRef Ref = Repl.slice(0, Repl.find_first_not_of("0123456789"));
157 Repl = Repl.substr(Ref.size());
158
159 unsigned RefValue;
160 if (!Ref.getAsInteger(10, RefValue) &&
161 RefValue < Matches.size())
162 Res += Matches[RefValue];
163 else if (Error && Error->empty())
Yaron Keren075759a2015-03-30 15:42:36 +0000164 *Error = ("invalid backreference string '" + Twine(Ref) + "'").str();
Daniel Dunbareb857112010-02-17 20:08:42 +0000165 break;
166 }
167 }
168 }
169
170 // And finally the suffix.
171 Res += StringRef(Matches[0].end(), String.end() - Matches[0].end());
172
173 return Res;
174}
Peter Collingbournefe8cd752013-08-05 17:47:59 +0000175
Alp Tokerd0d1a742013-12-12 02:51:58 +0000176// These are the special characters matched in functions like "p_ere_exp".
177static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
178
Peter Collingbournefe8cd752013-08-05 17:47:59 +0000179bool Regex::isLiteralERE(StringRef Str) {
180 // Check for regex metacharacters. This list was derived from our regex
181 // implementation in regcomp.c and double checked against the POSIX extended
182 // regular expression specification.
Alp Tokerd0d1a742013-12-12 02:51:58 +0000183 return Str.find_first_of(RegexMetachars) == StringRef::npos;
Peter Collingbournefe8cd752013-08-05 17:47:59 +0000184}
Hans Wennborg6f4f77b2013-12-12 00:06:41 +0000185
186std::string Regex::escape(StringRef String) {
187 std::string RegexStr;
Hans Wennborg6f4f77b2013-12-12 00:06:41 +0000188 for (unsigned i = 0, e = String.size(); i != e; ++i) {
Alp Tokerd0d1a742013-12-12 02:51:58 +0000189 if (strchr(RegexMetachars, String[i]))
Hans Wennborg6f4f77b2013-12-12 00:06:41 +0000190 RegexStr += '\\';
Alp Tokerd0d1a742013-12-12 02:51:58 +0000191 RegexStr += String[i];
Hans Wennborg6f4f77b2013-12-12 00:06:41 +0000192 }
193
194 return RegexStr;
195}