Coverage Report

Created: 2020-06-26 05:44

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