parse.cc 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483
  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 parser.
  5. // The parser is a simple precedence-based parser with a
  6. // manual stack. The parsing work is done by the methods
  7. // of the ParseState class. The Regexp::Parse function is
  8. // essentially just a lexer that calls the ParseState method
  9. // for each token.
  10. // The parser recognizes POSIX extended regular expressions
  11. // excluding backreferences, collating elements, and collating
  12. // classes. It also allows the empty string as a regular expression
  13. // and recognizes the Perl escape sequences \d, \s, \w, \D, \S, and \W.
  14. // See regexp.h for rationale.
  15. #include <ctype.h>
  16. #include <stddef.h>
  17. #include <stdint.h>
  18. #include <string.h>
  19. #include <algorithm>
  20. #include <map>
  21. #include <string>
  22. #include <vector>
  23. #include "util/util.h"
  24. #include "util/logging.h"
  25. #include "util/strutil.h"
  26. #include "util/utf.h"
  27. #include "re2/pod_array.h"
  28. #include "re2/regexp.h"
  29. #include "re2/stringpiece.h"
  30. #include "re2/unicode_casefold.h"
  31. #include "re2/unicode_groups.h"
  32. #include "re2/walker-inl.h"
  33. #if defined(RE2_USE_ICU)
  34. #include "unicode/uniset.h"
  35. #include "unicode/unistr.h"
  36. #include "unicode/utypes.h"
  37. #endif
  38. namespace re2 {
  39. // Controls the maximum repeat count permitted by the parser.
  40. static int maximum_repeat_count = 1000;
  41. void Regexp::FUZZING_ONLY_set_maximum_repeat_count(int i) {
  42. maximum_repeat_count = i;
  43. }
  44. // Regular expression parse state.
  45. // The list of parsed regexps so far is maintained as a vector of
  46. // Regexp pointers called the stack. Left parenthesis and vertical
  47. // bar markers are also placed on the stack, as Regexps with
  48. // non-standard opcodes.
  49. // Scanning a left parenthesis causes the parser to push a left parenthesis
  50. // marker on the stack.
  51. // Scanning a vertical bar causes the parser to pop the stack until it finds a
  52. // vertical bar or left parenthesis marker (not popping the marker),
  53. // concatenate all the popped results, and push them back on
  54. // the stack (DoConcatenation).
  55. // Scanning a right parenthesis causes the parser to act as though it
  56. // has seen a vertical bar, which then leaves the top of the stack in the
  57. // form LeftParen regexp VerticalBar regexp VerticalBar ... regexp VerticalBar.
  58. // The parser pops all this off the stack and creates an alternation of the
  59. // regexps (DoAlternation).
  60. class Regexp::ParseState {
  61. public:
  62. ParseState(ParseFlags flags, const StringPiece& whole_regexp,
  63. RegexpStatus* status);
  64. ~ParseState();
  65. ParseFlags flags() { return flags_; }
  66. int rune_max() { return rune_max_; }
  67. // Parse methods. All public methods return a bool saying
  68. // whether parsing should continue. If a method returns
  69. // false, it has set fields in *status_, and the parser
  70. // should return NULL.
  71. // Pushes the given regular expression onto the stack.
  72. // Could check for too much memory used here.
  73. bool PushRegexp(Regexp* re);
  74. // Pushes the literal rune r onto the stack.
  75. bool PushLiteral(Rune r);
  76. // Pushes a regexp with the given op (and no args) onto the stack.
  77. bool PushSimpleOp(RegexpOp op);
  78. // Pushes a ^ onto the stack.
  79. bool PushCaret();
  80. // Pushes a \b (word == true) or \B (word == false) onto the stack.
  81. bool PushWordBoundary(bool word);
  82. // Pushes a $ onto the stack.
  83. bool PushDollar();
  84. // Pushes a . onto the stack
  85. bool PushDot();
  86. // Pushes a repeat operator regexp onto the stack.
  87. // A valid argument for the operator must already be on the stack.
  88. // s is the name of the operator, for use in error messages.
  89. bool PushRepeatOp(RegexpOp op, const StringPiece& s, bool nongreedy);
  90. // Pushes a repetition regexp onto the stack.
  91. // A valid argument for the operator must already be on the stack.
  92. bool PushRepetition(int min, int max, const StringPiece& s, bool nongreedy);
  93. // Checks whether a particular regexp op is a marker.
  94. bool IsMarker(RegexpOp op);
  95. // Processes a left parenthesis in the input.
  96. // Pushes a marker onto the stack.
  97. bool DoLeftParen(const StringPiece& name);
  98. bool DoLeftParenNoCapture();
  99. // Processes a vertical bar in the input.
  100. bool DoVerticalBar();
  101. // Processes a right parenthesis in the input.
  102. bool DoRightParen();
  103. // Processes the end of input, returning the final regexp.
  104. Regexp* DoFinish();
  105. // Finishes the regexp if necessary, preparing it for use
  106. // in a more complicated expression.
  107. // If it is a CharClassBuilder, converts into a CharClass.
  108. Regexp* FinishRegexp(Regexp*);
  109. // These routines don't manipulate the parse stack
  110. // directly, but they do need to look at flags_.
  111. // ParseCharClass also manipulates the internals of Regexp
  112. // while creating *out_re.
  113. // Parse a character class into *out_re.
  114. // Removes parsed text from s.
  115. bool ParseCharClass(StringPiece* s, Regexp** out_re,
  116. RegexpStatus* status);
  117. // Parse a character class character into *rp.
  118. // Removes parsed text from s.
  119. bool ParseCCCharacter(StringPiece* s, Rune *rp,
  120. const StringPiece& whole_class,
  121. RegexpStatus* status);
  122. // Parse a character class range into rr.
  123. // Removes parsed text from s.
  124. bool ParseCCRange(StringPiece* s, RuneRange* rr,
  125. const StringPiece& whole_class,
  126. RegexpStatus* status);
  127. // Parse a Perl flag set or non-capturing group from s.
  128. bool ParsePerlFlags(StringPiece* s);
  129. // Finishes the current concatenation,
  130. // collapsing it into a single regexp on the stack.
  131. void DoConcatenation();
  132. // Finishes the current alternation,
  133. // collapsing it to a single regexp on the stack.
  134. void DoAlternation();
  135. // Generalized DoAlternation/DoConcatenation.
  136. void DoCollapse(RegexpOp op);
  137. // Maybe concatenate Literals into LiteralString.
  138. bool MaybeConcatString(int r, ParseFlags flags);
  139. private:
  140. ParseFlags flags_;
  141. StringPiece whole_regexp_;
  142. RegexpStatus* status_;
  143. Regexp* stacktop_;
  144. int ncap_; // number of capturing parens seen
  145. int rune_max_; // maximum char value for this encoding
  146. ParseState(const ParseState&) = delete;
  147. ParseState& operator=(const ParseState&) = delete;
  148. };
  149. // Pseudo-operators - only on parse stack.
  150. const RegexpOp kLeftParen = static_cast<RegexpOp>(kMaxRegexpOp+1);
  151. const RegexpOp kVerticalBar = static_cast<RegexpOp>(kMaxRegexpOp+2);
  152. Regexp::ParseState::ParseState(ParseFlags flags,
  153. const StringPiece& whole_regexp,
  154. RegexpStatus* status)
  155. : flags_(flags), whole_regexp_(whole_regexp),
  156. status_(status), stacktop_(NULL), ncap_(0) {
  157. if (flags_ & Latin1)
  158. rune_max_ = 0xFF;
  159. else
  160. rune_max_ = Runemax;
  161. }
  162. // Cleans up by freeing all the regexps on the stack.
  163. Regexp::ParseState::~ParseState() {
  164. Regexp* next;
  165. for (Regexp* re = stacktop_; re != NULL; re = next) {
  166. next = re->down_;
  167. re->down_ = NULL;
  168. if (re->op() == kLeftParen)
  169. delete re->name_;
  170. re->Decref();
  171. }
  172. }
  173. // Finishes the regexp if necessary, preparing it for use in
  174. // a more complex expression.
  175. // If it is a CharClassBuilder, converts into a CharClass.
  176. Regexp* Regexp::ParseState::FinishRegexp(Regexp* re) {
  177. if (re == NULL)
  178. return NULL;
  179. re->down_ = NULL;
  180. if (re->op_ == kRegexpCharClass && re->ccb_ != NULL) {
  181. CharClassBuilder* ccb = re->ccb_;
  182. re->ccb_ = NULL;
  183. re->cc_ = ccb->GetCharClass();
  184. delete ccb;
  185. }
  186. return re;
  187. }
  188. // Pushes the given regular expression onto the stack.
  189. // Could check for too much memory used here.
  190. bool Regexp::ParseState::PushRegexp(Regexp* re) {
  191. MaybeConcatString(-1, NoParseFlags);
  192. // Special case: a character class of one character is just
  193. // a literal. This is a common idiom for escaping
  194. // single characters (e.g., [.] instead of \.), and some
  195. // analysis does better with fewer character classes.
  196. // Similarly, [Aa] can be rewritten as a literal A with ASCII case folding.
  197. if (re->op_ == kRegexpCharClass && re->ccb_ != NULL) {
  198. re->ccb_->RemoveAbove(rune_max_);
  199. if (re->ccb_->size() == 1) {
  200. Rune r = re->ccb_->begin()->lo;
  201. re->Decref();
  202. re = new Regexp(kRegexpLiteral, flags_);
  203. re->rune_ = r;
  204. } else if (re->ccb_->size() == 2) {
  205. Rune r = re->ccb_->begin()->lo;
  206. if ('A' <= r && r <= 'Z' && re->ccb_->Contains(r + 'a' - 'A')) {
  207. re->Decref();
  208. re = new Regexp(kRegexpLiteral, flags_ | FoldCase);
  209. re->rune_ = r + 'a' - 'A';
  210. }
  211. }
  212. }
  213. if (!IsMarker(re->op()))
  214. re->simple_ = re->ComputeSimple();
  215. re->down_ = stacktop_;
  216. stacktop_ = re;
  217. return true;
  218. }
  219. // Searches the case folding tables and returns the CaseFold* that contains r.
  220. // If there isn't one, returns the CaseFold* with smallest f->lo bigger than r.
  221. // If there isn't one, returns NULL.
  222. const CaseFold* LookupCaseFold(const CaseFold *f, int n, Rune r) {
  223. const CaseFold* ef = f + n;
  224. // Binary search for entry containing r.
  225. while (n > 0) {
  226. int m = n/2;
  227. if (f[m].lo <= r && r <= f[m].hi)
  228. return &f[m];
  229. if (r < f[m].lo) {
  230. n = m;
  231. } else {
  232. f += m+1;
  233. n -= m+1;
  234. }
  235. }
  236. // There is no entry that contains r, but f points
  237. // where it would have been. Unless f points at
  238. // the end of the array, it points at the next entry
  239. // after r.
  240. if (f < ef)
  241. return f;
  242. // No entry contains r; no entry contains runes > r.
  243. return NULL;
  244. }
  245. // Returns the result of applying the fold f to the rune r.
  246. Rune ApplyFold(const CaseFold *f, Rune r) {
  247. switch (f->delta) {
  248. default:
  249. return r + f->delta;
  250. case EvenOddSkip: // even <-> odd but only applies to every other
  251. if ((r - f->lo) % 2)
  252. return r;
  253. FALLTHROUGH_INTENDED;
  254. case EvenOdd: // even <-> odd
  255. if (r%2 == 0)
  256. return r + 1;
  257. return r - 1;
  258. case OddEvenSkip: // odd <-> even but only applies to every other
  259. if ((r - f->lo) % 2)
  260. return r;
  261. FALLTHROUGH_INTENDED;
  262. case OddEven: // odd <-> even
  263. if (r%2 == 1)
  264. return r + 1;
  265. return r - 1;
  266. }
  267. }
  268. // Returns the next Rune in r's folding cycle (see unicode_casefold.h).
  269. // Examples:
  270. // CycleFoldRune('A') = 'a'
  271. // CycleFoldRune('a') = 'A'
  272. //
  273. // CycleFoldRune('K') = 'k'
  274. // CycleFoldRune('k') = 0x212A (Kelvin)
  275. // CycleFoldRune(0x212A) = 'K'
  276. //
  277. // CycleFoldRune('?') = '?'
  278. Rune CycleFoldRune(Rune r) {
  279. const CaseFold* f = LookupCaseFold(unicode_casefold, num_unicode_casefold, r);
  280. if (f == NULL || r < f->lo)
  281. return r;
  282. return ApplyFold(f, r);
  283. }
  284. // Add lo-hi to the class, along with their fold-equivalent characters.
  285. // If lo-hi is already in the class, assume that the fold-equivalent
  286. // chars are there too, so there's no work to do.
  287. static void AddFoldedRange(CharClassBuilder* cc, Rune lo, Rune hi, int depth) {
  288. // AddFoldedRange calls itself recursively for each rune in the fold cycle.
  289. // Most folding cycles are small: there aren't any bigger than four in the
  290. // current Unicode tables. make_unicode_casefold.py checks that
  291. // the cycles are not too long, and we double-check here using depth.
  292. if (depth > 10) {
  293. LOG(DFATAL) << "AddFoldedRange recurses too much.";
  294. return;
  295. }
  296. if (!cc->AddRange(lo, hi)) // lo-hi was already there? we're done
  297. return;
  298. while (lo <= hi) {
  299. const CaseFold* f = LookupCaseFold(unicode_casefold, num_unicode_casefold, lo);
  300. if (f == NULL) // lo has no fold, nor does anything above lo
  301. break;
  302. if (lo < f->lo) { // lo has no fold; next rune with a fold is f->lo
  303. lo = f->lo;
  304. continue;
  305. }
  306. // Add in the result of folding the range lo - f->hi
  307. // and that range's fold, recursively.
  308. Rune lo1 = lo;
  309. Rune hi1 = std::min<Rune>(hi, f->hi);
  310. switch (f->delta) {
  311. default:
  312. lo1 += f->delta;
  313. hi1 += f->delta;
  314. break;
  315. case EvenOdd:
  316. if (lo1%2 == 1)
  317. lo1--;
  318. if (hi1%2 == 0)
  319. hi1++;
  320. break;
  321. case OddEven:
  322. if (lo1%2 == 0)
  323. lo1--;
  324. if (hi1%2 == 1)
  325. hi1++;
  326. break;
  327. }
  328. AddFoldedRange(cc, lo1, hi1, depth+1);
  329. // Pick up where this fold left off.
  330. lo = f->hi + 1;
  331. }
  332. }
  333. // Pushes the literal rune r onto the stack.
  334. bool Regexp::ParseState::PushLiteral(Rune r) {
  335. // Do case folding if needed.
  336. if ((flags_ & FoldCase) && CycleFoldRune(r) != r) {
  337. Regexp* re = new Regexp(kRegexpCharClass, flags_ & ~FoldCase);
  338. re->ccb_ = new CharClassBuilder;
  339. Rune r1 = r;
  340. do {
  341. if (!(flags_ & NeverNL) || r != '\n') {
  342. re->ccb_->AddRange(r, r);
  343. }
  344. r = CycleFoldRune(r);
  345. } while (r != r1);
  346. return PushRegexp(re);
  347. }
  348. // Exclude newline if applicable.
  349. if ((flags_ & NeverNL) && r == '\n')
  350. return PushRegexp(new Regexp(kRegexpNoMatch, flags_));
  351. // No fancy stuff worked. Ordinary literal.
  352. if (MaybeConcatString(r, flags_))
  353. return true;
  354. Regexp* re = new Regexp(kRegexpLiteral, flags_);
  355. re->rune_ = r;
  356. return PushRegexp(re);
  357. }
  358. // Pushes a ^ onto the stack.
  359. bool Regexp::ParseState::PushCaret() {
  360. if (flags_ & OneLine) {
  361. return PushSimpleOp(kRegexpBeginText);
  362. }
  363. return PushSimpleOp(kRegexpBeginLine);
  364. }
  365. // Pushes a \b or \B onto the stack.
  366. bool Regexp::ParseState::PushWordBoundary(bool word) {
  367. if (word)
  368. return PushSimpleOp(kRegexpWordBoundary);
  369. return PushSimpleOp(kRegexpNoWordBoundary);
  370. }
  371. // Pushes a $ onto the stack.
  372. bool Regexp::ParseState::PushDollar() {
  373. if (flags_ & OneLine) {
  374. // Clumsy marker so that MimicsPCRE() can tell whether
  375. // this kRegexpEndText was a $ and not a \z.
  376. Regexp::ParseFlags oflags = flags_;
  377. flags_ = flags_ | WasDollar;
  378. bool ret = PushSimpleOp(kRegexpEndText);
  379. flags_ = oflags;
  380. return ret;
  381. }
  382. return PushSimpleOp(kRegexpEndLine);
  383. }
  384. // Pushes a . onto the stack.
  385. bool Regexp::ParseState::PushDot() {
  386. if ((flags_ & DotNL) && !(flags_ & NeverNL))
  387. return PushSimpleOp(kRegexpAnyChar);
  388. // Rewrite . into [^\n]
  389. Regexp* re = new Regexp(kRegexpCharClass, flags_ & ~FoldCase);
  390. re->ccb_ = new CharClassBuilder;
  391. re->ccb_->AddRange(0, '\n' - 1);
  392. re->ccb_->AddRange('\n' + 1, rune_max_);
  393. return PushRegexp(re);
  394. }
  395. // Pushes a regexp with the given op (and no args) onto the stack.
  396. bool Regexp::ParseState::PushSimpleOp(RegexpOp op) {
  397. Regexp* re = new Regexp(op, flags_);
  398. return PushRegexp(re);
  399. }
  400. // Pushes a repeat operator regexp onto the stack.
  401. // A valid argument for the operator must already be on the stack.
  402. // The char c is the name of the operator, for use in error messages.
  403. bool Regexp::ParseState::PushRepeatOp(RegexpOp op, const StringPiece& s,
  404. bool nongreedy) {
  405. if (stacktop_ == NULL || IsMarker(stacktop_->op())) {
  406. status_->set_code(kRegexpRepeatArgument);
  407. status_->set_error_arg(s);
  408. return false;
  409. }
  410. Regexp::ParseFlags fl = flags_;
  411. if (nongreedy)
  412. fl = fl ^ NonGreedy;
  413. // Squash **, ++ and ??. Regexp::Star() et al. handle this too, but
  414. // they're mostly for use during simplification, not during parsing.
  415. if (op == stacktop_->op() && fl == stacktop_->parse_flags())
  416. return true;
  417. // Squash *+, *?, +*, +?, ?* and ?+. They all squash to *, so because
  418. // op is a repeat, we just have to check that stacktop_->op() is too,
  419. // then adjust stacktop_.
  420. if ((stacktop_->op() == kRegexpStar ||
  421. stacktop_->op() == kRegexpPlus ||
  422. stacktop_->op() == kRegexpQuest) &&
  423. fl == stacktop_->parse_flags()) {
  424. stacktop_->op_ = kRegexpStar;
  425. return true;
  426. }
  427. Regexp* re = new Regexp(op, fl);
  428. re->AllocSub(1);
  429. re->down_ = stacktop_->down_;
  430. re->sub()[0] = FinishRegexp(stacktop_);
  431. re->simple_ = re->ComputeSimple();
  432. stacktop_ = re;
  433. return true;
  434. }
  435. // RepetitionWalker reports whether the repetition regexp is valid.
  436. // Valid means that the combination of the top-level repetition
  437. // and any inner repetitions does not exceed n copies of the
  438. // innermost thing.
  439. // This rewalks the regexp tree and is called for every repetition,
  440. // so we have to worry about inducing quadratic behavior in the parser.
  441. // We avoid this by only using RepetitionWalker when min or max >= 2.
  442. // In that case the depth of any >= 2 nesting can only get to 9 without
  443. // triggering a parse error, so each subtree can only be rewalked 9 times.
  444. class RepetitionWalker : public Regexp::Walker<int> {
  445. public:
  446. RepetitionWalker() {}
  447. virtual int PreVisit(Regexp* re, int parent_arg, bool* stop);
  448. virtual int PostVisit(Regexp* re, int parent_arg, int pre_arg,
  449. int* child_args, int nchild_args);
  450. virtual int ShortVisit(Regexp* re, int parent_arg);
  451. private:
  452. RepetitionWalker(const RepetitionWalker&) = delete;
  453. RepetitionWalker& operator=(const RepetitionWalker&) = delete;
  454. };
  455. int RepetitionWalker::PreVisit(Regexp* re, int parent_arg, bool* stop) {
  456. int arg = parent_arg;
  457. if (re->op() == kRegexpRepeat) {
  458. int m = re->max();
  459. if (m < 0) {
  460. m = re->min();
  461. }
  462. if (m > 0) {
  463. arg /= m;
  464. }
  465. }
  466. return arg;
  467. }
  468. int RepetitionWalker::PostVisit(Regexp* re, int parent_arg, int pre_arg,
  469. int* child_args, int nchild_args) {
  470. int arg = pre_arg;
  471. for (int i = 0; i < nchild_args; i++) {
  472. if (child_args[i] < arg) {
  473. arg = child_args[i];
  474. }
  475. }
  476. return arg;
  477. }
  478. int RepetitionWalker::ShortVisit(Regexp* re, int parent_arg) {
  479. // Should never be called: we use Walk(), not WalkExponential().
  480. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  481. LOG(DFATAL) << "RepetitionWalker::ShortVisit called";
  482. #endif
  483. return 0;
  484. }
  485. // Pushes a repetition regexp onto the stack.
  486. // A valid argument for the operator must already be on the stack.
  487. bool Regexp::ParseState::PushRepetition(int min, int max,
  488. const StringPiece& s,
  489. bool nongreedy) {
  490. if ((max != -1 && max < min) ||
  491. min > maximum_repeat_count ||
  492. max > maximum_repeat_count) {
  493. status_->set_code(kRegexpRepeatSize);
  494. status_->set_error_arg(s);
  495. return false;
  496. }
  497. if (stacktop_ == NULL || IsMarker(stacktop_->op())) {
  498. status_->set_code(kRegexpRepeatArgument);
  499. status_->set_error_arg(s);
  500. return false;
  501. }
  502. Regexp::ParseFlags fl = flags_;
  503. if (nongreedy)
  504. fl = fl ^ NonGreedy;
  505. Regexp* re = new Regexp(kRegexpRepeat, fl);
  506. re->min_ = min;
  507. re->max_ = max;
  508. re->AllocSub(1);
  509. re->down_ = stacktop_->down_;
  510. re->sub()[0] = FinishRegexp(stacktop_);
  511. re->simple_ = re->ComputeSimple();
  512. stacktop_ = re;
  513. if (min >= 2 || max >= 2) {
  514. RepetitionWalker w;
  515. if (w.Walk(stacktop_, maximum_repeat_count) == 0) {
  516. status_->set_code(kRegexpRepeatSize);
  517. status_->set_error_arg(s);
  518. return false;
  519. }
  520. }
  521. return true;
  522. }
  523. // Checks whether a particular regexp op is a marker.
  524. bool Regexp::ParseState::IsMarker(RegexpOp op) {
  525. return op >= kLeftParen;
  526. }
  527. // Processes a left parenthesis in the input.
  528. // Pushes a marker onto the stack.
  529. bool Regexp::ParseState::DoLeftParen(const StringPiece& name) {
  530. Regexp* re = new Regexp(kLeftParen, flags_);
  531. re->cap_ = ++ncap_;
  532. if (name.data() != NULL)
  533. re->name_ = new std::string(name);
  534. return PushRegexp(re);
  535. }
  536. // Pushes a non-capturing marker onto the stack.
  537. bool Regexp::ParseState::DoLeftParenNoCapture() {
  538. Regexp* re = new Regexp(kLeftParen, flags_);
  539. re->cap_ = -1;
  540. return PushRegexp(re);
  541. }
  542. // Processes a vertical bar in the input.
  543. bool Regexp::ParseState::DoVerticalBar() {
  544. MaybeConcatString(-1, NoParseFlags);
  545. DoConcatenation();
  546. // Below the vertical bar is a list to alternate.
  547. // Above the vertical bar is a list to concatenate.
  548. // We just did the concatenation, so either swap
  549. // the result below the vertical bar or push a new
  550. // vertical bar on the stack.
  551. Regexp* r1;
  552. Regexp* r2;
  553. if ((r1 = stacktop_) != NULL &&
  554. (r2 = r1->down_) != NULL &&
  555. r2->op() == kVerticalBar) {
  556. Regexp* r3;
  557. if ((r3 = r2->down_) != NULL &&
  558. (r1->op() == kRegexpAnyChar || r3->op() == kRegexpAnyChar)) {
  559. // AnyChar is above or below the vertical bar. Let it subsume
  560. // the other when the other is Literal, CharClass or AnyChar.
  561. if (r3->op() == kRegexpAnyChar &&
  562. (r1->op() == kRegexpLiteral ||
  563. r1->op() == kRegexpCharClass ||
  564. r1->op() == kRegexpAnyChar)) {
  565. // Discard r1.
  566. stacktop_ = r2;
  567. r1->Decref();
  568. return true;
  569. }
  570. if (r1->op() == kRegexpAnyChar &&
  571. (r3->op() == kRegexpLiteral ||
  572. r3->op() == kRegexpCharClass ||
  573. r3->op() == kRegexpAnyChar)) {
  574. // Rearrange the stack and discard r3.
  575. r1->down_ = r3->down_;
  576. r2->down_ = r1;
  577. stacktop_ = r2;
  578. r3->Decref();
  579. return true;
  580. }
  581. }
  582. // Swap r1 below vertical bar (r2).
  583. r1->down_ = r2->down_;
  584. r2->down_ = r1;
  585. stacktop_ = r2;
  586. return true;
  587. }
  588. return PushSimpleOp(kVerticalBar);
  589. }
  590. // Processes a right parenthesis in the input.
  591. bool Regexp::ParseState::DoRightParen() {
  592. // Finish the current concatenation and alternation.
  593. DoAlternation();
  594. // The stack should be: LeftParen regexp
  595. // Remove the LeftParen, leaving the regexp,
  596. // parenthesized.
  597. Regexp* r1;
  598. Regexp* r2;
  599. if ((r1 = stacktop_) == NULL ||
  600. (r2 = r1->down_) == NULL ||
  601. r2->op() != kLeftParen) {
  602. status_->set_code(kRegexpUnexpectedParen);
  603. status_->set_error_arg(whole_regexp_);
  604. return false;
  605. }
  606. // Pop off r1, r2. Will Decref or reuse below.
  607. stacktop_ = r2->down_;
  608. // Restore flags from when paren opened.
  609. Regexp* re = r2;
  610. flags_ = re->parse_flags();
  611. // Rewrite LeftParen as capture if needed.
  612. if (re->cap_ > 0) {
  613. re->op_ = kRegexpCapture;
  614. // re->cap_ is already set
  615. re->AllocSub(1);
  616. re->sub()[0] = FinishRegexp(r1);
  617. re->simple_ = re->ComputeSimple();
  618. } else {
  619. re->Decref();
  620. re = r1;
  621. }
  622. return PushRegexp(re);
  623. }
  624. // Processes the end of input, returning the final regexp.
  625. Regexp* Regexp::ParseState::DoFinish() {
  626. DoAlternation();
  627. Regexp* re = stacktop_;
  628. if (re != NULL && re->down_ != NULL) {
  629. status_->set_code(kRegexpMissingParen);
  630. status_->set_error_arg(whole_regexp_);
  631. return NULL;
  632. }
  633. stacktop_ = NULL;
  634. return FinishRegexp(re);
  635. }
  636. // Returns the leading regexp that re starts with.
  637. // The returned Regexp* points into a piece of re,
  638. // so it must not be used after the caller calls re->Decref().
  639. Regexp* Regexp::LeadingRegexp(Regexp* re) {
  640. if (re->op() == kRegexpEmptyMatch)
  641. return NULL;
  642. if (re->op() == kRegexpConcat && re->nsub() >= 2) {
  643. Regexp** sub = re->sub();
  644. if (sub[0]->op() == kRegexpEmptyMatch)
  645. return NULL;
  646. return sub[0];
  647. }
  648. return re;
  649. }
  650. // Removes LeadingRegexp(re) from re and returns what's left.
  651. // Consumes the reference to re and may edit it in place.
  652. // If caller wants to hold on to LeadingRegexp(re),
  653. // must have already Incref'ed it.
  654. Regexp* Regexp::RemoveLeadingRegexp(Regexp* re) {
  655. if (re->op() == kRegexpEmptyMatch)
  656. return re;
  657. if (re->op() == kRegexpConcat && re->nsub() >= 2) {
  658. Regexp** sub = re->sub();
  659. if (sub[0]->op() == kRegexpEmptyMatch)
  660. return re;
  661. sub[0]->Decref();
  662. sub[0] = NULL;
  663. if (re->nsub() == 2) {
  664. // Collapse concatenation to single regexp.
  665. Regexp* nre = sub[1];
  666. sub[1] = NULL;
  667. re->Decref();
  668. return nre;
  669. }
  670. // 3 or more -> 2 or more.
  671. re->nsub_--;
  672. memmove(sub, sub + 1, re->nsub_ * sizeof sub[0]);
  673. return re;
  674. }
  675. Regexp::ParseFlags pf = re->parse_flags();
  676. re->Decref();
  677. return new Regexp(kRegexpEmptyMatch, pf);
  678. }
  679. // Returns the leading string that re starts with.
  680. // The returned Rune* points into a piece of re,
  681. // so it must not be used after the caller calls re->Decref().
  682. Rune* Regexp::LeadingString(Regexp* re, int *nrune,
  683. Regexp::ParseFlags *flags) {
  684. while (re->op() == kRegexpConcat && re->nsub() > 0)
  685. re = re->sub()[0];
  686. *flags = static_cast<Regexp::ParseFlags>(re->parse_flags_ & Regexp::FoldCase);
  687. if (re->op() == kRegexpLiteral) {
  688. *nrune = 1;
  689. return &re->rune_;
  690. }
  691. if (re->op() == kRegexpLiteralString) {
  692. *nrune = re->nrunes_;
  693. return re->runes_;
  694. }
  695. *nrune = 0;
  696. return NULL;
  697. }
  698. // Removes the first n leading runes from the beginning of re.
  699. // Edits re in place.
  700. void Regexp::RemoveLeadingString(Regexp* re, int n) {
  701. // Chase down concats to find first string.
  702. // For regexps generated by parser, nested concats are
  703. // flattened except when doing so would overflow the 16-bit
  704. // limit on the size of a concatenation, so we should never
  705. // see more than two here.
  706. Regexp* stk[4];
  707. size_t d = 0;
  708. while (re->op() == kRegexpConcat) {
  709. if (d < arraysize(stk))
  710. stk[d++] = re;
  711. re = re->sub()[0];
  712. }
  713. // Remove leading string from re.
  714. if (re->op() == kRegexpLiteral) {
  715. re->rune_ = 0;
  716. re->op_ = kRegexpEmptyMatch;
  717. } else if (re->op() == kRegexpLiteralString) {
  718. if (n >= re->nrunes_) {
  719. delete[] re->runes_;
  720. re->runes_ = NULL;
  721. re->nrunes_ = 0;
  722. re->op_ = kRegexpEmptyMatch;
  723. } else if (n == re->nrunes_ - 1) {
  724. Rune rune = re->runes_[re->nrunes_ - 1];
  725. delete[] re->runes_;
  726. re->runes_ = NULL;
  727. re->nrunes_ = 0;
  728. re->rune_ = rune;
  729. re->op_ = kRegexpLiteral;
  730. } else {
  731. re->nrunes_ -= n;
  732. memmove(re->runes_, re->runes_ + n, re->nrunes_ * sizeof re->runes_[0]);
  733. }
  734. }
  735. // If re is now empty, concatenations might simplify too.
  736. while (d > 0) {
  737. re = stk[--d];
  738. Regexp** sub = re->sub();
  739. if (sub[0]->op() == kRegexpEmptyMatch) {
  740. sub[0]->Decref();
  741. sub[0] = NULL;
  742. // Delete first element of concat.
  743. switch (re->nsub()) {
  744. case 0:
  745. case 1:
  746. // Impossible.
  747. LOG(DFATAL) << "Concat of " << re->nsub();
  748. re->submany_ = NULL;
  749. re->op_ = kRegexpEmptyMatch;
  750. break;
  751. case 2: {
  752. // Replace re with sub[1].
  753. Regexp* old = sub[1];
  754. sub[1] = NULL;
  755. re->Swap(old);
  756. old->Decref();
  757. break;
  758. }
  759. default:
  760. // Slide down.
  761. re->nsub_--;
  762. memmove(sub, sub + 1, re->nsub_ * sizeof sub[0]);
  763. break;
  764. }
  765. }
  766. }
  767. }
  768. // In the context of factoring alternations, a Splice is: a factored prefix or
  769. // merged character class computed by one iteration of one round of factoring;
  770. // the span of subexpressions of the alternation to be "spliced" (i.e. removed
  771. // and replaced); and, for a factored prefix, the number of suffixes after any
  772. // factoring that might have subsequently been performed on them. For a merged
  773. // character class, there are no suffixes, of course, so the field is ignored.
  774. struct Splice {
  775. Splice(Regexp* prefix, Regexp** sub, int nsub)
  776. : prefix(prefix),
  777. sub(sub),
  778. nsub(nsub),
  779. nsuffix(-1) {}
  780. Regexp* prefix;
  781. Regexp** sub;
  782. int nsub;
  783. int nsuffix;
  784. };
  785. // Named so because it is used to implement an explicit stack, a Frame is: the
  786. // span of subexpressions of the alternation to be factored; the current round
  787. // of factoring; any Splices computed; and, for a factored prefix, an iterator
  788. // to the next Splice to be factored (i.e. in another Frame) because suffixes.
  789. struct Frame {
  790. Frame(Regexp** sub, int nsub)
  791. : sub(sub),
  792. nsub(nsub),
  793. round(0) {}
  794. Regexp** sub;
  795. int nsub;
  796. int round;
  797. std::vector<Splice> splices;
  798. int spliceidx;
  799. };
  800. // Bundled into a class for friend access to Regexp without needing to declare
  801. // (or define) Splice in regexp.h.
  802. class FactorAlternationImpl {
  803. public:
  804. static void Round1(Regexp** sub, int nsub,
  805. Regexp::ParseFlags flags,
  806. std::vector<Splice>* splices);
  807. static void Round2(Regexp** sub, int nsub,
  808. Regexp::ParseFlags flags,
  809. std::vector<Splice>* splices);
  810. static void Round3(Regexp** sub, int nsub,
  811. Regexp::ParseFlags flags,
  812. std::vector<Splice>* splices);
  813. };
  814. // Factors common prefixes from alternation.
  815. // For example,
  816. // ABC|ABD|AEF|BCX|BCY
  817. // simplifies to
  818. // A(B(C|D)|EF)|BC(X|Y)
  819. // and thence to
  820. // A(B[CD]|EF)|BC[XY]
  821. //
  822. // Rewrites sub to contain simplified list to alternate and returns
  823. // the new length of sub. Adjusts reference counts accordingly
  824. // (incoming sub[i] decremented, outgoing sub[i] incremented).
  825. int Regexp::FactorAlternation(Regexp** sub, int nsub, ParseFlags flags) {
  826. std::vector<Frame> stk;
  827. stk.emplace_back(sub, nsub);
  828. for (;;) {
  829. auto& sub = stk.back().sub;
  830. auto& nsub = stk.back().nsub;
  831. auto& round = stk.back().round;
  832. auto& splices = stk.back().splices;
  833. auto& spliceidx = stk.back().spliceidx;
  834. if (splices.empty()) {
  835. // Advance to the next round of factoring. Note that this covers
  836. // the initialised state: when splices is empty and round is 0.
  837. round++;
  838. } else if (spliceidx < static_cast<int>(splices.size())) {
  839. // We have at least one more Splice to factor. Recurse logically.
  840. stk.emplace_back(splices[spliceidx].sub, splices[spliceidx].nsub);
  841. continue;
  842. } else {
  843. // We have no more Splices to factor. Apply them.
  844. auto iter = splices.begin();
  845. int out = 0;
  846. for (int i = 0; i < nsub; ) {
  847. // Copy until we reach where the next Splice begins.
  848. while (sub + i < iter->sub)
  849. sub[out++] = sub[i++];
  850. switch (round) {
  851. case 1:
  852. case 2: {
  853. // Assemble the Splice prefix and the suffixes.
  854. Regexp* re[2];
  855. re[0] = iter->prefix;
  856. re[1] = Regexp::AlternateNoFactor(iter->sub, iter->nsuffix, flags);
  857. sub[out++] = Regexp::Concat(re, 2, flags);
  858. i += iter->nsub;
  859. break;
  860. }
  861. case 3:
  862. // Just use the Splice prefix.
  863. sub[out++] = iter->prefix;
  864. i += iter->nsub;
  865. break;
  866. default:
  867. LOG(DFATAL) << "unknown round: " << round;
  868. break;
  869. }
  870. // If we are done, copy until the end of sub.
  871. if (++iter == splices.end()) {
  872. while (i < nsub)
  873. sub[out++] = sub[i++];
  874. }
  875. }
  876. splices.clear();
  877. nsub = out;
  878. // Advance to the next round of factoring.
  879. round++;
  880. }
  881. switch (round) {
  882. case 1:
  883. FactorAlternationImpl::Round1(sub, nsub, flags, &splices);
  884. break;
  885. case 2:
  886. FactorAlternationImpl::Round2(sub, nsub, flags, &splices);
  887. break;
  888. case 3:
  889. FactorAlternationImpl::Round3(sub, nsub, flags, &splices);
  890. break;
  891. case 4:
  892. if (stk.size() == 1) {
  893. // We are at the top of the stack. Just return.
  894. return nsub;
  895. } else {
  896. // Pop the stack and set the number of suffixes.
  897. // (Note that references will be invalidated!)
  898. int nsuffix = nsub;
  899. stk.pop_back();
  900. stk.back().splices[stk.back().spliceidx].nsuffix = nsuffix;
  901. ++stk.back().spliceidx;
  902. continue;
  903. }
  904. default:
  905. LOG(DFATAL) << "unknown round: " << round;
  906. break;
  907. }
  908. // Set spliceidx depending on whether we have Splices to factor.
  909. if (splices.empty() || round == 3) {
  910. spliceidx = static_cast<int>(splices.size());
  911. } else {
  912. spliceidx = 0;
  913. }
  914. }
  915. }
  916. void FactorAlternationImpl::Round1(Regexp** sub, int nsub,
  917. Regexp::ParseFlags flags,
  918. std::vector<Splice>* splices) {
  919. // Round 1: Factor out common literal prefixes.
  920. int start = 0;
  921. Rune* rune = NULL;
  922. int nrune = 0;
  923. Regexp::ParseFlags runeflags = Regexp::NoParseFlags;
  924. for (int i = 0; i <= nsub; i++) {
  925. // Invariant: sub[start:i] consists of regexps that all
  926. // begin with rune[0:nrune].
  927. Rune* rune_i = NULL;
  928. int nrune_i = 0;
  929. Regexp::ParseFlags runeflags_i = Regexp::NoParseFlags;
  930. if (i < nsub) {
  931. rune_i = Regexp::LeadingString(sub[i], &nrune_i, &runeflags_i);
  932. if (runeflags_i == runeflags) {
  933. int same = 0;
  934. while (same < nrune && same < nrune_i && rune[same] == rune_i[same])
  935. same++;
  936. if (same > 0) {
  937. // Matches at least one rune in current range. Keep going around.
  938. nrune = same;
  939. continue;
  940. }
  941. }
  942. }
  943. // Found end of a run with common leading literal string:
  944. // sub[start:i] all begin with rune[0:nrune],
  945. // but sub[i] does not even begin with rune[0].
  946. if (i == start) {
  947. // Nothing to do - first iteration.
  948. } else if (i == start+1) {
  949. // Just one: don't bother factoring.
  950. } else {
  951. Regexp* prefix = Regexp::LiteralString(rune, nrune, runeflags);
  952. for (int j = start; j < i; j++)
  953. Regexp::RemoveLeadingString(sub[j], nrune);
  954. splices->emplace_back(prefix, sub + start, i - start);
  955. }
  956. // Prepare for next iteration (if there is one).
  957. if (i < nsub) {
  958. start = i;
  959. rune = rune_i;
  960. nrune = nrune_i;
  961. runeflags = runeflags_i;
  962. }
  963. }
  964. }
  965. void FactorAlternationImpl::Round2(Regexp** sub, int nsub,
  966. Regexp::ParseFlags flags,
  967. std::vector<Splice>* splices) {
  968. // Round 2: Factor out common simple prefixes,
  969. // just the first piece of each concatenation.
  970. // This will be good enough a lot of the time.
  971. //
  972. // Complex subexpressions (e.g. involving quantifiers)
  973. // are not safe to factor because that collapses their
  974. // distinct paths through the automaton, which affects
  975. // correctness in some cases.
  976. int start = 0;
  977. Regexp* first = NULL;
  978. for (int i = 0; i <= nsub; i++) {
  979. // Invariant: sub[start:i] consists of regexps that all
  980. // begin with first.
  981. Regexp* first_i = NULL;
  982. if (i < nsub) {
  983. first_i = Regexp::LeadingRegexp(sub[i]);
  984. if (first != NULL &&
  985. // first must be an empty-width op
  986. // OR a char class, any char or any byte
  987. // OR a fixed repeat of a literal, char class, any char or any byte.
  988. (first->op() == kRegexpBeginLine ||
  989. first->op() == kRegexpEndLine ||
  990. first->op() == kRegexpWordBoundary ||
  991. first->op() == kRegexpNoWordBoundary ||
  992. first->op() == kRegexpBeginText ||
  993. first->op() == kRegexpEndText ||
  994. first->op() == kRegexpCharClass ||
  995. first->op() == kRegexpAnyChar ||
  996. first->op() == kRegexpAnyByte ||
  997. (first->op() == kRegexpRepeat &&
  998. first->min() == first->max() &&
  999. (first->sub()[0]->op() == kRegexpLiteral ||
  1000. first->sub()[0]->op() == kRegexpCharClass ||
  1001. first->sub()[0]->op() == kRegexpAnyChar ||
  1002. first->sub()[0]->op() == kRegexpAnyByte))) &&
  1003. Regexp::Equal(first, first_i))
  1004. continue;
  1005. }
  1006. // Found end of a run with common leading regexp:
  1007. // sub[start:i] all begin with first,
  1008. // but sub[i] does not.
  1009. if (i == start) {
  1010. // Nothing to do - first iteration.
  1011. } else if (i == start+1) {
  1012. // Just one: don't bother factoring.
  1013. } else {
  1014. Regexp* prefix = first->Incref();
  1015. for (int j = start; j < i; j++)
  1016. sub[j] = Regexp::RemoveLeadingRegexp(sub[j]);
  1017. splices->emplace_back(prefix, sub + start, i - start);
  1018. }
  1019. // Prepare for next iteration (if there is one).
  1020. if (i < nsub) {
  1021. start = i;
  1022. first = first_i;
  1023. }
  1024. }
  1025. }
  1026. void FactorAlternationImpl::Round3(Regexp** sub, int nsub,
  1027. Regexp::ParseFlags flags,
  1028. std::vector<Splice>* splices) {
  1029. // Round 3: Merge runs of literals and/or character classes.
  1030. int start = 0;
  1031. Regexp* first = NULL;
  1032. for (int i = 0; i <= nsub; i++) {
  1033. // Invariant: sub[start:i] consists of regexps that all
  1034. // are either literals (i.e. runes) or character classes.
  1035. Regexp* first_i = NULL;
  1036. if (i < nsub) {
  1037. first_i = sub[i];
  1038. if (first != NULL &&
  1039. (first->op() == kRegexpLiteral ||
  1040. first->op() == kRegexpCharClass) &&
  1041. (first_i->op() == kRegexpLiteral ||
  1042. first_i->op() == kRegexpCharClass))
  1043. continue;
  1044. }
  1045. // Found end of a run of Literal/CharClass:
  1046. // sub[start:i] all are either one or the other,
  1047. // but sub[i] is not.
  1048. if (i == start) {
  1049. // Nothing to do - first iteration.
  1050. } else if (i == start+1) {
  1051. // Just one: don't bother factoring.
  1052. } else {
  1053. CharClassBuilder ccb;
  1054. for (int j = start; j < i; j++) {
  1055. Regexp* re = sub[j];
  1056. if (re->op() == kRegexpCharClass) {
  1057. CharClass* cc = re->cc();
  1058. for (CharClass::iterator it = cc->begin(); it != cc->end(); ++it)
  1059. ccb.AddRange(it->lo, it->hi);
  1060. } else if (re->op() == kRegexpLiteral) {
  1061. ccb.AddRangeFlags(re->rune(), re->rune(), re->parse_flags());
  1062. } else {
  1063. LOG(DFATAL) << "RE2: unexpected op: " << re->op() << " "
  1064. << re->ToString();
  1065. }
  1066. re->Decref();
  1067. }
  1068. Regexp* re = Regexp::NewCharClass(ccb.GetCharClass(), flags);
  1069. splices->emplace_back(re, sub + start, i - start);
  1070. }
  1071. // Prepare for next iteration (if there is one).
  1072. if (i < nsub) {
  1073. start = i;
  1074. first = first_i;
  1075. }
  1076. }
  1077. }
  1078. // Collapse the regexps on top of the stack, down to the
  1079. // first marker, into a new op node (op == kRegexpAlternate
  1080. // or op == kRegexpConcat).
  1081. void Regexp::ParseState::DoCollapse(RegexpOp op) {
  1082. // Scan backward to marker, counting children of composite.
  1083. int n = 0;
  1084. Regexp* next = NULL;
  1085. Regexp* sub;
  1086. for (sub = stacktop_; sub != NULL && !IsMarker(sub->op()); sub = next) {
  1087. next = sub->down_;
  1088. if (sub->op_ == op)
  1089. n += sub->nsub_;
  1090. else
  1091. n++;
  1092. }
  1093. // If there's just one child, leave it alone.
  1094. // (Concat of one thing is that one thing; alternate of one thing is same.)
  1095. if (stacktop_ != NULL && stacktop_->down_ == next)
  1096. return;
  1097. // Construct op (alternation or concatenation), flattening op of op.
  1098. PODArray<Regexp*> subs(n);
  1099. next = NULL;
  1100. int i = n;
  1101. for (sub = stacktop_; sub != NULL && !IsMarker(sub->op()); sub = next) {
  1102. next = sub->down_;
  1103. if (sub->op_ == op) {
  1104. Regexp** sub_subs = sub->sub();
  1105. for (int k = sub->nsub_ - 1; k >= 0; k--)
  1106. subs[--i] = sub_subs[k]->Incref();
  1107. sub->Decref();
  1108. } else {
  1109. subs[--i] = FinishRegexp(sub);
  1110. }
  1111. }
  1112. Regexp* re = ConcatOrAlternate(op, subs.data(), n, flags_, true);
  1113. re->simple_ = re->ComputeSimple();
  1114. re->down_ = next;
  1115. stacktop_ = re;
  1116. }
  1117. // Finishes the current concatenation,
  1118. // collapsing it into a single regexp on the stack.
  1119. void Regexp::ParseState::DoConcatenation() {
  1120. Regexp* r1 = stacktop_;
  1121. if (r1 == NULL || IsMarker(r1->op())) {
  1122. // empty concatenation is special case
  1123. Regexp* re = new Regexp(kRegexpEmptyMatch, flags_);
  1124. PushRegexp(re);
  1125. }
  1126. DoCollapse(kRegexpConcat);
  1127. }
  1128. // Finishes the current alternation,
  1129. // collapsing it to a single regexp on the stack.
  1130. void Regexp::ParseState::DoAlternation() {
  1131. DoVerticalBar();
  1132. // Now stack top is kVerticalBar.
  1133. Regexp* r1 = stacktop_;
  1134. stacktop_ = r1->down_;
  1135. r1->Decref();
  1136. DoCollapse(kRegexpAlternate);
  1137. }
  1138. // Incremental conversion of concatenated literals into strings.
  1139. // If top two elements on stack are both literal or string,
  1140. // collapse into single string.
  1141. // Don't walk down the stack -- the parser calls this frequently
  1142. // enough that below the bottom two is known to be collapsed.
  1143. // Only called when another regexp is about to be pushed
  1144. // on the stack, so that the topmost literal is not being considered.
  1145. // (Otherwise ab* would turn into (ab)*.)
  1146. // If r >= 0, consider pushing a literal r on the stack.
  1147. // Return whether that happened.
  1148. bool Regexp::ParseState::MaybeConcatString(int r, ParseFlags flags) {
  1149. Regexp* re1;
  1150. Regexp* re2;
  1151. if ((re1 = stacktop_) == NULL || (re2 = re1->down_) == NULL)
  1152. return false;
  1153. if (re1->op_ != kRegexpLiteral && re1->op_ != kRegexpLiteralString)
  1154. return false;
  1155. if (re2->op_ != kRegexpLiteral && re2->op_ != kRegexpLiteralString)
  1156. return false;
  1157. if ((re1->parse_flags_ & FoldCase) != (re2->parse_flags_ & FoldCase))
  1158. return false;
  1159. if (re2->op_ == kRegexpLiteral) {
  1160. // convert into string
  1161. Rune rune = re2->rune_;
  1162. re2->op_ = kRegexpLiteralString;
  1163. re2->nrunes_ = 0;
  1164. re2->runes_ = NULL;
  1165. re2->AddRuneToString(rune);
  1166. }
  1167. // push re1 into re2.
  1168. if (re1->op_ == kRegexpLiteral) {
  1169. re2->AddRuneToString(re1->rune_);
  1170. } else {
  1171. for (int i = 0; i < re1->nrunes_; i++)
  1172. re2->AddRuneToString(re1->runes_[i]);
  1173. re1->nrunes_ = 0;
  1174. delete[] re1->runes_;
  1175. re1->runes_ = NULL;
  1176. }
  1177. // reuse re1 if possible
  1178. if (r >= 0) {
  1179. re1->op_ = kRegexpLiteral;
  1180. re1->rune_ = r;
  1181. re1->parse_flags_ = static_cast<uint16_t>(flags);
  1182. return true;
  1183. }
  1184. stacktop_ = re2;
  1185. re1->Decref();
  1186. return false;
  1187. }
  1188. // Lexing routines.
  1189. // Parses a decimal integer, storing it in *np.
  1190. // Sets *s to span the remainder of the string.
  1191. static bool ParseInteger(StringPiece* s, int* np) {
  1192. if (s->empty() || !isdigit((*s)[0] & 0xFF))
  1193. return false;
  1194. // Disallow leading zeros.
  1195. if (s->size() >= 2 && (*s)[0] == '0' && isdigit((*s)[1] & 0xFF))
  1196. return false;
  1197. int n = 0;
  1198. int c;
  1199. while (!s->empty() && isdigit(c = (*s)[0] & 0xFF)) {
  1200. // Avoid overflow.
  1201. if (n >= 100000000)
  1202. return false;
  1203. n = n*10 + c - '0';
  1204. s->remove_prefix(1); // digit
  1205. }
  1206. *np = n;
  1207. return true;
  1208. }
  1209. // Parses a repetition suffix like {1,2} or {2} or {2,}.
  1210. // Sets *s to span the remainder of the string on success.
  1211. // Sets *lo and *hi to the given range.
  1212. // In the case of {2,}, the high number is unbounded;
  1213. // sets *hi to -1 to signify this.
  1214. // {,2} is NOT a valid suffix.
  1215. // The Maybe in the name signifies that the regexp parse
  1216. // doesn't fail even if ParseRepetition does, so the StringPiece
  1217. // s must NOT be edited unless MaybeParseRepetition returns true.
  1218. static bool MaybeParseRepetition(StringPiece* sp, int* lo, int* hi) {
  1219. StringPiece s = *sp;
  1220. if (s.empty() || s[0] != '{')
  1221. return false;
  1222. s.remove_prefix(1); // '{'
  1223. if (!ParseInteger(&s, lo))
  1224. return false;
  1225. if (s.empty())
  1226. return false;
  1227. if (s[0] == ',') {
  1228. s.remove_prefix(1); // ','
  1229. if (s.empty())
  1230. return false;
  1231. if (s[0] == '}') {
  1232. // {2,} means at least 2
  1233. *hi = -1;
  1234. } else {
  1235. // {2,4} means 2, 3, or 4.
  1236. if (!ParseInteger(&s, hi))
  1237. return false;
  1238. }
  1239. } else {
  1240. // {2} means exactly two
  1241. *hi = *lo;
  1242. }
  1243. if (s.empty() || s[0] != '}')
  1244. return false;
  1245. s.remove_prefix(1); // '}'
  1246. *sp = s;
  1247. return true;
  1248. }
  1249. // Removes the next Rune from the StringPiece and stores it in *r.
  1250. // Returns number of bytes removed from sp.
  1251. // Behaves as though there is a terminating NUL at the end of sp.
  1252. // Argument order is backwards from usual Google style
  1253. // but consistent with chartorune.
  1254. static int StringPieceToRune(Rune *r, StringPiece *sp, RegexpStatus* status) {
  1255. // fullrune() takes int, not size_t. However, it just looks
  1256. // at the leading byte and treats any length >= 4 the same.
  1257. if (fullrune(sp->data(), static_cast<int>(std::min(size_t{4}, sp->size())))) {
  1258. int n = chartorune(r, sp->data());
  1259. // Some copies of chartorune have a bug that accepts
  1260. // encodings of values in (10FFFF, 1FFFFF] as valid.
  1261. // Those values break the character class algorithm,
  1262. // which assumes Runemax is the largest rune.
  1263. if (*r > Runemax) {
  1264. n = 1;
  1265. *r = Runeerror;
  1266. }
  1267. if (!(n == 1 && *r == Runeerror)) { // no decoding error
  1268. sp->remove_prefix(n);
  1269. return n;
  1270. }
  1271. }
  1272. if (status != NULL) {
  1273. status->set_code(kRegexpBadUTF8);
  1274. status->set_error_arg(StringPiece());
  1275. }
  1276. return -1;
  1277. }
  1278. // Returns whether name is valid UTF-8.
  1279. // If not, sets status to kRegexpBadUTF8.
  1280. static bool IsValidUTF8(const StringPiece& s, RegexpStatus* status) {
  1281. StringPiece t = s;
  1282. Rune r;
  1283. while (!t.empty()) {
  1284. if (StringPieceToRune(&r, &t, status) < 0)
  1285. return false;
  1286. }
  1287. return true;
  1288. }
  1289. // Is c a hex digit?
  1290. static int IsHex(int c) {
  1291. return ('0' <= c && c <= '9') ||
  1292. ('A' <= c && c <= 'F') ||
  1293. ('a' <= c && c <= 'f');
  1294. }
  1295. // Convert hex digit to value.
  1296. static int UnHex(int c) {
  1297. if ('0' <= c && c <= '9')
  1298. return c - '0';
  1299. if ('A' <= c && c <= 'F')
  1300. return c - 'A' + 10;
  1301. if ('a' <= c && c <= 'f')
  1302. return c - 'a' + 10;
  1303. LOG(DFATAL) << "Bad hex digit " << c;
  1304. return 0;
  1305. }
  1306. // Parse an escape sequence (e.g., \n, \{).
  1307. // Sets *s to span the remainder of the string.
  1308. // Sets *rp to the named character.
  1309. static bool ParseEscape(StringPiece* s, Rune* rp,
  1310. RegexpStatus* status, int rune_max) {
  1311. const char* begin = s->data();
  1312. if (s->empty() || (*s)[0] != '\\') {
  1313. // Should not happen - caller always checks.
  1314. status->set_code(kRegexpInternalError);
  1315. status->set_error_arg(StringPiece());
  1316. return false;
  1317. }
  1318. if (s->size() == 1) {
  1319. status->set_code(kRegexpTrailingBackslash);
  1320. status->set_error_arg(StringPiece());
  1321. return false;
  1322. }
  1323. Rune c, c1;
  1324. s->remove_prefix(1); // backslash
  1325. if (StringPieceToRune(&c, s, status) < 0)
  1326. return false;
  1327. int code;
  1328. switch (c) {
  1329. default:
  1330. if (c < Runeself && !isalpha(c) && !isdigit(c)) {
  1331. // Escaped non-word characters are always themselves.
  1332. // PCRE is not quite so rigorous: it accepts things like
  1333. // \q, but we don't. We once rejected \_, but too many
  1334. // programs and people insist on using it, so allow \_.
  1335. *rp = c;
  1336. return true;
  1337. }
  1338. goto BadEscape;
  1339. // Octal escapes.
  1340. case '1':
  1341. case '2':
  1342. case '3':
  1343. case '4':
  1344. case '5':
  1345. case '6':
  1346. case '7':
  1347. // Single non-zero octal digit is a backreference; not supported.
  1348. if (s->empty() || (*s)[0] < '0' || (*s)[0] > '7')
  1349. goto BadEscape;
  1350. FALLTHROUGH_INTENDED;
  1351. case '0':
  1352. // consume up to three octal digits; already have one.
  1353. code = c - '0';
  1354. if (!s->empty() && '0' <= (c = (*s)[0]) && c <= '7') {
  1355. code = code * 8 + c - '0';
  1356. s->remove_prefix(1); // digit
  1357. if (!s->empty()) {
  1358. c = (*s)[0];
  1359. if ('0' <= c && c <= '7') {
  1360. code = code * 8 + c - '0';
  1361. s->remove_prefix(1); // digit
  1362. }
  1363. }
  1364. }
  1365. if (code > rune_max)
  1366. goto BadEscape;
  1367. *rp = code;
  1368. return true;
  1369. // Hexadecimal escapes
  1370. case 'x':
  1371. if (s->empty())
  1372. goto BadEscape;
  1373. if (StringPieceToRune(&c, s, status) < 0)
  1374. return false;
  1375. if (c == '{') {
  1376. // Any number of digits in braces.
  1377. // Update n as we consume the string, so that
  1378. // the whole thing gets shown in the error message.
  1379. // Perl accepts any text at all; it ignores all text
  1380. // after the first non-hex digit. We require only hex digits,
  1381. // and at least one.
  1382. if (StringPieceToRune(&c, s, status) < 0)
  1383. return false;
  1384. int nhex = 0;
  1385. code = 0;
  1386. while (IsHex(c)) {
  1387. nhex++;
  1388. code = code * 16 + UnHex(c);
  1389. if (code > rune_max)
  1390. goto BadEscape;
  1391. if (s->empty())
  1392. goto BadEscape;
  1393. if (StringPieceToRune(&c, s, status) < 0)
  1394. return false;
  1395. }
  1396. if (c != '}' || nhex == 0)
  1397. goto BadEscape;
  1398. *rp = code;
  1399. return true;
  1400. }
  1401. // Easy case: two hex digits.
  1402. if (s->empty())
  1403. goto BadEscape;
  1404. if (StringPieceToRune(&c1, s, status) < 0)
  1405. return false;
  1406. if (!IsHex(c) || !IsHex(c1))
  1407. goto BadEscape;
  1408. *rp = UnHex(c) * 16 + UnHex(c1);
  1409. return true;
  1410. // C escapes.
  1411. case 'n':
  1412. *rp = '\n';
  1413. return true;
  1414. case 'r':
  1415. *rp = '\r';
  1416. return true;
  1417. case 't':
  1418. *rp = '\t';
  1419. return true;
  1420. // Less common C escapes.
  1421. case 'a':
  1422. *rp = '\a';
  1423. return true;
  1424. case 'f':
  1425. *rp = '\f';
  1426. return true;
  1427. case 'v':
  1428. *rp = '\v';
  1429. return true;
  1430. // This code is disabled to avoid misparsing
  1431. // the Perl word-boundary \b as a backspace
  1432. // when in POSIX regexp mode. Surprisingly,
  1433. // in Perl, \b means word-boundary but [\b]
  1434. // means backspace. We don't support that:
  1435. // if you want a backspace embed a literal
  1436. // backspace character or use \x08.
  1437. //
  1438. // case 'b':
  1439. // *rp = '\b';
  1440. // return true;
  1441. }
  1442. LOG(DFATAL) << "Not reached in ParseEscape.";
  1443. BadEscape:
  1444. // Unrecognized escape sequence.
  1445. status->set_code(kRegexpBadEscape);
  1446. status->set_error_arg(
  1447. StringPiece(begin, static_cast<size_t>(s->data() - begin)));
  1448. return false;
  1449. }
  1450. // Add a range to the character class, but exclude newline if asked.
  1451. // Also handle case folding.
  1452. void CharClassBuilder::AddRangeFlags(
  1453. Rune lo, Rune hi, Regexp::ParseFlags parse_flags) {
  1454. // Take out \n if the flags say so.
  1455. bool cutnl = !(parse_flags & Regexp::ClassNL) ||
  1456. (parse_flags & Regexp::NeverNL);
  1457. if (cutnl && lo <= '\n' && '\n' <= hi) {
  1458. if (lo < '\n')
  1459. AddRangeFlags(lo, '\n' - 1, parse_flags);
  1460. if (hi > '\n')
  1461. AddRangeFlags('\n' + 1, hi, parse_flags);
  1462. return;
  1463. }
  1464. // If folding case, add fold-equivalent characters too.
  1465. if (parse_flags & Regexp::FoldCase)
  1466. AddFoldedRange(this, lo, hi, 0);
  1467. else
  1468. AddRange(lo, hi);
  1469. }
  1470. // Look for a group with the given name.
  1471. static const UGroup* LookupGroup(const StringPiece& name,
  1472. const UGroup *groups, int ngroups) {
  1473. // Simple name lookup.
  1474. for (int i = 0; i < ngroups; i++)
  1475. if (StringPiece(groups[i].name) == name)
  1476. return &groups[i];
  1477. return NULL;
  1478. }
  1479. // Look for a POSIX group with the given name (e.g., "[:^alpha:]")
  1480. static const UGroup* LookupPosixGroup(const StringPiece& name) {
  1481. return LookupGroup(name, posix_groups, num_posix_groups);
  1482. }
  1483. static const UGroup* LookupPerlGroup(const StringPiece& name) {
  1484. return LookupGroup(name, perl_groups, num_perl_groups);
  1485. }
  1486. #if !defined(RE2_USE_ICU)
  1487. // Fake UGroup containing all Runes
  1488. static URange16 any16[] = { { 0, 65535 } };
  1489. static URange32 any32[] = { { 65536, Runemax } };
  1490. static UGroup anygroup = { "Any", +1, any16, 1, any32, 1 };
  1491. // Look for a Unicode group with the given name (e.g., "Han")
  1492. static const UGroup* LookupUnicodeGroup(const StringPiece& name) {
  1493. // Special case: "Any" means any.
  1494. if (name == StringPiece("Any"))
  1495. return &anygroup;
  1496. return LookupGroup(name, unicode_groups, num_unicode_groups);
  1497. }
  1498. #endif
  1499. // Add a UGroup or its negation to the character class.
  1500. static void AddUGroup(CharClassBuilder *cc, const UGroup *g, int sign,
  1501. Regexp::ParseFlags parse_flags) {
  1502. if (sign == +1) {
  1503. for (int i = 0; i < g->nr16; i++) {
  1504. cc->AddRangeFlags(g->r16[i].lo, g->r16[i].hi, parse_flags);
  1505. }
  1506. for (int i = 0; i < g->nr32; i++) {
  1507. cc->AddRangeFlags(g->r32[i].lo, g->r32[i].hi, parse_flags);
  1508. }
  1509. } else {
  1510. if (parse_flags & Regexp::FoldCase) {
  1511. // Normally adding a case-folded group means
  1512. // adding all the extra fold-equivalent runes too.
  1513. // But if we're adding the negation of the group,
  1514. // we have to exclude all the runes that are fold-equivalent
  1515. // to what's already missing. Too hard, so do in two steps.
  1516. CharClassBuilder ccb1;
  1517. AddUGroup(&ccb1, g, +1, parse_flags);
  1518. // If the flags say to take out \n, put it in, so that negating will take it out.
  1519. // Normally AddRangeFlags does this, but we're bypassing AddRangeFlags.
  1520. bool cutnl = !(parse_flags & Regexp::ClassNL) ||
  1521. (parse_flags & Regexp::NeverNL);
  1522. if (cutnl) {
  1523. ccb1.AddRange('\n', '\n');
  1524. }
  1525. ccb1.Negate();
  1526. cc->AddCharClass(&ccb1);
  1527. return;
  1528. }
  1529. int next = 0;
  1530. for (int i = 0; i < g->nr16; i++) {
  1531. if (next < g->r16[i].lo)
  1532. cc->AddRangeFlags(next, g->r16[i].lo - 1, parse_flags);
  1533. next = g->r16[i].hi + 1;
  1534. }
  1535. for (int i = 0; i < g->nr32; i++) {
  1536. if (next < g->r32[i].lo)
  1537. cc->AddRangeFlags(next, g->r32[i].lo - 1, parse_flags);
  1538. next = g->r32[i].hi + 1;
  1539. }
  1540. if (next <= Runemax)
  1541. cc->AddRangeFlags(next, Runemax, parse_flags);
  1542. }
  1543. }
  1544. // Maybe parse a Perl character class escape sequence.
  1545. // Only recognizes the Perl character classes (\d \s \w \D \S \W),
  1546. // not the Perl empty-string classes (\b \B \A \Z \z).
  1547. // On success, sets *s to span the remainder of the string
  1548. // and returns the corresponding UGroup.
  1549. // The StringPiece must *NOT* be edited unless the call succeeds.
  1550. const UGroup* MaybeParsePerlCCEscape(StringPiece* s, Regexp::ParseFlags parse_flags) {
  1551. if (!(parse_flags & Regexp::PerlClasses))
  1552. return NULL;
  1553. if (s->size() < 2 || (*s)[0] != '\\')
  1554. return NULL;
  1555. // Could use StringPieceToRune, but there aren't
  1556. // any non-ASCII Perl group names.
  1557. StringPiece name(s->data(), 2);
  1558. const UGroup *g = LookupPerlGroup(name);
  1559. if (g == NULL)
  1560. return NULL;
  1561. s->remove_prefix(name.size());
  1562. return g;
  1563. }
  1564. enum ParseStatus {
  1565. kParseOk, // Did some parsing.
  1566. kParseError, // Found an error.
  1567. kParseNothing, // Decided not to parse.
  1568. };
  1569. // Maybe parses a Unicode character group like \p{Han} or \P{Han}
  1570. // (the latter is a negated group).
  1571. ParseStatus ParseUnicodeGroup(StringPiece* s, Regexp::ParseFlags parse_flags,
  1572. CharClassBuilder *cc,
  1573. RegexpStatus* status) {
  1574. // Decide whether to parse.
  1575. if (!(parse_flags & Regexp::UnicodeGroups))
  1576. return kParseNothing;
  1577. if (s->size() < 2 || (*s)[0] != '\\')
  1578. return kParseNothing;
  1579. Rune c = (*s)[1];
  1580. if (c != 'p' && c != 'P')
  1581. return kParseNothing;
  1582. // Committed to parse. Results:
  1583. int sign = +1; // -1 = negated char class
  1584. if (c == 'P')
  1585. sign = -sign;
  1586. StringPiece seq = *s; // \p{Han} or \pL
  1587. StringPiece name; // Han or L
  1588. s->remove_prefix(2); // '\\', 'p'
  1589. if (!StringPieceToRune(&c, s, status))
  1590. return kParseError;
  1591. if (c != '{') {
  1592. // Name is the bit of string we just skipped over for c.
  1593. const char* p = seq.data() + 2;
  1594. name = StringPiece(p, static_cast<size_t>(s->data() - p));
  1595. } else {
  1596. // Name is in braces. Look for closing }
  1597. size_t end = s->find('}', 0);
  1598. if (end == StringPiece::npos) {
  1599. if (!IsValidUTF8(seq, status))
  1600. return kParseError;
  1601. status->set_code(kRegexpBadCharRange);
  1602. status->set_error_arg(seq);
  1603. return kParseError;
  1604. }
  1605. name = StringPiece(s->data(), end); // without '}'
  1606. s->remove_prefix(end + 1); // with '}'
  1607. if (!IsValidUTF8(name, status))
  1608. return kParseError;
  1609. }
  1610. // Chop seq where s now begins.
  1611. seq = StringPiece(seq.data(), static_cast<size_t>(s->data() - seq.data()));
  1612. if (!name.empty() && name[0] == '^') {
  1613. sign = -sign;
  1614. name.remove_prefix(1); // '^'
  1615. }
  1616. #if !defined(RE2_USE_ICU)
  1617. // Look up the group in the RE2 Unicode data.
  1618. const UGroup *g = LookupUnicodeGroup(name);
  1619. if (g == NULL) {
  1620. status->set_code(kRegexpBadCharRange);
  1621. status->set_error_arg(seq);
  1622. return kParseError;
  1623. }
  1624. AddUGroup(cc, g, sign, parse_flags);
  1625. #else
  1626. // Look up the group in the ICU Unicode data. Because ICU provides full
  1627. // Unicode properties support, this could be more than a lookup by name.
  1628. ::icu::UnicodeString ustr = ::icu::UnicodeString::fromUTF8(
  1629. std::string("\\p{") + std::string(name) + std::string("}"));
  1630. UErrorCode uerr = U_ZERO_ERROR;
  1631. ::icu::UnicodeSet uset(ustr, uerr);
  1632. if (U_FAILURE(uerr)) {
  1633. status->set_code(kRegexpBadCharRange);
  1634. status->set_error_arg(seq);
  1635. return kParseError;
  1636. }
  1637. // Convert the UnicodeSet to a URange32 and UGroup that we can add.
  1638. int nr = uset.getRangeCount();
  1639. PODArray<URange32> r(nr);
  1640. for (int i = 0; i < nr; i++) {
  1641. r[i].lo = uset.getRangeStart(i);
  1642. r[i].hi = uset.getRangeEnd(i);
  1643. }
  1644. UGroup g = {"", +1, 0, 0, r.data(), nr};
  1645. AddUGroup(cc, &g, sign, parse_flags);
  1646. #endif
  1647. return kParseOk;
  1648. }
  1649. // Parses a character class name like [:alnum:].
  1650. // Sets *s to span the remainder of the string.
  1651. // Adds the ranges corresponding to the class to ranges.
  1652. static ParseStatus ParseCCName(StringPiece* s, Regexp::ParseFlags parse_flags,
  1653. CharClassBuilder *cc,
  1654. RegexpStatus* status) {
  1655. // Check begins with [:
  1656. const char* p = s->data();
  1657. const char* ep = s->data() + s->size();
  1658. if (ep - p < 2 || p[0] != '[' || p[1] != ':')
  1659. return kParseNothing;
  1660. // Look for closing :].
  1661. const char* q;
  1662. for (q = p+2; q <= ep-2 && (*q != ':' || *(q+1) != ']'); q++)
  1663. ;
  1664. // If no closing :], then ignore.
  1665. if (q > ep-2)
  1666. return kParseNothing;
  1667. // Got it. Check that it's valid.
  1668. q += 2;
  1669. StringPiece name(p, static_cast<size_t>(q - p));
  1670. const UGroup *g = LookupPosixGroup(name);
  1671. if (g == NULL) {
  1672. status->set_code(kRegexpBadCharRange);
  1673. status->set_error_arg(name);
  1674. return kParseError;
  1675. }
  1676. s->remove_prefix(name.size());
  1677. AddUGroup(cc, g, g->sign, parse_flags);
  1678. return kParseOk;
  1679. }
  1680. // Parses a character inside a character class.
  1681. // There are fewer special characters here than in the rest of the regexp.
  1682. // Sets *s to span the remainder of the string.
  1683. // Sets *rp to the character.
  1684. bool Regexp::ParseState::ParseCCCharacter(StringPiece* s, Rune *rp,
  1685. const StringPiece& whole_class,
  1686. RegexpStatus* status) {
  1687. if (s->empty()) {
  1688. status->set_code(kRegexpMissingBracket);
  1689. status->set_error_arg(whole_class);
  1690. return false;
  1691. }
  1692. // Allow regular escape sequences even though
  1693. // many need not be escaped in this context.
  1694. if ((*s)[0] == '\\')
  1695. return ParseEscape(s, rp, status, rune_max_);
  1696. // Otherwise take the next rune.
  1697. return StringPieceToRune(rp, s, status) >= 0;
  1698. }
  1699. // Parses a character class character, or, if the character
  1700. // is followed by a hyphen, parses a character class range.
  1701. // For single characters, rr->lo == rr->hi.
  1702. // Sets *s to span the remainder of the string.
  1703. // Sets *rp to the character.
  1704. bool Regexp::ParseState::ParseCCRange(StringPiece* s, RuneRange* rr,
  1705. const StringPiece& whole_class,
  1706. RegexpStatus* status) {
  1707. StringPiece os = *s;
  1708. if (!ParseCCCharacter(s, &rr->lo, whole_class, status))
  1709. return false;
  1710. // [a-] means (a|-), so check for final ].
  1711. if (s->size() >= 2 && (*s)[0] == '-' && (*s)[1] != ']') {
  1712. s->remove_prefix(1); // '-'
  1713. if (!ParseCCCharacter(s, &rr->hi, whole_class, status))
  1714. return false;
  1715. if (rr->hi < rr->lo) {
  1716. status->set_code(kRegexpBadCharRange);
  1717. status->set_error_arg(
  1718. StringPiece(os.data(), static_cast<size_t>(s->data() - os.data())));
  1719. return false;
  1720. }
  1721. } else {
  1722. rr->hi = rr->lo;
  1723. }
  1724. return true;
  1725. }
  1726. // Parses a possibly-negated character class expression like [^abx-z[:digit:]].
  1727. // Sets *s to span the remainder of the string.
  1728. // Sets *out_re to the regexp for the class.
  1729. bool Regexp::ParseState::ParseCharClass(StringPiece* s,
  1730. Regexp** out_re,
  1731. RegexpStatus* status) {
  1732. StringPiece whole_class = *s;
  1733. if (s->empty() || (*s)[0] != '[') {
  1734. // Caller checked this.
  1735. status->set_code(kRegexpInternalError);
  1736. status->set_error_arg(StringPiece());
  1737. return false;
  1738. }
  1739. bool negated = false;
  1740. Regexp* re = new Regexp(kRegexpCharClass, flags_ & ~FoldCase);
  1741. re->ccb_ = new CharClassBuilder;
  1742. s->remove_prefix(1); // '['
  1743. if (!s->empty() && (*s)[0] == '^') {
  1744. s->remove_prefix(1); // '^'
  1745. negated = true;
  1746. if (!(flags_ & ClassNL) || (flags_ & NeverNL)) {
  1747. // If NL can't match implicitly, then pretend
  1748. // negated classes include a leading \n.
  1749. re->ccb_->AddRange('\n', '\n');
  1750. }
  1751. }
  1752. bool first = true; // ] is okay as first char in class
  1753. while (!s->empty() && ((*s)[0] != ']' || first)) {
  1754. // - is only okay unescaped as first or last in class.
  1755. // Except that Perl allows - anywhere.
  1756. if ((*s)[0] == '-' && !first && !(flags_&PerlX) &&
  1757. (s->size() == 1 || (*s)[1] != ']')) {
  1758. StringPiece t = *s;
  1759. t.remove_prefix(1); // '-'
  1760. Rune r;
  1761. int n = StringPieceToRune(&r, &t, status);
  1762. if (n < 0) {
  1763. re->Decref();
  1764. return false;
  1765. }
  1766. status->set_code(kRegexpBadCharRange);
  1767. status->set_error_arg(StringPiece(s->data(), 1+n));
  1768. re->Decref();
  1769. return false;
  1770. }
  1771. first = false;
  1772. // Look for [:alnum:] etc.
  1773. if (s->size() > 2 && (*s)[0] == '[' && (*s)[1] == ':') {
  1774. switch (ParseCCName(s, flags_, re->ccb_, status)) {
  1775. case kParseOk:
  1776. continue;
  1777. case kParseError:
  1778. re->Decref();
  1779. return false;
  1780. case kParseNothing:
  1781. break;
  1782. }
  1783. }
  1784. // Look for Unicode character group like \p{Han}
  1785. if (s->size() > 2 &&
  1786. (*s)[0] == '\\' &&
  1787. ((*s)[1] == 'p' || (*s)[1] == 'P')) {
  1788. switch (ParseUnicodeGroup(s, flags_, re->ccb_, status)) {
  1789. case kParseOk:
  1790. continue;
  1791. case kParseError:
  1792. re->Decref();
  1793. return false;
  1794. case kParseNothing:
  1795. break;
  1796. }
  1797. }
  1798. // Look for Perl character class symbols (extension).
  1799. const UGroup *g = MaybeParsePerlCCEscape(s, flags_);
  1800. if (g != NULL) {
  1801. AddUGroup(re->ccb_, g, g->sign, flags_);
  1802. continue;
  1803. }
  1804. // Otherwise assume single character or simple range.
  1805. RuneRange rr;
  1806. if (!ParseCCRange(s, &rr, whole_class, status)) {
  1807. re->Decref();
  1808. return false;
  1809. }
  1810. // AddRangeFlags is usually called in response to a class like
  1811. // \p{Foo} or [[:foo:]]; for those, it filters \n out unless
  1812. // Regexp::ClassNL is set. In an explicit range or singleton
  1813. // like we just parsed, we do not filter \n out, so set ClassNL
  1814. // in the flags.
  1815. re->ccb_->AddRangeFlags(rr.lo, rr.hi, flags_ | Regexp::ClassNL);
  1816. }
  1817. if (s->empty()) {
  1818. status->set_code(kRegexpMissingBracket);
  1819. status->set_error_arg(whole_class);
  1820. re->Decref();
  1821. return false;
  1822. }
  1823. s->remove_prefix(1); // ']'
  1824. if (negated)
  1825. re->ccb_->Negate();
  1826. *out_re = re;
  1827. return true;
  1828. }
  1829. // Returns whether name is a valid capture name.
  1830. static bool IsValidCaptureName(const StringPiece& name) {
  1831. if (name.empty())
  1832. return false;
  1833. // Historically, we effectively used [0-9A-Za-z_]+ to validate; that
  1834. // followed Python 2 except for not restricting the first character.
  1835. // As of Python 3, Unicode characters beyond ASCII are also allowed;
  1836. // accordingly, we permit the Lu, Ll, Lt, Lm, Lo, Nl, Mn, Mc, Nd and
  1837. // Pc categories, but again without restricting the first character.
  1838. // Also, Unicode normalization (e.g. NFKC) isn't performed: Python 3
  1839. // performs it for identifiers, but seemingly not for capture names;
  1840. // if they start doing that for capture names, we won't follow suit.
  1841. static const CharClass* const cc = []() {
  1842. CharClassBuilder ccb;
  1843. for (StringPiece group :
  1844. {"Lu", "Ll", "Lt", "Lm", "Lo", "Nl", "Mn", "Mc", "Nd", "Pc"})
  1845. AddUGroup(&ccb, LookupGroup(group, unicode_groups, num_unicode_groups),
  1846. +1, Regexp::NoParseFlags);
  1847. return ccb.GetCharClass();
  1848. }();
  1849. StringPiece t = name;
  1850. Rune r;
  1851. while (!t.empty()) {
  1852. if (StringPieceToRune(&r, &t, NULL) < 0)
  1853. return false;
  1854. if (cc->Contains(r))
  1855. continue;
  1856. return false;
  1857. }
  1858. return true;
  1859. }
  1860. // Parses a Perl flag setting or non-capturing group or both,
  1861. // like (?i) or (?: or (?i:. Removes from s, updates parse state.
  1862. // The caller must check that s begins with "(?".
  1863. // Returns true on success. If the Perl flag is not
  1864. // well-formed or not supported, sets status_ and returns false.
  1865. bool Regexp::ParseState::ParsePerlFlags(StringPiece* s) {
  1866. StringPiece t = *s;
  1867. // Caller is supposed to check this.
  1868. if (!(flags_ & PerlX) || t.size() < 2 || t[0] != '(' || t[1] != '?') {
  1869. LOG(DFATAL) << "Bad call to ParseState::ParsePerlFlags";
  1870. status_->set_code(kRegexpInternalError);
  1871. return false;
  1872. }
  1873. t.remove_prefix(2); // "(?"
  1874. // Check for named captures, first introduced in Python's regexp library.
  1875. // As usual, there are three slightly different syntaxes:
  1876. //
  1877. // (?P<name>expr) the original, introduced by Python
  1878. // (?<name>expr) the .NET alteration, adopted by Perl 5.10
  1879. // (?'name'expr) another .NET alteration, adopted by Perl 5.10
  1880. //
  1881. // Perl 5.10 gave in and implemented the Python version too,
  1882. // but they claim that the last two are the preferred forms.
  1883. // PCRE and languages based on it (specifically, PHP and Ruby)
  1884. // support all three as well. EcmaScript 4 uses only the Python form.
  1885. //
  1886. // In both the open source world (via Code Search) and the
  1887. // Google source tree, (?P<expr>name) is the dominant form,
  1888. // so that's the one we implement. One is enough.
  1889. if (t.size() > 2 && t[0] == 'P' && t[1] == '<') {
  1890. // Pull out name.
  1891. size_t end = t.find('>', 2);
  1892. if (end == StringPiece::npos) {
  1893. if (!IsValidUTF8(*s, status_))
  1894. return false;
  1895. status_->set_code(kRegexpBadNamedCapture);
  1896. status_->set_error_arg(*s);
  1897. return false;
  1898. }
  1899. // t is "P<name>...", t[end] == '>'
  1900. StringPiece capture(t.data()-2, end+3); // "(?P<name>"
  1901. StringPiece name(t.data()+2, end-2); // "name"
  1902. if (!IsValidUTF8(name, status_))
  1903. return false;
  1904. if (!IsValidCaptureName(name)) {
  1905. status_->set_code(kRegexpBadNamedCapture);
  1906. status_->set_error_arg(capture);
  1907. return false;
  1908. }
  1909. if (!DoLeftParen(name)) {
  1910. // DoLeftParen's failure set status_.
  1911. return false;
  1912. }
  1913. s->remove_prefix(
  1914. static_cast<size_t>(capture.data() + capture.size() - s->data()));
  1915. return true;
  1916. }
  1917. bool negated = false;
  1918. bool sawflags = false;
  1919. int nflags = flags_;
  1920. Rune c;
  1921. for (bool done = false; !done; ) {
  1922. if (t.empty())
  1923. goto BadPerlOp;
  1924. if (StringPieceToRune(&c, &t, status_) < 0)
  1925. return false;
  1926. switch (c) {
  1927. default:
  1928. goto BadPerlOp;
  1929. // Parse flags.
  1930. case 'i':
  1931. sawflags = true;
  1932. if (negated)
  1933. nflags &= ~FoldCase;
  1934. else
  1935. nflags |= FoldCase;
  1936. break;
  1937. case 'm': // opposite of our OneLine
  1938. sawflags = true;
  1939. if (negated)
  1940. nflags |= OneLine;
  1941. else
  1942. nflags &= ~OneLine;
  1943. break;
  1944. case 's':
  1945. sawflags = true;
  1946. if (negated)
  1947. nflags &= ~DotNL;
  1948. else
  1949. nflags |= DotNL;
  1950. break;
  1951. case 'U':
  1952. sawflags = true;
  1953. if (negated)
  1954. nflags &= ~NonGreedy;
  1955. else
  1956. nflags |= NonGreedy;
  1957. break;
  1958. // Negation
  1959. case '-':
  1960. if (negated)
  1961. goto BadPerlOp;
  1962. negated = true;
  1963. sawflags = false;
  1964. break;
  1965. // Open new group.
  1966. case ':':
  1967. if (!DoLeftParenNoCapture()) {
  1968. // DoLeftParenNoCapture's failure set status_.
  1969. return false;
  1970. }
  1971. done = true;
  1972. break;
  1973. // Finish flags.
  1974. case ')':
  1975. done = true;
  1976. break;
  1977. }
  1978. }
  1979. if (negated && !sawflags)
  1980. goto BadPerlOp;
  1981. flags_ = static_cast<Regexp::ParseFlags>(nflags);
  1982. *s = t;
  1983. return true;
  1984. BadPerlOp:
  1985. status_->set_code(kRegexpBadPerlOp);
  1986. status_->set_error_arg(
  1987. StringPiece(s->data(), static_cast<size_t>(t.data() - s->data())));
  1988. return false;
  1989. }
  1990. // Converts latin1 (assumed to be encoded as Latin1 bytes)
  1991. // into UTF8 encoding in string.
  1992. // Can't use EncodingUtils::EncodeLatin1AsUTF8 because it is
  1993. // deprecated and because it rejects code points 0x80-0x9F.
  1994. void ConvertLatin1ToUTF8(const StringPiece& latin1, std::string* utf) {
  1995. char buf[UTFmax];
  1996. utf->clear();
  1997. for (size_t i = 0; i < latin1.size(); i++) {
  1998. Rune r = latin1[i] & 0xFF;
  1999. int n = runetochar(buf, &r);
  2000. utf->append(buf, n);
  2001. }
  2002. }
  2003. // Parses the regular expression given by s,
  2004. // returning the corresponding Regexp tree.
  2005. // The caller must Decref the return value when done with it.
  2006. // Returns NULL on error.
  2007. Regexp* Regexp::Parse(const StringPiece& s, ParseFlags global_flags,
  2008. RegexpStatus* status) {
  2009. // Make status non-NULL (easier on everyone else).
  2010. RegexpStatus xstatus;
  2011. if (status == NULL)
  2012. status = &xstatus;
  2013. ParseState ps(global_flags, s, status);
  2014. StringPiece t = s;
  2015. // Convert regexp to UTF-8 (easier on the rest of the parser).
  2016. if (global_flags & Latin1) {
  2017. std::string* tmp = new std::string;
  2018. ConvertLatin1ToUTF8(t, tmp);
  2019. status->set_tmp(tmp);
  2020. t = *tmp;
  2021. }
  2022. if (global_flags & Literal) {
  2023. // Special parse loop for literal string.
  2024. while (!t.empty()) {
  2025. Rune r;
  2026. if (StringPieceToRune(&r, &t, status) < 0)
  2027. return NULL;
  2028. if (!ps.PushLiteral(r))
  2029. return NULL;
  2030. }
  2031. return ps.DoFinish();
  2032. }
  2033. StringPiece lastunary = StringPiece();
  2034. while (!t.empty()) {
  2035. StringPiece isunary = StringPiece();
  2036. switch (t[0]) {
  2037. default: {
  2038. Rune r;
  2039. if (StringPieceToRune(&r, &t, status) < 0)
  2040. return NULL;
  2041. if (!ps.PushLiteral(r))
  2042. return NULL;
  2043. break;
  2044. }
  2045. case '(':
  2046. // "(?" introduces Perl escape.
  2047. if ((ps.flags() & PerlX) && (t.size() >= 2 && t[1] == '?')) {
  2048. // Flag changes and non-capturing groups.
  2049. if (!ps.ParsePerlFlags(&t))
  2050. return NULL;
  2051. break;
  2052. }
  2053. if (ps.flags() & NeverCapture) {
  2054. if (!ps.DoLeftParenNoCapture())
  2055. return NULL;
  2056. } else {
  2057. if (!ps.DoLeftParen(StringPiece()))
  2058. return NULL;
  2059. }
  2060. t.remove_prefix(1); // '('
  2061. break;
  2062. case '|':
  2063. if (!ps.DoVerticalBar())
  2064. return NULL;
  2065. t.remove_prefix(1); // '|'
  2066. break;
  2067. case ')':
  2068. if (!ps.DoRightParen())
  2069. return NULL;
  2070. t.remove_prefix(1); // ')'
  2071. break;
  2072. case '^': // Beginning of line.
  2073. if (!ps.PushCaret())
  2074. return NULL;
  2075. t.remove_prefix(1); // '^'
  2076. break;
  2077. case '$': // End of line.
  2078. if (!ps.PushDollar())
  2079. return NULL;
  2080. t.remove_prefix(1); // '$'
  2081. break;
  2082. case '.': // Any character (possibly except newline).
  2083. if (!ps.PushDot())
  2084. return NULL;
  2085. t.remove_prefix(1); // '.'
  2086. break;
  2087. case '[': { // Character class.
  2088. Regexp* re;
  2089. if (!ps.ParseCharClass(&t, &re, status))
  2090. return NULL;
  2091. if (!ps.PushRegexp(re))
  2092. return NULL;
  2093. break;
  2094. }
  2095. case '*': { // Zero or more.
  2096. RegexpOp op;
  2097. op = kRegexpStar;
  2098. goto Rep;
  2099. case '+': // One or more.
  2100. op = kRegexpPlus;
  2101. goto Rep;
  2102. case '?': // Zero or one.
  2103. op = kRegexpQuest;
  2104. goto Rep;
  2105. Rep:
  2106. StringPiece opstr = t;
  2107. bool nongreedy = false;
  2108. t.remove_prefix(1); // '*' or '+' or '?'
  2109. if (ps.flags() & PerlX) {
  2110. if (!t.empty() && t[0] == '?') {
  2111. nongreedy = true;
  2112. t.remove_prefix(1); // '?'
  2113. }
  2114. if (!lastunary.empty()) {
  2115. // In Perl it is not allowed to stack repetition operators:
  2116. // a** is a syntax error, not a double-star.
  2117. // (and a++ means something else entirely, which we don't support!)
  2118. status->set_code(kRegexpRepeatOp);
  2119. status->set_error_arg(StringPiece(
  2120. lastunary.data(),
  2121. static_cast<size_t>(t.data() - lastunary.data())));
  2122. return NULL;
  2123. }
  2124. }
  2125. opstr = StringPiece(opstr.data(),
  2126. static_cast<size_t>(t.data() - opstr.data()));
  2127. if (!ps.PushRepeatOp(op, opstr, nongreedy))
  2128. return NULL;
  2129. isunary = opstr;
  2130. break;
  2131. }
  2132. case '{': { // Counted repetition.
  2133. int lo, hi;
  2134. StringPiece opstr = t;
  2135. if (!MaybeParseRepetition(&t, &lo, &hi)) {
  2136. // Treat like a literal.
  2137. if (!ps.PushLiteral('{'))
  2138. return NULL;
  2139. t.remove_prefix(1); // '{'
  2140. break;
  2141. }
  2142. bool nongreedy = false;
  2143. if (ps.flags() & PerlX) {
  2144. if (!t.empty() && t[0] == '?') {
  2145. nongreedy = true;
  2146. t.remove_prefix(1); // '?'
  2147. }
  2148. if (!lastunary.empty()) {
  2149. // Not allowed to stack repetition operators.
  2150. status->set_code(kRegexpRepeatOp);
  2151. status->set_error_arg(StringPiece(
  2152. lastunary.data(),
  2153. static_cast<size_t>(t.data() - lastunary.data())));
  2154. return NULL;
  2155. }
  2156. }
  2157. opstr = StringPiece(opstr.data(),
  2158. static_cast<size_t>(t.data() - opstr.data()));
  2159. if (!ps.PushRepetition(lo, hi, opstr, nongreedy))
  2160. return NULL;
  2161. isunary = opstr;
  2162. break;
  2163. }
  2164. case '\\': { // Escaped character or Perl sequence.
  2165. // \b and \B: word boundary or not
  2166. if ((ps.flags() & Regexp::PerlB) &&
  2167. t.size() >= 2 && (t[1] == 'b' || t[1] == 'B')) {
  2168. if (!ps.PushWordBoundary(t[1] == 'b'))
  2169. return NULL;
  2170. t.remove_prefix(2); // '\\', 'b'
  2171. break;
  2172. }
  2173. if ((ps.flags() & Regexp::PerlX) && t.size() >= 2) {
  2174. if (t[1] == 'A') {
  2175. if (!ps.PushSimpleOp(kRegexpBeginText))
  2176. return NULL;
  2177. t.remove_prefix(2); // '\\', 'A'
  2178. break;
  2179. }
  2180. if (t[1] == 'z') {
  2181. if (!ps.PushSimpleOp(kRegexpEndText))
  2182. return NULL;
  2183. t.remove_prefix(2); // '\\', 'z'
  2184. break;
  2185. }
  2186. // Do not recognize \Z, because this library can't
  2187. // implement the exact Perl/PCRE semantics.
  2188. // (This library treats "(?-m)$" as \z, even though
  2189. // in Perl and PCRE it is equivalent to \Z.)
  2190. if (t[1] == 'C') { // \C: any byte [sic]
  2191. if (!ps.PushSimpleOp(kRegexpAnyByte))
  2192. return NULL;
  2193. t.remove_prefix(2); // '\\', 'C'
  2194. break;
  2195. }
  2196. if (t[1] == 'Q') { // \Q ... \E: the ... is always literals
  2197. t.remove_prefix(2); // '\\', 'Q'
  2198. while (!t.empty()) {
  2199. if (t.size() >= 2 && t[0] == '\\' && t[1] == 'E') {
  2200. t.remove_prefix(2); // '\\', 'E'
  2201. break;
  2202. }
  2203. Rune r;
  2204. if (StringPieceToRune(&r, &t, status) < 0)
  2205. return NULL;
  2206. if (!ps.PushLiteral(r))
  2207. return NULL;
  2208. }
  2209. break;
  2210. }
  2211. }
  2212. if (t.size() >= 2 && (t[1] == 'p' || t[1] == 'P')) {
  2213. Regexp* re = new Regexp(kRegexpCharClass, ps.flags() & ~FoldCase);
  2214. re->ccb_ = new CharClassBuilder;
  2215. switch (ParseUnicodeGroup(&t, ps.flags(), re->ccb_, status)) {
  2216. case kParseOk:
  2217. if (!ps.PushRegexp(re))
  2218. return NULL;
  2219. goto Break2;
  2220. case kParseError:
  2221. re->Decref();
  2222. return NULL;
  2223. case kParseNothing:
  2224. re->Decref();
  2225. break;
  2226. }
  2227. }
  2228. const UGroup *g = MaybeParsePerlCCEscape(&t, ps.flags());
  2229. if (g != NULL) {
  2230. Regexp* re = new Regexp(kRegexpCharClass, ps.flags() & ~FoldCase);
  2231. re->ccb_ = new CharClassBuilder;
  2232. AddUGroup(re->ccb_, g, g->sign, ps.flags());
  2233. if (!ps.PushRegexp(re))
  2234. return NULL;
  2235. break;
  2236. }
  2237. Rune r;
  2238. if (!ParseEscape(&t, &r, status, ps.rune_max()))
  2239. return NULL;
  2240. if (!ps.PushLiteral(r))
  2241. return NULL;
  2242. break;
  2243. }
  2244. }
  2245. Break2:
  2246. lastunary = isunary;
  2247. }
  2248. return ps.DoFinish();
  2249. }
  2250. } // namespace re2