Regex.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. #include "llvm/Support/Regex.h"
  14. #include "llvm/Support/ErrorHandling.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "regex_impl.h"
  18. #include <string>
  19. using namespace llvm;
  20. Regex::Regex(const StringRef &regex, unsigned Flags) {
  21. unsigned flags = 0;
  22. preg = new llvm_regex();
  23. preg->re_endp = regex.end();
  24. if (Flags & IgnoreCase)
  25. flags |= REG_ICASE;
  26. if (Flags & NoSub) {
  27. flags |= REG_NOSUB;
  28. sub = false;
  29. } else {
  30. sub = true;
  31. }
  32. if (Flags & Newline)
  33. flags |= REG_NEWLINE;
  34. error = llvm_regcomp(preg, regex.data(), flags|REG_EXTENDED|REG_PEND);
  35. }
  36. bool Regex::isValid(std::string &Error) {
  37. if (!error)
  38. return true;
  39. size_t len = llvm_regerror(error, preg, NULL, 0);
  40. Error.resize(len);
  41. llvm_regerror(error, preg, &Error[0], len);
  42. return false;
  43. }
  44. Regex::~Regex() {
  45. llvm_regfree(preg);
  46. delete preg;
  47. }
  48. bool Regex::match(const StringRef &String, SmallVectorImpl<StringRef> *Matches){
  49. unsigned nmatch = Matches ? preg->re_nsub+1 : 0;
  50. if (Matches) {
  51. assert(sub && "Substring matching requested but pattern compiled without");
  52. Matches->clear();
  53. }
  54. // pmatch needs to have at least one element.
  55. SmallVector<llvm_regmatch_t, 8> pm;
  56. pm.resize(nmatch > 0 ? nmatch : 1);
  57. pm[0].rm_so = 0;
  58. pm[0].rm_eo = String.size();
  59. int rc = llvm_regexec(preg, String.data(), nmatch, pm.data(), REG_STARTEND);
  60. if (rc == REG_NOMATCH)
  61. return false;
  62. if (rc != 0) {
  63. // regexec can fail due to invalid pattern or running out of memory.
  64. error = rc;
  65. return false;
  66. }
  67. // There was a match.
  68. if (Matches) { // match position requested
  69. for (unsigned i = 0; i != nmatch; ++i) {
  70. if (pm[i].rm_so == -1) {
  71. // this group didn't match
  72. Matches->push_back(StringRef());
  73. continue;
  74. }
  75. assert(pm[i].rm_eo > pm[i].rm_so);
  76. Matches->push_back(StringRef(String.data()+pm[i].rm_so,
  77. pm[i].rm_eo-pm[i].rm_so));
  78. }
  79. }
  80. return true;
  81. }