LLVM 24.0.0git
Regex.cpp
Go to the documentation of this file.
1//===-- Regex.cpp - Regular Expression matcher implementation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a POSIX regular expression matcher.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Support/Regex.h"
14#include "regex_impl.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/ADT/Twine.h"
19
20#include <cassert>
21#include <string>
22
23using namespace llvm;
24
25Regex::Regex() : preg(nullptr), error(REG_BADPAT) {}
26
28 unsigned flags = 0;
29 preg = new llvm_regex();
30 preg->re_endp = regex.end();
31 if (Flags & IgnoreCase)
32 flags |= REG_ICASE;
33 if (Flags & Newline)
34 flags |= REG_NEWLINE;
35 if (!(Flags & BasicRegex))
36 flags |= REG_EXTENDED;
37 error = llvm_regcomp(preg, regex.data(), flags|REG_PEND);
38}
39
40Regex::Regex(StringRef regex, unsigned Flags)
41 : Regex(regex, static_cast<RegexFlags>(Flags)) {}
42
44 preg = regex.preg;
45 error = regex.error;
46 regex.preg = nullptr;
47 regex.error = REG_BADPAT;
48}
49
51 if (preg) {
52 llvm_regfree(preg);
53 delete preg;
54 }
55}
56
57namespace {
58
59/// Utility to convert a regex error code into a human-readable string.
60void RegexErrorToString(int error, struct llvm_regex *preg,
61 std::string &Error) {
62 size_t len = llvm_regerror(error, preg, nullptr, 0);
63
64 Error.resize(len - 1);
65 llvm_regerror(error, preg, &Error[0], len);
66}
67
68} // namespace
69
70bool Regex::isValid(std::string &Error) const {
71 if (!error)
72 return true;
73
74 RegexErrorToString(error, preg, Error);
75 return false;
76}
77
78/// getNumMatches - In a valid regex, return the number of parenthesized
79/// matches it contains.
80unsigned Regex::getNumMatches() const {
81 return preg->re_nsub;
82}
83
85 std::string *Error) const {
86 // Reset error, if given.
87 if (Error && !Error->empty())
88 *Error = "";
89
90 // Check if the regex itself didn't successfully compile.
91 if (Error ? !isValid(*Error) : !isValid())
92 return false;
93
94 unsigned nmatch = Matches ? preg->re_nsub+1 : 0;
95
96 // Update null string to empty string.
97 if (String.data() == nullptr)
98 String = "";
99
100 // pmatch needs to have at least one element.
102 pm.resize(nmatch > 0 ? nmatch : 1);
103 pm[0].rm_so = 0;
104 pm[0].rm_eo = String.size();
105
106 int rc = llvm_regexec(preg, String.data(), nmatch, pm.data(), REG_STARTEND);
107
108 // Failure to match is not an error, it's just a normal return value.
109 // Any other error code is considered abnormal, and is logged in the Error.
110 if (rc == REG_NOMATCH)
111 return false;
112 if (rc != 0) {
113 if (Error)
114 RegexErrorToString(error, preg, *Error);
115 return false;
116 }
117
118 // There was a match.
119
120 if (Matches) { // match position requested
121 Matches->clear();
122
123 for (unsigned i = 0; i != nmatch; ++i) {
124 if (pm[i].rm_so == -1) {
125 // this group didn't match
126 Matches->push_back(StringRef());
127 continue;
128 }
129 assert(pm[i].rm_eo >= pm[i].rm_so);
130 Matches->push_back(StringRef(String.data()+pm[i].rm_so,
131 pm[i].rm_eo-pm[i].rm_so));
132 }
133 }
134
135 return true;
136}
137
139 std::string *Error) const {
141
142 // Return the input if there was no match.
143 if (!match(String, &Matches, Error))
144 return std::string(String);
145
146 // Otherwise splice in the replacement string, starting with the prefix before
147 // the match.
148 std::string Res(String.begin(), Matches[0].begin());
149
150 // Then the replacement string, honoring possible substitutions.
151 while (!Repl.empty()) {
152 // Skip to the next escape.
153 std::pair<StringRef, StringRef> Split = Repl.split('\\');
154
155 // Add the skipped substring.
156 Res += Split.first;
157
158 // Check for termination and trailing backslash.
159 if (Split.second.empty()) {
160 if (Repl.size() != Split.first.size() &&
161 Error && Error->empty())
162 *Error = "replacement string contained trailing backslash";
163 break;
164 }
165
166 // Otherwise update the replacement string and interpret escapes.
167 Repl = Split.second;
168
169 // FIXME: We should have a StringExtras function for mapping C99 escapes.
170 switch (Repl[0]) {
171
172 // Backreference with the "\g<ref>" syntax
173 case 'g':
174 if (Repl.size() >= 4 && Repl[1] == '<') {
175 size_t End = Repl.find('>');
176 StringRef Ref = Repl.slice(2, End);
177 unsigned RefValue;
178 if (End != StringRef::npos && !Ref.getAsInteger(10, RefValue)) {
179 Repl = Repl.substr(End + 1);
180 if (RefValue < Matches.size())
181 Res += Matches[RefValue];
182 else if (Error && Error->empty())
183 *Error =
184 ("invalid backreference string 'g<" + Twine(Ref) + ">'").str();
185 break;
186 }
187 }
188 [[fallthrough]];
189
190 // Treat all unrecognized characters as self-quoting.
191 default:
192 Res += Repl[0];
193 Repl = Repl.substr(1);
194 break;
195
196 // Single character escapes.
197 case 't':
198 Res += '\t';
199 Repl = Repl.substr(1);
200 break;
201 case 'n':
202 Res += '\n';
203 Repl = Repl.substr(1);
204 break;
205
206 // Hex character escapes.
207 case 'x':
208 if (Repl.size() >= 3 && isHexDigit(Repl[1]) && isHexDigit(Repl[2])) {
209 Res += char(hexDigitValue(Repl[1]) * 16 + hexDigitValue(Repl[2]));
210 Repl = Repl.substr(3);
211 } else {
212 Res += Repl[0];
213 Repl = Repl.substr(1);
214 }
215 break;
216
217 // Decimal escapes are backreferences.
218 case '0': case '1': case '2': case '3': case '4':
219 case '5': case '6': case '7': case '8': case '9': {
220 // Extract the backreference number.
221 StringRef Ref = Repl.slice(0, Repl.find_first_not_of("0123456789"));
222 Repl = Repl.substr(Ref.size());
223
224 unsigned RefValue;
225 if (!Ref.getAsInteger(10, RefValue) &&
226 RefValue < Matches.size())
227 Res += Matches[RefValue];
228 else if (Error && Error->empty())
229 *Error = ("invalid backreference string '" + Twine(Ref) + "'").str();
230 break;
231 }
232 }
233 }
234
235 // And finally the suffix.
236 Res += StringRef(Matches[0].end(), String.end() - Matches[0].end());
237
238 return Res;
239}
240
241// These are the special characters matched in functions like "p_ere_exp".
242static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
243
245 // Check for regex metacharacters. This list was derived from our regex
246 // implementation in regcomp.c and double checked against the POSIX extended
247 // regular expression specification.
248 return Str.find_first_of(RegexMetachars) == StringRef::npos;
249}
250
252 std::string RegexStr;
253 for (char C : String) {
254 if (strchr(RegexMetachars, C))
255 RegexStr += '\\';
256 RegexStr += C;
257 }
258
259 return RegexStr;
260}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define rc(i)
static const char RegexMetachars[]
Definition Regex.cpp:242
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define error(X)
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
@ Newline
Compile for newline-sensitive matching.
Definition Regex.h:40
@ IgnoreCase
Compile for matching that ignores upper/lower case distinctions.
Definition Regex.h:34
@ BasicRegex
By default, the POSIX extended regular expression (ERE) syntax is assumed.
Definition Regex.h:44
static LLVM_ABI std::string escape(StringRef String)
Turn String into a regex by escaping its special characters.
Definition Regex.cpp:251
LLVM_ABI ~Regex()
Definition Regex.cpp:50
bool isValid() const
Definition Regex.h:68
LLVM_ABI std::string sub(StringRef Repl, StringRef String, std::string *Error=nullptr) const
sub - Return the result of replacing the first match of the regex in String with the Repl string.
Definition Regex.cpp:138
static LLVM_ABI bool isLiteralERE(StringRef Str)
If this function returns true, ^Str$ is an extended regular expression that matches Str and only Str.
Definition Regex.cpp:244
LLVM_ABI Regex()
Definition Regex.cpp:25
LLVM_ABI unsigned getNumMatches() const
getNumMatches - In a valid regex, return the number of parenthesized matches it contains.
Definition Regex.cpp:80
LLVM_ABI bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr, std::string *Error=nullptr) const
matches - Match the regex against a given String.
Definition Regex.cpp:84
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
static constexpr size_t npos
Definition StringRef.h:58
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
iterator end() const
Definition StringRef.h:116
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
LLVM_ABI size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This is an optimization pass for GlobalISel generic memory operations.
unsigned hexDigitValue(char C)
Interpret the given character C as a hexadecimal digit and return its value.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
int llvm_regcomp(llvm_regex_t *preg, const char *pattern, int cflags)
Definition regcomp.c:288
size_t llvm_regerror(int errcode, const llvm_regex_t *preg, char *errbuf, size_t errbuf_size)
Definition regerror.c:84
#define REG_ICASE
Definition regex_impl.h:58
#define REG_NOMATCH
Definition regex_impl.h:66
#define REG_STARTEND
Definition regex_impl.h:88
void llvm_regfree(llvm_regex_t *)
Definition regfree.c:50
#define REG_EXTENDED
Definition regex_impl.h:57
int llvm_regexec(const llvm_regex_t *, const char *, size_t, llvm_regmatch_t[], int)
Definition regexec.c:141
#define REG_PEND
Definition regex_impl.h:62
#define REG_NEWLINE
Definition regex_impl.h:60
#define REG_BADPAT
Definition regex_impl.h:67