regexp.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. // Copyright 2006 The RE2 Authors. All Rights Reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Regular expression representation.
  5. // Tested by parse_test.cc
  6. #include "re2/regexp.h"
  7. #include <stddef.h>
  8. #include <stdint.h>
  9. #include <string.h>
  10. #include <algorithm>
  11. #include <map>
  12. #include <mutex>
  13. #include <string>
  14. #include <vector>
  15. #include "util/util.h"
  16. #include "util/logging.h"
  17. #include "util/mutex.h"
  18. #include "util/utf.h"
  19. #include "re2/pod_array.h"
  20. #include "re2/stringpiece.h"
  21. #include "re2/walker-inl.h"
  22. namespace re2 {
  23. // Constructor. Allocates vectors as appropriate for operator.
  24. Regexp::Regexp(RegexpOp op, ParseFlags parse_flags)
  25. : op_(static_cast<uint8_t>(op)),
  26. simple_(false),
  27. parse_flags_(static_cast<uint16_t>(parse_flags)),
  28. ref_(1),
  29. nsub_(0),
  30. down_(NULL) {
  31. subone_ = NULL;
  32. memset(the_union_, 0, sizeof the_union_);
  33. }
  34. // Destructor. Assumes already cleaned up children.
  35. // Private: use Decref() instead of delete to destroy Regexps.
  36. // Can't call Decref on the sub-Regexps here because
  37. // that could cause arbitrarily deep recursion, so
  38. // required Decref() to have handled them for us.
  39. Regexp::~Regexp() {
  40. if (nsub_ > 0)
  41. LOG(DFATAL) << "Regexp not destroyed.";
  42. switch (op_) {
  43. default:
  44. break;
  45. case kRegexpCapture:
  46. delete name_;
  47. break;
  48. case kRegexpLiteralString:
  49. delete[] runes_;
  50. break;
  51. case kRegexpCharClass:
  52. if (cc_)
  53. cc_->Delete();
  54. delete ccb_;
  55. break;
  56. }
  57. }
  58. // If it's possible to destroy this regexp without recurring,
  59. // do so and return true. Else return false.
  60. bool Regexp::QuickDestroy() {
  61. if (nsub_ == 0) {
  62. delete this;
  63. return true;
  64. }
  65. return false;
  66. }
  67. // Lazily allocated.
  68. static Mutex* ref_mutex;
  69. static std::map<Regexp*, int>* ref_map;
  70. int Regexp::Ref() {
  71. if (ref_ < kMaxRef)
  72. return ref_;
  73. MutexLock l(ref_mutex);
  74. return (*ref_map)[this];
  75. }
  76. // Increments reference count, returns object as convenience.
  77. Regexp* Regexp::Incref() {
  78. if (ref_ >= kMaxRef-1) {
  79. static std::once_flag ref_once;
  80. std::call_once(ref_once, []() {
  81. ref_mutex = new Mutex;
  82. ref_map = new std::map<Regexp*, int>;
  83. });
  84. // Store ref count in overflow map.
  85. MutexLock l(ref_mutex);
  86. if (ref_ == kMaxRef) {
  87. // already overflowed
  88. (*ref_map)[this]++;
  89. } else {
  90. // overflowing now
  91. (*ref_map)[this] = kMaxRef;
  92. ref_ = kMaxRef;
  93. }
  94. return this;
  95. }
  96. ref_++;
  97. return this;
  98. }
  99. // Decrements reference count and deletes this object if count reaches 0.
  100. void Regexp::Decref() {
  101. if (ref_ == kMaxRef) {
  102. // Ref count is stored in overflow map.
  103. MutexLock l(ref_mutex);
  104. int r = (*ref_map)[this] - 1;
  105. if (r < kMaxRef) {
  106. ref_ = static_cast<uint16_t>(r);
  107. ref_map->erase(this);
  108. } else {
  109. (*ref_map)[this] = r;
  110. }
  111. return;
  112. }
  113. ref_--;
  114. if (ref_ == 0)
  115. Destroy();
  116. }
  117. // Deletes this object; ref count has count reached 0.
  118. void Regexp::Destroy() {
  119. if (QuickDestroy())
  120. return;
  121. // Handle recursive Destroy with explicit stack
  122. // to avoid arbitrarily deep recursion on process stack [sigh].
  123. down_ = NULL;
  124. Regexp* stack = this;
  125. while (stack != NULL) {
  126. Regexp* re = stack;
  127. stack = re->down_;
  128. if (re->ref_ != 0)
  129. LOG(DFATAL) << "Bad reference count " << re->ref_;
  130. if (re->nsub_ > 0) {
  131. Regexp** subs = re->sub();
  132. for (int i = 0; i < re->nsub_; i++) {
  133. Regexp* sub = subs[i];
  134. if (sub == NULL)
  135. continue;
  136. if (sub->ref_ == kMaxRef)
  137. sub->Decref();
  138. else
  139. --sub->ref_;
  140. if (sub->ref_ == 0 && !sub->QuickDestroy()) {
  141. sub->down_ = stack;
  142. stack = sub;
  143. }
  144. }
  145. if (re->nsub_ > 1)
  146. delete[] subs;
  147. re->nsub_ = 0;
  148. }
  149. delete re;
  150. }
  151. }
  152. void Regexp::AddRuneToString(Rune r) {
  153. DCHECK(op_ == kRegexpLiteralString);
  154. if (nrunes_ == 0) {
  155. // start with 8
  156. runes_ = new Rune[8];
  157. } else if (nrunes_ >= 8 && (nrunes_ & (nrunes_ - 1)) == 0) {
  158. // double on powers of two
  159. Rune *old = runes_;
  160. runes_ = new Rune[nrunes_ * 2];
  161. for (int i = 0; i < nrunes_; i++)
  162. runes_[i] = old[i];
  163. delete[] old;
  164. }
  165. runes_[nrunes_++] = r;
  166. }
  167. Regexp* Regexp::HaveMatch(int match_id, ParseFlags flags) {
  168. Regexp* re = new Regexp(kRegexpHaveMatch, flags);
  169. re->match_id_ = match_id;
  170. return re;
  171. }
  172. Regexp* Regexp::StarPlusOrQuest(RegexpOp op, Regexp* sub, ParseFlags flags) {
  173. // Squash **, ++ and ??.
  174. if (op == sub->op() && flags == sub->parse_flags())
  175. return sub;
  176. // Squash *+, *?, +*, +?, ?* and ?+. They all squash to *, so because
  177. // op is Star/Plus/Quest, we just have to check that sub->op() is too.
  178. if ((sub->op() == kRegexpStar ||
  179. sub->op() == kRegexpPlus ||
  180. sub->op() == kRegexpQuest) &&
  181. flags == sub->parse_flags()) {
  182. // If sub is Star, no need to rewrite it.
  183. if (sub->op() == kRegexpStar)
  184. return sub;
  185. // Rewrite sub to Star.
  186. Regexp* re = new Regexp(kRegexpStar, flags);
  187. re->AllocSub(1);
  188. re->sub()[0] = sub->sub()[0]->Incref();
  189. sub->Decref(); // We didn't consume the reference after all.
  190. return re;
  191. }
  192. Regexp* re = new Regexp(op, flags);
  193. re->AllocSub(1);
  194. re->sub()[0] = sub;
  195. return re;
  196. }
  197. Regexp* Regexp::Plus(Regexp* sub, ParseFlags flags) {
  198. return StarPlusOrQuest(kRegexpPlus, sub, flags);
  199. }
  200. Regexp* Regexp::Star(Regexp* sub, ParseFlags flags) {
  201. return StarPlusOrQuest(kRegexpStar, sub, flags);
  202. }
  203. Regexp* Regexp::Quest(Regexp* sub, ParseFlags flags) {
  204. return StarPlusOrQuest(kRegexpQuest, sub, flags);
  205. }
  206. Regexp* Regexp::ConcatOrAlternate(RegexpOp op, Regexp** sub, int nsub,
  207. ParseFlags flags, bool can_factor) {
  208. if (nsub == 1)
  209. return sub[0];
  210. if (nsub == 0) {
  211. if (op == kRegexpAlternate)
  212. return new Regexp(kRegexpNoMatch, flags);
  213. else
  214. return new Regexp(kRegexpEmptyMatch, flags);
  215. }
  216. PODArray<Regexp*> subcopy;
  217. if (op == kRegexpAlternate && can_factor) {
  218. // Going to edit sub; make a copy so we don't step on caller.
  219. subcopy = PODArray<Regexp*>(nsub);
  220. memmove(subcopy.data(), sub, nsub * sizeof sub[0]);
  221. sub = subcopy.data();
  222. nsub = FactorAlternation(sub, nsub, flags);
  223. if (nsub == 1) {
  224. Regexp* re = sub[0];
  225. return re;
  226. }
  227. }
  228. if (nsub > kMaxNsub) {
  229. // Too many subexpressions to fit in a single Regexp.
  230. // Make a two-level tree. Two levels gets us to 65535^2.
  231. int nbigsub = (nsub+kMaxNsub-1)/kMaxNsub;
  232. Regexp* re = new Regexp(op, flags);
  233. re->AllocSub(nbigsub);
  234. Regexp** subs = re->sub();
  235. for (int i = 0; i < nbigsub - 1; i++)
  236. subs[i] = ConcatOrAlternate(op, sub+i*kMaxNsub, kMaxNsub, flags, false);
  237. subs[nbigsub - 1] = ConcatOrAlternate(op, sub+(nbigsub-1)*kMaxNsub,
  238. nsub - (nbigsub-1)*kMaxNsub, flags,
  239. false);
  240. return re;
  241. }
  242. Regexp* re = new Regexp(op, flags);
  243. re->AllocSub(nsub);
  244. Regexp** subs = re->sub();
  245. for (int i = 0; i < nsub; i++)
  246. subs[i] = sub[i];
  247. return re;
  248. }
  249. Regexp* Regexp::Concat(Regexp** sub, int nsub, ParseFlags flags) {
  250. return ConcatOrAlternate(kRegexpConcat, sub, nsub, flags, false);
  251. }
  252. Regexp* Regexp::Alternate(Regexp** sub, int nsub, ParseFlags flags) {
  253. return ConcatOrAlternate(kRegexpAlternate, sub, nsub, flags, true);
  254. }
  255. Regexp* Regexp::AlternateNoFactor(Regexp** sub, int nsub, ParseFlags flags) {
  256. return ConcatOrAlternate(kRegexpAlternate, sub, nsub, flags, false);
  257. }
  258. Regexp* Regexp::Capture(Regexp* sub, ParseFlags flags, int cap) {
  259. Regexp* re = new Regexp(kRegexpCapture, flags);
  260. re->AllocSub(1);
  261. re->sub()[0] = sub;
  262. re->cap_ = cap;
  263. return re;
  264. }
  265. Regexp* Regexp::Repeat(Regexp* sub, ParseFlags flags, int min, int max) {
  266. Regexp* re = new Regexp(kRegexpRepeat, flags);
  267. re->AllocSub(1);
  268. re->sub()[0] = sub;
  269. re->min_ = min;
  270. re->max_ = max;
  271. return re;
  272. }
  273. Regexp* Regexp::NewLiteral(Rune rune, ParseFlags flags) {
  274. Regexp* re = new Regexp(kRegexpLiteral, flags);
  275. re->rune_ = rune;
  276. return re;
  277. }
  278. Regexp* Regexp::LiteralString(Rune* runes, int nrunes, ParseFlags flags) {
  279. if (nrunes <= 0)
  280. return new Regexp(kRegexpEmptyMatch, flags);
  281. if (nrunes == 1)
  282. return NewLiteral(runes[0], flags);
  283. Regexp* re = new Regexp(kRegexpLiteralString, flags);
  284. for (int i = 0; i < nrunes; i++)
  285. re->AddRuneToString(runes[i]);
  286. return re;
  287. }
  288. Regexp* Regexp::NewCharClass(CharClass* cc, ParseFlags flags) {
  289. Regexp* re = new Regexp(kRegexpCharClass, flags);
  290. re->cc_ = cc;
  291. return re;
  292. }
  293. void Regexp::Swap(Regexp* that) {
  294. // Regexp is not trivially copyable, so we cannot freely copy it with
  295. // memmove(3), but swapping objects like so is safe for our purposes.
  296. char tmp[sizeof *this];
  297. void* vthis = reinterpret_cast<void*>(this);
  298. void* vthat = reinterpret_cast<void*>(that);
  299. memmove(tmp, vthis, sizeof *this);
  300. memmove(vthis, vthat, sizeof *this);
  301. memmove(vthat, tmp, sizeof *this);
  302. }
  303. // Tests equality of all top-level structure but not subregexps.
  304. static bool TopEqual(Regexp* a, Regexp* b) {
  305. if (a->op() != b->op())
  306. return false;
  307. switch (a->op()) {
  308. case kRegexpNoMatch:
  309. case kRegexpEmptyMatch:
  310. case kRegexpAnyChar:
  311. case kRegexpAnyByte:
  312. case kRegexpBeginLine:
  313. case kRegexpEndLine:
  314. case kRegexpWordBoundary:
  315. case kRegexpNoWordBoundary:
  316. case kRegexpBeginText:
  317. return true;
  318. case kRegexpEndText:
  319. // The parse flags remember whether it's \z or (?-m:$),
  320. // which matters when testing against PCRE.
  321. return ((a->parse_flags() ^ b->parse_flags()) & Regexp::WasDollar) == 0;
  322. case kRegexpLiteral:
  323. return a->rune() == b->rune() &&
  324. ((a->parse_flags() ^ b->parse_flags()) & Regexp::FoldCase) == 0;
  325. case kRegexpLiteralString:
  326. return a->nrunes() == b->nrunes() &&
  327. ((a->parse_flags() ^ b->parse_flags()) & Regexp::FoldCase) == 0 &&
  328. memcmp(a->runes(), b->runes(),
  329. a->nrunes() * sizeof a->runes()[0]) == 0;
  330. case kRegexpAlternate:
  331. case kRegexpConcat:
  332. return a->nsub() == b->nsub();
  333. case kRegexpStar:
  334. case kRegexpPlus:
  335. case kRegexpQuest:
  336. return ((a->parse_flags() ^ b->parse_flags()) & Regexp::NonGreedy) == 0;
  337. case kRegexpRepeat:
  338. return ((a->parse_flags() ^ b->parse_flags()) & Regexp::NonGreedy) == 0 &&
  339. a->min() == b->min() &&
  340. a->max() == b->max();
  341. case kRegexpCapture:
  342. return a->cap() == b->cap() && a->name() == b->name();
  343. case kRegexpHaveMatch:
  344. return a->match_id() == b->match_id();
  345. case kRegexpCharClass: {
  346. CharClass* acc = a->cc();
  347. CharClass* bcc = b->cc();
  348. return acc->size() == bcc->size() &&
  349. acc->end() - acc->begin() == bcc->end() - bcc->begin() &&
  350. memcmp(acc->begin(), bcc->begin(),
  351. (acc->end() - acc->begin()) * sizeof acc->begin()[0]) == 0;
  352. }
  353. }
  354. LOG(DFATAL) << "Unexpected op in Regexp::Equal: " << a->op();
  355. return 0;
  356. }
  357. bool Regexp::Equal(Regexp* a, Regexp* b) {
  358. if (a == NULL || b == NULL)
  359. return a == b;
  360. if (!TopEqual(a, b))
  361. return false;
  362. // Fast path:
  363. // return without allocating vector if there are no subregexps.
  364. switch (a->op()) {
  365. case kRegexpAlternate:
  366. case kRegexpConcat:
  367. case kRegexpStar:
  368. case kRegexpPlus:
  369. case kRegexpQuest:
  370. case kRegexpRepeat:
  371. case kRegexpCapture:
  372. break;
  373. default:
  374. return true;
  375. }
  376. // Committed to doing real work.
  377. // The stack (vector) has pairs of regexps waiting to
  378. // be compared. The regexps are only equal if
  379. // all the pairs end up being equal.
  380. std::vector<Regexp*> stk;
  381. for (;;) {
  382. // Invariant: TopEqual(a, b) == true.
  383. Regexp* a2;
  384. Regexp* b2;
  385. switch (a->op()) {
  386. default:
  387. break;
  388. case kRegexpAlternate:
  389. case kRegexpConcat:
  390. for (int i = 0; i < a->nsub(); i++) {
  391. a2 = a->sub()[i];
  392. b2 = b->sub()[i];
  393. if (!TopEqual(a2, b2))
  394. return false;
  395. stk.push_back(a2);
  396. stk.push_back(b2);
  397. }
  398. break;
  399. case kRegexpStar:
  400. case kRegexpPlus:
  401. case kRegexpQuest:
  402. case kRegexpRepeat:
  403. case kRegexpCapture:
  404. a2 = a->sub()[0];
  405. b2 = b->sub()[0];
  406. if (!TopEqual(a2, b2))
  407. return false;
  408. // Really:
  409. // stk.push_back(a2);
  410. // stk.push_back(b2);
  411. // break;
  412. // but faster to assign directly and loop.
  413. a = a2;
  414. b = b2;
  415. continue;
  416. }
  417. size_t n = stk.size();
  418. if (n == 0)
  419. break;
  420. DCHECK_GE(n, 2);
  421. a = stk[n-2];
  422. b = stk[n-1];
  423. stk.resize(n-2);
  424. }
  425. return true;
  426. }
  427. // Keep in sync with enum RegexpStatusCode in regexp.h
  428. static const char *kErrorStrings[] = {
  429. "no error",
  430. "unexpected error",
  431. "invalid escape sequence",
  432. "invalid character class",
  433. "invalid character class range",
  434. "missing ]",
  435. "missing )",
  436. "unexpected )",
  437. "trailing \\",
  438. "no argument for repetition operator",
  439. "invalid repetition size",
  440. "bad repetition operator",
  441. "invalid perl operator",
  442. "invalid UTF-8",
  443. "invalid named capture group",
  444. };
  445. std::string RegexpStatus::CodeText(enum RegexpStatusCode code) {
  446. if (code < 0 || code >= arraysize(kErrorStrings))
  447. code = kRegexpInternalError;
  448. return kErrorStrings[code];
  449. }
  450. std::string RegexpStatus::Text() const {
  451. if (error_arg_.empty())
  452. return CodeText(code_);
  453. std::string s;
  454. s.append(CodeText(code_));
  455. s.append(": ");
  456. s.append(error_arg_.data(), error_arg_.size());
  457. return s;
  458. }
  459. void RegexpStatus::Copy(const RegexpStatus& status) {
  460. code_ = status.code_;
  461. error_arg_ = status.error_arg_;
  462. }
  463. typedef int Ignored; // Walker<void> doesn't exist
  464. // Walker subclass to count capturing parens in regexp.
  465. class NumCapturesWalker : public Regexp::Walker<Ignored> {
  466. public:
  467. NumCapturesWalker() : ncapture_(0) {}
  468. int ncapture() { return ncapture_; }
  469. virtual Ignored PreVisit(Regexp* re, Ignored ignored, bool* stop) {
  470. if (re->op() == kRegexpCapture)
  471. ncapture_++;
  472. return ignored;
  473. }
  474. virtual Ignored ShortVisit(Regexp* re, Ignored ignored) {
  475. // Should never be called: we use Walk(), not WalkExponential().
  476. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  477. LOG(DFATAL) << "NumCapturesWalker::ShortVisit called";
  478. #endif
  479. return ignored;
  480. }
  481. private:
  482. int ncapture_;
  483. NumCapturesWalker(const NumCapturesWalker&) = delete;
  484. NumCapturesWalker& operator=(const NumCapturesWalker&) = delete;
  485. };
  486. int Regexp::NumCaptures() {
  487. NumCapturesWalker w;
  488. w.Walk(this, 0);
  489. return w.ncapture();
  490. }
  491. // Walker class to build map of named capture groups and their indices.
  492. class NamedCapturesWalker : public Regexp::Walker<Ignored> {
  493. public:
  494. NamedCapturesWalker() : map_(NULL) {}
  495. ~NamedCapturesWalker() { delete map_; }
  496. std::map<std::string, int>* TakeMap() {
  497. std::map<std::string, int>* m = map_;
  498. map_ = NULL;
  499. return m;
  500. }
  501. virtual Ignored PreVisit(Regexp* re, Ignored ignored, bool* stop) {
  502. if (re->op() == kRegexpCapture && re->name() != NULL) {
  503. // Allocate map once we find a name.
  504. if (map_ == NULL)
  505. map_ = new std::map<std::string, int>;
  506. // Record first occurrence of each name.
  507. // (The rule is that if you have the same name
  508. // multiple times, only the leftmost one counts.)
  509. if (map_->find(*re->name()) == map_->end())
  510. (*map_)[*re->name()] = re->cap();
  511. }
  512. return ignored;
  513. }
  514. virtual Ignored ShortVisit(Regexp* re, Ignored ignored) {
  515. // Should never be called: we use Walk(), not WalkExponential().
  516. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  517. LOG(DFATAL) << "NamedCapturesWalker::ShortVisit called";
  518. #endif
  519. return ignored;
  520. }
  521. private:
  522. std::map<std::string, int>* map_;
  523. NamedCapturesWalker(const NamedCapturesWalker&) = delete;
  524. NamedCapturesWalker& operator=(const NamedCapturesWalker&) = delete;
  525. };
  526. std::map<std::string, int>* Regexp::NamedCaptures() {
  527. NamedCapturesWalker w;
  528. w.Walk(this, 0);
  529. return w.TakeMap();
  530. }
  531. // Walker class to build map from capture group indices to their names.
  532. class CaptureNamesWalker : public Regexp::Walker<Ignored> {
  533. public:
  534. CaptureNamesWalker() : map_(NULL) {}
  535. ~CaptureNamesWalker() { delete map_; }
  536. std::map<int, std::string>* TakeMap() {
  537. std::map<int, std::string>* m = map_;
  538. map_ = NULL;
  539. return m;
  540. }
  541. virtual Ignored PreVisit(Regexp* re, Ignored ignored, bool* stop) {
  542. if (re->op() == kRegexpCapture && re->name() != NULL) {
  543. // Allocate map once we find a name.
  544. if (map_ == NULL)
  545. map_ = new std::map<int, std::string>;
  546. (*map_)[re->cap()] = *re->name();
  547. }
  548. return ignored;
  549. }
  550. virtual Ignored ShortVisit(Regexp* re, Ignored ignored) {
  551. // Should never be called: we use Walk(), not WalkExponential().
  552. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  553. LOG(DFATAL) << "CaptureNamesWalker::ShortVisit called";
  554. #endif
  555. return ignored;
  556. }
  557. private:
  558. std::map<int, std::string>* map_;
  559. CaptureNamesWalker(const CaptureNamesWalker&) = delete;
  560. CaptureNamesWalker& operator=(const CaptureNamesWalker&) = delete;
  561. };
  562. std::map<int, std::string>* Regexp::CaptureNames() {
  563. CaptureNamesWalker w;
  564. w.Walk(this, 0);
  565. return w.TakeMap();
  566. }
  567. void ConvertRunesToBytes(bool latin1, Rune* runes, int nrunes,
  568. std::string* bytes) {
  569. if (latin1) {
  570. bytes->resize(nrunes);
  571. for (int i = 0; i < nrunes; i++)
  572. (*bytes)[i] = static_cast<char>(runes[i]);
  573. } else {
  574. bytes->resize(nrunes * UTFmax); // worst case
  575. char* p = &(*bytes)[0];
  576. for (int i = 0; i < nrunes; i++)
  577. p += runetochar(p, &runes[i]);
  578. bytes->resize(p - &(*bytes)[0]);
  579. bytes->shrink_to_fit();
  580. }
  581. }
  582. // Determines whether regexp matches must be anchored
  583. // with a fixed string prefix. If so, returns the prefix and
  584. // the regexp that remains after the prefix. The prefix might
  585. // be ASCII case-insensitive.
  586. bool Regexp::RequiredPrefix(std::string* prefix, bool* foldcase,
  587. Regexp** suffix) {
  588. prefix->clear();
  589. *foldcase = false;
  590. *suffix = NULL;
  591. // No need for a walker: the regexp must be of the form
  592. // 1. some number of ^ anchors
  593. // 2. a literal char or string
  594. // 3. the rest
  595. if (op_ != kRegexpConcat)
  596. return false;
  597. int i = 0;
  598. while (i < nsub_ && sub()[i]->op_ == kRegexpBeginText)
  599. i++;
  600. if (i == 0 || i >= nsub_)
  601. return false;
  602. Regexp* re = sub()[i];
  603. if (re->op_ != kRegexpLiteral &&
  604. re->op_ != kRegexpLiteralString)
  605. return false;
  606. i++;
  607. if (i < nsub_) {
  608. for (int j = i; j < nsub_; j++)
  609. sub()[j]->Incref();
  610. *suffix = Concat(sub() + i, nsub_ - i, parse_flags());
  611. } else {
  612. *suffix = new Regexp(kRegexpEmptyMatch, parse_flags());
  613. }
  614. bool latin1 = (re->parse_flags() & Latin1) != 0;
  615. Rune* runes = re->op_ == kRegexpLiteral ? &re->rune_ : re->runes_;
  616. int nrunes = re->op_ == kRegexpLiteral ? 1 : re->nrunes_;
  617. ConvertRunesToBytes(latin1, runes, nrunes, prefix);
  618. *foldcase = (re->parse_flags() & FoldCase) != 0;
  619. return true;
  620. }
  621. // Determines whether regexp matches must be unanchored
  622. // with a fixed string prefix. If so, returns the prefix.
  623. // The prefix might be ASCII case-insensitive.
  624. bool Regexp::RequiredPrefixForAccel(std::string* prefix, bool* foldcase) {
  625. prefix->clear();
  626. *foldcase = false;
  627. // No need for a walker: the regexp must either begin with or be
  628. // a literal char or string. We "see through" capturing groups,
  629. // but make no effort to glue multiple prefix fragments together.
  630. Regexp* re = op_ == kRegexpConcat && nsub_ > 0 ? sub()[0] : this;
  631. while (re->op_ == kRegexpCapture) {
  632. re = re->sub()[0];
  633. if (re->op_ == kRegexpConcat && re->nsub_ > 0)
  634. re = re->sub()[0];
  635. }
  636. if (re->op_ != kRegexpLiteral &&
  637. re->op_ != kRegexpLiteralString)
  638. return false;
  639. bool latin1 = (re->parse_flags() & Latin1) != 0;
  640. Rune* runes = re->op_ == kRegexpLiteral ? &re->rune_ : re->runes_;
  641. int nrunes = re->op_ == kRegexpLiteral ? 1 : re->nrunes_;
  642. ConvertRunesToBytes(latin1, runes, nrunes, prefix);
  643. *foldcase = (re->parse_flags() & FoldCase) != 0;
  644. return true;
  645. }
  646. // Character class builder is a balanced binary tree (STL set)
  647. // containing non-overlapping, non-abutting RuneRanges.
  648. // The less-than operator used in the tree treats two
  649. // ranges as equal if they overlap at all, so that
  650. // lookups for a particular Rune are possible.
  651. CharClassBuilder::CharClassBuilder() {
  652. nrunes_ = 0;
  653. upper_ = 0;
  654. lower_ = 0;
  655. }
  656. // Add lo-hi to the class; return whether class got bigger.
  657. bool CharClassBuilder::AddRange(Rune lo, Rune hi) {
  658. if (hi < lo)
  659. return false;
  660. if (lo <= 'z' && hi >= 'A') {
  661. // Overlaps some alpha, maybe not all.
  662. // Update bitmaps telling which ASCII letters are in the set.
  663. Rune lo1 = std::max<Rune>(lo, 'A');
  664. Rune hi1 = std::min<Rune>(hi, 'Z');
  665. if (lo1 <= hi1)
  666. upper_ |= ((1 << (hi1 - lo1 + 1)) - 1) << (lo1 - 'A');
  667. lo1 = std::max<Rune>(lo, 'a');
  668. hi1 = std::min<Rune>(hi, 'z');
  669. if (lo1 <= hi1)
  670. lower_ |= ((1 << (hi1 - lo1 + 1)) - 1) << (lo1 - 'a');
  671. }
  672. { // Check whether lo, hi is already in the class.
  673. iterator it = ranges_.find(RuneRange(lo, lo));
  674. if (it != end() && it->lo <= lo && hi <= it->hi)
  675. return false;
  676. }
  677. // Look for a range abutting lo on the left.
  678. // If it exists, take it out and increase our range.
  679. if (lo > 0) {
  680. iterator it = ranges_.find(RuneRange(lo-1, lo-1));
  681. if (it != end()) {
  682. lo = it->lo;
  683. if (it->hi > hi)
  684. hi = it->hi;
  685. nrunes_ -= it->hi - it->lo + 1;
  686. ranges_.erase(it);
  687. }
  688. }
  689. // Look for a range abutting hi on the right.
  690. // If it exists, take it out and increase our range.
  691. if (hi < Runemax) {
  692. iterator it = ranges_.find(RuneRange(hi+1, hi+1));
  693. if (it != end()) {
  694. hi = it->hi;
  695. nrunes_ -= it->hi - it->lo + 1;
  696. ranges_.erase(it);
  697. }
  698. }
  699. // Look for ranges between lo and hi. Take them out.
  700. // This is only safe because the set has no overlapping ranges.
  701. // We've already removed any ranges abutting lo and hi, so
  702. // any that overlap [lo, hi] must be contained within it.
  703. for (;;) {
  704. iterator it = ranges_.find(RuneRange(lo, hi));
  705. if (it == end())
  706. break;
  707. nrunes_ -= it->hi - it->lo + 1;
  708. ranges_.erase(it);
  709. }
  710. // Finally, add [lo, hi].
  711. nrunes_ += hi - lo + 1;
  712. ranges_.insert(RuneRange(lo, hi));
  713. return true;
  714. }
  715. void CharClassBuilder::AddCharClass(CharClassBuilder *cc) {
  716. for (iterator it = cc->begin(); it != cc->end(); ++it)
  717. AddRange(it->lo, it->hi);
  718. }
  719. bool CharClassBuilder::Contains(Rune r) {
  720. return ranges_.find(RuneRange(r, r)) != end();
  721. }
  722. // Does the character class behave the same on A-Z as on a-z?
  723. bool CharClassBuilder::FoldsASCII() {
  724. return ((upper_ ^ lower_) & AlphaMask) == 0;
  725. }
  726. CharClassBuilder* CharClassBuilder::Copy() {
  727. CharClassBuilder* cc = new CharClassBuilder;
  728. for (iterator it = begin(); it != end(); ++it)
  729. cc->ranges_.insert(RuneRange(it->lo, it->hi));
  730. cc->upper_ = upper_;
  731. cc->lower_ = lower_;
  732. cc->nrunes_ = nrunes_;
  733. return cc;
  734. }
  735. void CharClassBuilder::RemoveAbove(Rune r) {
  736. if (r >= Runemax)
  737. return;
  738. if (r < 'z') {
  739. if (r < 'a')
  740. lower_ = 0;
  741. else
  742. lower_ &= AlphaMask >> ('z' - r);
  743. }
  744. if (r < 'Z') {
  745. if (r < 'A')
  746. upper_ = 0;
  747. else
  748. upper_ &= AlphaMask >> ('Z' - r);
  749. }
  750. for (;;) {
  751. iterator it = ranges_.find(RuneRange(r + 1, Runemax));
  752. if (it == end())
  753. break;
  754. RuneRange rr = *it;
  755. ranges_.erase(it);
  756. nrunes_ -= rr.hi - rr.lo + 1;
  757. if (rr.lo <= r) {
  758. rr.hi = r;
  759. ranges_.insert(rr);
  760. nrunes_ += rr.hi - rr.lo + 1;
  761. }
  762. }
  763. }
  764. void CharClassBuilder::Negate() {
  765. // Build up negation and then copy in.
  766. // Could edit ranges in place, but C++ won't let me.
  767. std::vector<RuneRange> v;
  768. v.reserve(ranges_.size() + 1);
  769. // In negation, first range begins at 0, unless
  770. // the current class begins at 0.
  771. iterator it = begin();
  772. if (it == end()) {
  773. v.push_back(RuneRange(0, Runemax));
  774. } else {
  775. int nextlo = 0;
  776. if (it->lo == 0) {
  777. nextlo = it->hi + 1;
  778. ++it;
  779. }
  780. for (; it != end(); ++it) {
  781. v.push_back(RuneRange(nextlo, it->lo - 1));
  782. nextlo = it->hi + 1;
  783. }
  784. if (nextlo <= Runemax)
  785. v.push_back(RuneRange(nextlo, Runemax));
  786. }
  787. ranges_.clear();
  788. for (size_t i = 0; i < v.size(); i++)
  789. ranges_.insert(v[i]);
  790. upper_ = AlphaMask & ~upper_;
  791. lower_ = AlphaMask & ~lower_;
  792. nrunes_ = Runemax+1 - nrunes_;
  793. }
  794. // Character class is a sorted list of ranges.
  795. // The ranges are allocated in the same block as the header,
  796. // necessitating a special allocator and Delete method.
  797. CharClass* CharClass::New(size_t maxranges) {
  798. CharClass* cc;
  799. uint8_t* data = new uint8_t[sizeof *cc + maxranges*sizeof cc->ranges_[0]];
  800. cc = reinterpret_cast<CharClass*>(data);
  801. cc->ranges_ = reinterpret_cast<RuneRange*>(data + sizeof *cc);
  802. cc->nranges_ = 0;
  803. cc->folds_ascii_ = false;
  804. cc->nrunes_ = 0;
  805. return cc;
  806. }
  807. void CharClass::Delete() {
  808. uint8_t* data = reinterpret_cast<uint8_t*>(this);
  809. delete[] data;
  810. }
  811. CharClass* CharClass::Negate() {
  812. CharClass* cc = CharClass::New(static_cast<size_t>(nranges_+1));
  813. cc->folds_ascii_ = folds_ascii_;
  814. cc->nrunes_ = Runemax + 1 - nrunes_;
  815. int n = 0;
  816. int nextlo = 0;
  817. for (CharClass::iterator it = begin(); it != end(); ++it) {
  818. if (it->lo == nextlo) {
  819. nextlo = it->hi + 1;
  820. } else {
  821. cc->ranges_[n++] = RuneRange(nextlo, it->lo - 1);
  822. nextlo = it->hi + 1;
  823. }
  824. }
  825. if (nextlo <= Runemax)
  826. cc->ranges_[n++] = RuneRange(nextlo, Runemax);
  827. cc->nranges_ = n;
  828. return cc;
  829. }
  830. bool CharClass::Contains(Rune r) const {
  831. RuneRange* rr = ranges_;
  832. int n = nranges_;
  833. while (n > 0) {
  834. int m = n/2;
  835. if (rr[m].hi < r) {
  836. rr += m+1;
  837. n -= m+1;
  838. } else if (r < rr[m].lo) {
  839. n = m;
  840. } else { // rr[m].lo <= r && r <= rr[m].hi
  841. return true;
  842. }
  843. }
  844. return false;
  845. }
  846. CharClass* CharClassBuilder::GetCharClass() {
  847. CharClass* cc = CharClass::New(ranges_.size());
  848. int n = 0;
  849. for (iterator it = begin(); it != end(); ++it)
  850. cc->ranges_[n++] = *it;
  851. cc->nranges_ = n;
  852. DCHECK_LE(n, static_cast<int>(ranges_.size()));
  853. cc->nrunes_ = nrunes_;
  854. cc->folds_ascii_ = FoldsASCII();
  855. return cc;
  856. }
  857. } // namespace re2