parse.cc 77 KB

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