sre.c 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374
  1. /*
  2. * Secret Labs' Regular Expression Engine
  3. *
  4. * regular expression matching engine
  5. *
  6. * partial history:
  7. * 1999-10-24 fl created (based on existing template matcher code)
  8. * 2000-03-06 fl first alpha, sort of
  9. * 2000-08-01 fl fixes for 1.6b1
  10. * 2000-08-07 fl use PyOS_CheckStack() if available
  11. * 2000-09-20 fl added expand method
  12. * 2001-03-20 fl lots of fixes for 2.1b2
  13. * 2001-04-15 fl export copyright as Python attribute, not global
  14. * 2001-04-28 fl added __copy__ methods (work in progress)
  15. * 2001-05-14 fl fixes for 1.5.2 compatibility
  16. * 2001-07-01 fl added BIGCHARSET support (from Martin von Loewis)
  17. * 2001-10-18 fl fixed group reset issue (from Matthew Mueller)
  18. * 2001-10-20 fl added split primitive; re-enable unicode for 1.6/2.0/2.1
  19. * 2001-10-21 fl added sub/subn primitive
  20. * 2001-10-24 fl added finditer primitive (for 2.2 only)
  21. * 2001-12-07 fl fixed memory leak in sub/subn (Guido van Rossum)
  22. * 2002-11-09 fl fixed empty sub/subn return type
  23. * 2003-04-18 mvl fully support 4-byte codes
  24. * 2003-10-17 gn implemented non recursive scheme
  25. * 2013-02-04 mrab added fullmatch primitive
  26. *
  27. * Copyright (c) 1997-2001 by Secret Labs AB. All rights reserved.
  28. *
  29. * This version of the SRE library can be redistributed under CNRI's
  30. * Python 1.6 license. For any other use, please contact Secret Labs
  31. * AB (info@pythonware.com).
  32. *
  33. * Portions of this engine have been developed in cooperation with
  34. * CNRI. Hewlett-Packard provided funding for 1.6 integration and
  35. * other compatibility work.
  36. */
  37. static const char copyright[] =
  38. " SRE 2.2.2 Copyright (c) 1997-2002 by Secret Labs AB ";
  39. #define PY_SSIZE_T_CLEAN
  40. #include "Python.h"
  41. #include "pycore_long.h" // _PyLong_GetZero()
  42. #include "pycore_moduleobject.h" // _PyModule_GetState()
  43. #include "structmember.h" // PyMemberDef
  44. #include "sre.h"
  45. #define SRE_CODE_BITS (8 * sizeof(SRE_CODE))
  46. #include <ctype.h>
  47. /* defining this one enables tracing */
  48. #undef VERBOSE
  49. /* -------------------------------------------------------------------- */
  50. #if defined(_MSC_VER)
  51. #pragma optimize("agtw", on) /* doesn't seem to make much difference... */
  52. #pragma warning(disable: 4710) /* who cares if functions are not inlined ;-) */
  53. /* fastest possible local call under MSVC */
  54. #define LOCAL(type) static __inline type __fastcall
  55. #else
  56. #define LOCAL(type) static inline type
  57. #endif
  58. /* error codes */
  59. #define SRE_ERROR_ILLEGAL -1 /* illegal opcode */
  60. #define SRE_ERROR_STATE -2 /* illegal state */
  61. #define SRE_ERROR_RECURSION_LIMIT -3 /* runaway recursion */
  62. #define SRE_ERROR_MEMORY -9 /* out of memory */
  63. #define SRE_ERROR_INTERRUPTED -10 /* signal handler raised exception */
  64. #if defined(VERBOSE)
  65. #define TRACE(v) printf v
  66. #else
  67. #define TRACE(v)
  68. #endif
  69. /* -------------------------------------------------------------------- */
  70. /* search engine state */
  71. #define SRE_IS_DIGIT(ch)\
  72. ((ch) <= '9' && Py_ISDIGIT(ch))
  73. #define SRE_IS_SPACE(ch)\
  74. ((ch) <= ' ' && Py_ISSPACE(ch))
  75. #define SRE_IS_LINEBREAK(ch)\
  76. ((ch) == '\n')
  77. #define SRE_IS_WORD(ch)\
  78. ((ch) <= 'z' && (Py_ISALNUM(ch) || (ch) == '_'))
  79. static unsigned int sre_lower_ascii(unsigned int ch)
  80. {
  81. return ((ch) < 128 ? Py_TOLOWER(ch) : ch);
  82. }
  83. /* locale-specific character predicates */
  84. /* !(c & ~N) == (c < N+1) for any unsigned c, this avoids
  85. * warnings when c's type supports only numbers < N+1 */
  86. #define SRE_LOC_IS_ALNUM(ch) (!((ch) & ~255) ? isalnum((ch)) : 0)
  87. #define SRE_LOC_IS_WORD(ch) (SRE_LOC_IS_ALNUM((ch)) || (ch) == '_')
  88. static unsigned int sre_lower_locale(unsigned int ch)
  89. {
  90. return ((ch) < 256 ? (unsigned int)tolower((ch)) : ch);
  91. }
  92. static unsigned int sre_upper_locale(unsigned int ch)
  93. {
  94. return ((ch) < 256 ? (unsigned int)toupper((ch)) : ch);
  95. }
  96. /* unicode-specific character predicates */
  97. #define SRE_UNI_IS_DIGIT(ch) Py_UNICODE_ISDECIMAL(ch)
  98. #define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE(ch)
  99. #define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK(ch)
  100. #define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM(ch)
  101. #define SRE_UNI_IS_WORD(ch) (SRE_UNI_IS_ALNUM(ch) || (ch) == '_')
  102. static unsigned int sre_lower_unicode(unsigned int ch)
  103. {
  104. return (unsigned int) Py_UNICODE_TOLOWER(ch);
  105. }
  106. static unsigned int sre_upper_unicode(unsigned int ch)
  107. {
  108. return (unsigned int) Py_UNICODE_TOUPPER(ch);
  109. }
  110. LOCAL(int)
  111. sre_category(SRE_CODE category, unsigned int ch)
  112. {
  113. switch (category) {
  114. case SRE_CATEGORY_DIGIT:
  115. return SRE_IS_DIGIT(ch);
  116. case SRE_CATEGORY_NOT_DIGIT:
  117. return !SRE_IS_DIGIT(ch);
  118. case SRE_CATEGORY_SPACE:
  119. return SRE_IS_SPACE(ch);
  120. case SRE_CATEGORY_NOT_SPACE:
  121. return !SRE_IS_SPACE(ch);
  122. case SRE_CATEGORY_WORD:
  123. return SRE_IS_WORD(ch);
  124. case SRE_CATEGORY_NOT_WORD:
  125. return !SRE_IS_WORD(ch);
  126. case SRE_CATEGORY_LINEBREAK:
  127. return SRE_IS_LINEBREAK(ch);
  128. case SRE_CATEGORY_NOT_LINEBREAK:
  129. return !SRE_IS_LINEBREAK(ch);
  130. case SRE_CATEGORY_LOC_WORD:
  131. return SRE_LOC_IS_WORD(ch);
  132. case SRE_CATEGORY_LOC_NOT_WORD:
  133. return !SRE_LOC_IS_WORD(ch);
  134. case SRE_CATEGORY_UNI_DIGIT:
  135. return SRE_UNI_IS_DIGIT(ch);
  136. case SRE_CATEGORY_UNI_NOT_DIGIT:
  137. return !SRE_UNI_IS_DIGIT(ch);
  138. case SRE_CATEGORY_UNI_SPACE:
  139. return SRE_UNI_IS_SPACE(ch);
  140. case SRE_CATEGORY_UNI_NOT_SPACE:
  141. return !SRE_UNI_IS_SPACE(ch);
  142. case SRE_CATEGORY_UNI_WORD:
  143. return SRE_UNI_IS_WORD(ch);
  144. case SRE_CATEGORY_UNI_NOT_WORD:
  145. return !SRE_UNI_IS_WORD(ch);
  146. case SRE_CATEGORY_UNI_LINEBREAK:
  147. return SRE_UNI_IS_LINEBREAK(ch);
  148. case SRE_CATEGORY_UNI_NOT_LINEBREAK:
  149. return !SRE_UNI_IS_LINEBREAK(ch);
  150. }
  151. return 0;
  152. }
  153. LOCAL(int)
  154. char_loc_ignore(SRE_CODE pattern, SRE_CODE ch)
  155. {
  156. return ch == pattern
  157. || (SRE_CODE) sre_lower_locale(ch) == pattern
  158. || (SRE_CODE) sre_upper_locale(ch) == pattern;
  159. }
  160. /* helpers */
  161. static void
  162. data_stack_dealloc(SRE_STATE* state)
  163. {
  164. if (state->data_stack) {
  165. PyMem_Free(state->data_stack);
  166. state->data_stack = NULL;
  167. }
  168. state->data_stack_size = state->data_stack_base = 0;
  169. }
  170. static int
  171. data_stack_grow(SRE_STATE* state, Py_ssize_t size)
  172. {
  173. Py_ssize_t minsize, cursize;
  174. minsize = state->data_stack_base+size;
  175. cursize = state->data_stack_size;
  176. if (cursize < minsize) {
  177. void* stack;
  178. cursize = minsize+minsize/4+1024;
  179. TRACE(("allocate/grow stack %zd\n", cursize));
  180. stack = PyMem_Realloc(state->data_stack, cursize);
  181. if (!stack) {
  182. data_stack_dealloc(state);
  183. return SRE_ERROR_MEMORY;
  184. }
  185. state->data_stack = (char *)stack;
  186. state->data_stack_size = cursize;
  187. }
  188. return 0;
  189. }
  190. /* memory pool functions for SRE_REPEAT, this can avoid memory
  191. leak when SRE(match) function terminates abruptly.
  192. state->repeat_pool_used is a doubly-linked list, so that we
  193. can remove a SRE_REPEAT node from it.
  194. state->repeat_pool_unused is a singly-linked list, we put/get
  195. node at the head. */
  196. static SRE_REPEAT *
  197. repeat_pool_malloc(SRE_STATE *state)
  198. {
  199. SRE_REPEAT *repeat;
  200. if (state->repeat_pool_unused) {
  201. /* remove from unused pool (singly-linked list) */
  202. repeat = state->repeat_pool_unused;
  203. state->repeat_pool_unused = repeat->pool_next;
  204. }
  205. else {
  206. repeat = PyObject_Malloc(sizeof(SRE_REPEAT));
  207. if (!repeat) {
  208. return NULL;
  209. }
  210. }
  211. /* add to used pool (doubly-linked list) */
  212. SRE_REPEAT *temp = state->repeat_pool_used;
  213. if (temp) {
  214. temp->pool_prev = repeat;
  215. }
  216. repeat->pool_prev = NULL;
  217. repeat->pool_next = temp;
  218. state->repeat_pool_used = repeat;
  219. return repeat;
  220. }
  221. static void
  222. repeat_pool_free(SRE_STATE *state, SRE_REPEAT *repeat)
  223. {
  224. SRE_REPEAT *prev = repeat->pool_prev;
  225. SRE_REPEAT *next = repeat->pool_next;
  226. /* remove from used pool (doubly-linked list) */
  227. if (prev) {
  228. prev->pool_next = next;
  229. }
  230. else {
  231. state->repeat_pool_used = next;
  232. }
  233. if (next) {
  234. next->pool_prev = prev;
  235. }
  236. /* add to unused pool (singly-linked list) */
  237. repeat->pool_next = state->repeat_pool_unused;
  238. state->repeat_pool_unused = repeat;
  239. }
  240. static void
  241. repeat_pool_clear(SRE_STATE *state)
  242. {
  243. /* clear used pool */
  244. SRE_REPEAT *next = state->repeat_pool_used;
  245. state->repeat_pool_used = NULL;
  246. while (next) {
  247. SRE_REPEAT *temp = next;
  248. next = temp->pool_next;
  249. PyObject_Free(temp);
  250. }
  251. /* clear unused pool */
  252. next = state->repeat_pool_unused;
  253. state->repeat_pool_unused = NULL;
  254. while (next) {
  255. SRE_REPEAT *temp = next;
  256. next = temp->pool_next;
  257. PyObject_Free(temp);
  258. }
  259. }
  260. /* generate 8-bit version */
  261. #define SRE_CHAR Py_UCS1
  262. #define SIZEOF_SRE_CHAR 1
  263. #define SRE(F) sre_ucs1_##F
  264. #include "sre_lib.h"
  265. /* generate 16-bit unicode version */
  266. #define SRE_CHAR Py_UCS2
  267. #define SIZEOF_SRE_CHAR 2
  268. #define SRE(F) sre_ucs2_##F
  269. #include "sre_lib.h"
  270. /* generate 32-bit unicode version */
  271. #define SRE_CHAR Py_UCS4
  272. #define SIZEOF_SRE_CHAR 4
  273. #define SRE(F) sre_ucs4_##F
  274. #include "sre_lib.h"
  275. /* -------------------------------------------------------------------- */
  276. /* factories and destructors */
  277. /* module state */
  278. typedef struct {
  279. PyTypeObject *Pattern_Type;
  280. PyTypeObject *Match_Type;
  281. PyTypeObject *Scanner_Type;
  282. PyTypeObject *Template_Type;
  283. PyObject *compile_template; // reference to re._compile_template
  284. } _sremodulestate;
  285. static _sremodulestate *
  286. get_sre_module_state(PyObject *m)
  287. {
  288. _sremodulestate *state = (_sremodulestate *)_PyModule_GetState(m);
  289. assert(state);
  290. return state;
  291. }
  292. static struct PyModuleDef sremodule;
  293. #define get_sre_module_state_by_class(cls) \
  294. (get_sre_module_state(PyType_GetModule(cls)))
  295. /* see sre.h for object declarations */
  296. static PyObject*pattern_new_match(_sremodulestate *, PatternObject*, SRE_STATE*, Py_ssize_t);
  297. static PyObject *pattern_scanner(_sremodulestate *, PatternObject *, PyObject *, Py_ssize_t, Py_ssize_t);
  298. /*[clinic input]
  299. module _sre
  300. class _sre.SRE_Pattern "PatternObject *" "get_sre_module_state_by_class(tp)->Pattern_Type"
  301. class _sre.SRE_Match "MatchObject *" "get_sre_module_state_by_class(tp)->Match_Type"
  302. class _sre.SRE_Scanner "ScannerObject *" "get_sre_module_state_by_class(tp)->Scanner_Type"
  303. [clinic start generated code]*/
  304. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=fe2966e32b66a231]*/
  305. /*[clinic input]
  306. _sre.getcodesize -> int
  307. [clinic start generated code]*/
  308. static int
  309. _sre_getcodesize_impl(PyObject *module)
  310. /*[clinic end generated code: output=e0db7ce34a6dd7b1 input=bd6f6ecf4916bb2b]*/
  311. {
  312. return sizeof(SRE_CODE);
  313. }
  314. /*[clinic input]
  315. _sre.ascii_iscased -> bool
  316. character: int
  317. /
  318. [clinic start generated code]*/
  319. static int
  320. _sre_ascii_iscased_impl(PyObject *module, int character)
  321. /*[clinic end generated code: output=4f454b630fbd19a2 input=9f0bd952812c7ed3]*/
  322. {
  323. unsigned int ch = (unsigned int)character;
  324. return ch < 128 && Py_ISALPHA(ch);
  325. }
  326. /*[clinic input]
  327. _sre.unicode_iscased -> bool
  328. character: int
  329. /
  330. [clinic start generated code]*/
  331. static int
  332. _sre_unicode_iscased_impl(PyObject *module, int character)
  333. /*[clinic end generated code: output=9c5ddee0dc2bc258 input=51e42c3b8dddb78e]*/
  334. {
  335. unsigned int ch = (unsigned int)character;
  336. return ch != sre_lower_unicode(ch) || ch != sre_upper_unicode(ch);
  337. }
  338. /*[clinic input]
  339. _sre.ascii_tolower -> int
  340. character: int
  341. /
  342. [clinic start generated code]*/
  343. static int
  344. _sre_ascii_tolower_impl(PyObject *module, int character)
  345. /*[clinic end generated code: output=228294ed6ff2a612 input=272c609b5b61f136]*/
  346. {
  347. return sre_lower_ascii(character);
  348. }
  349. /*[clinic input]
  350. _sre.unicode_tolower -> int
  351. character: int
  352. /
  353. [clinic start generated code]*/
  354. static int
  355. _sre_unicode_tolower_impl(PyObject *module, int character)
  356. /*[clinic end generated code: output=6422272d7d7fee65 input=91d708c5f3c2045a]*/
  357. {
  358. return sre_lower_unicode(character);
  359. }
  360. LOCAL(void)
  361. state_reset(SRE_STATE* state)
  362. {
  363. /* state->mark will be set to 0 in SRE_OP_MARK dynamically. */
  364. /*memset(state->mark, 0, sizeof(*state->mark) * SRE_MARK_SIZE);*/
  365. state->lastmark = -1;
  366. state->lastindex = -1;
  367. state->repeat = NULL;
  368. data_stack_dealloc(state);
  369. }
  370. static const void*
  371. getstring(PyObject* string, Py_ssize_t* p_length,
  372. int* p_isbytes, int* p_charsize,
  373. Py_buffer *view)
  374. {
  375. /* given a python object, return a data pointer, a length (in
  376. characters), and a character size. return NULL if the object
  377. is not a string (or not compatible) */
  378. /* Unicode objects do not support the buffer API. So, get the data
  379. directly instead. */
  380. if (PyUnicode_Check(string)) {
  381. if (PyUnicode_READY(string) == -1)
  382. return NULL;
  383. *p_length = PyUnicode_GET_LENGTH(string);
  384. *p_charsize = PyUnicode_KIND(string);
  385. *p_isbytes = 0;
  386. return PyUnicode_DATA(string);
  387. }
  388. /* get pointer to byte string buffer */
  389. if (PyObject_GetBuffer(string, view, PyBUF_SIMPLE) != 0) {
  390. PyErr_Format(PyExc_TypeError, "expected string or bytes-like "
  391. "object, got '%.200s'", Py_TYPE(string)->tp_name);
  392. return NULL;
  393. }
  394. *p_length = view->len;
  395. *p_charsize = 1;
  396. *p_isbytes = 1;
  397. if (view->buf == NULL) {
  398. PyErr_SetString(PyExc_ValueError, "Buffer is NULL");
  399. PyBuffer_Release(view);
  400. view->buf = NULL;
  401. return NULL;
  402. }
  403. return view->buf;
  404. }
  405. LOCAL(PyObject*)
  406. state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string,
  407. Py_ssize_t start, Py_ssize_t end)
  408. {
  409. /* prepare state object */
  410. Py_ssize_t length;
  411. int isbytes, charsize;
  412. const void* ptr;
  413. memset(state, 0, sizeof(SRE_STATE));
  414. state->mark = PyMem_New(const void *, pattern->groups * 2);
  415. if (!state->mark) {
  416. PyErr_NoMemory();
  417. goto err;
  418. }
  419. state->lastmark = -1;
  420. state->lastindex = -1;
  421. state->buffer.buf = NULL;
  422. ptr = getstring(string, &length, &isbytes, &charsize, &state->buffer);
  423. if (!ptr)
  424. goto err;
  425. if (isbytes && pattern->isbytes == 0) {
  426. PyErr_SetString(PyExc_TypeError,
  427. "cannot use a string pattern on a bytes-like object");
  428. goto err;
  429. }
  430. if (!isbytes && pattern->isbytes > 0) {
  431. PyErr_SetString(PyExc_TypeError,
  432. "cannot use a bytes pattern on a string-like object");
  433. goto err;
  434. }
  435. /* adjust boundaries */
  436. if (start < 0)
  437. start = 0;
  438. else if (start > length)
  439. start = length;
  440. if (end < 0)
  441. end = 0;
  442. else if (end > length)
  443. end = length;
  444. state->isbytes = isbytes;
  445. state->charsize = charsize;
  446. state->match_all = 0;
  447. state->must_advance = 0;
  448. state->beginning = ptr;
  449. state->start = (void*) ((char*) ptr + start * state->charsize);
  450. state->end = (void*) ((char*) ptr + end * state->charsize);
  451. state->string = Py_NewRef(string);
  452. state->pos = start;
  453. state->endpos = end;
  454. #ifdef Py_DEBUG
  455. state->fail_after_count = pattern->fail_after_count;
  456. state->fail_after_exc = pattern->fail_after_exc; // borrowed ref
  457. #endif
  458. return string;
  459. err:
  460. /* We add an explicit cast here because MSVC has a bug when
  461. compiling C code where it believes that `const void**` cannot be
  462. safely casted to `void*`, see bpo-39943 for details. */
  463. PyMem_Free((void*) state->mark);
  464. state->mark = NULL;
  465. if (state->buffer.buf)
  466. PyBuffer_Release(&state->buffer);
  467. return NULL;
  468. }
  469. LOCAL(void)
  470. state_fini(SRE_STATE* state)
  471. {
  472. if (state->buffer.buf)
  473. PyBuffer_Release(&state->buffer);
  474. Py_XDECREF(state->string);
  475. data_stack_dealloc(state);
  476. /* See above PyMem_Del for why we explicitly cast here. */
  477. PyMem_Free((void*) state->mark);
  478. state->mark = NULL;
  479. /* SRE_REPEAT pool */
  480. repeat_pool_clear(state);
  481. }
  482. /* calculate offset from start of string */
  483. #define STATE_OFFSET(state, member)\
  484. (((char*)(member) - (char*)(state)->beginning) / (state)->charsize)
  485. LOCAL(PyObject*)
  486. getslice(int isbytes, const void *ptr,
  487. PyObject* string, Py_ssize_t start, Py_ssize_t end)
  488. {
  489. if (isbytes) {
  490. if (PyBytes_CheckExact(string) &&
  491. start == 0 && end == PyBytes_GET_SIZE(string)) {
  492. return Py_NewRef(string);
  493. }
  494. return PyBytes_FromStringAndSize(
  495. (const char *)ptr + start, end - start);
  496. }
  497. else {
  498. return PyUnicode_Substring(string, start, end);
  499. }
  500. }
  501. LOCAL(PyObject*)
  502. state_getslice(SRE_STATE* state, Py_ssize_t index, PyObject* string, int empty)
  503. {
  504. Py_ssize_t i, j;
  505. index = (index - 1) * 2;
  506. if (string == Py_None || index >= state->lastmark || !state->mark[index] || !state->mark[index+1]) {
  507. if (empty)
  508. /* want empty string */
  509. i = j = 0;
  510. else {
  511. Py_RETURN_NONE;
  512. }
  513. } else {
  514. i = STATE_OFFSET(state, state->mark[index]);
  515. j = STATE_OFFSET(state, state->mark[index+1]);
  516. /* check wrong span */
  517. if (i > j) {
  518. PyErr_SetString(PyExc_SystemError,
  519. "The span of capturing group is wrong,"
  520. " please report a bug for the re module.");
  521. return NULL;
  522. }
  523. }
  524. return getslice(state->isbytes, state->beginning, string, i, j);
  525. }
  526. static void
  527. pattern_error(Py_ssize_t status)
  528. {
  529. switch (status) {
  530. case SRE_ERROR_RECURSION_LIMIT:
  531. /* This error code seems to be unused. */
  532. PyErr_SetString(
  533. PyExc_RecursionError,
  534. "maximum recursion limit exceeded"
  535. );
  536. break;
  537. case SRE_ERROR_MEMORY:
  538. PyErr_NoMemory();
  539. break;
  540. case SRE_ERROR_INTERRUPTED:
  541. /* An exception has already been raised, so let it fly */
  542. break;
  543. default:
  544. /* other error codes indicate compiler/engine bugs */
  545. PyErr_SetString(
  546. PyExc_RuntimeError,
  547. "internal error in regular expression engine"
  548. );
  549. }
  550. }
  551. static int
  552. pattern_traverse(PatternObject *self, visitproc visit, void *arg)
  553. {
  554. Py_VISIT(Py_TYPE(self));
  555. Py_VISIT(self->groupindex);
  556. Py_VISIT(self->indexgroup);
  557. Py_VISIT(self->pattern);
  558. #ifdef Py_DEBUG
  559. Py_VISIT(self->fail_after_exc);
  560. #endif
  561. return 0;
  562. }
  563. static int
  564. pattern_clear(PatternObject *self)
  565. {
  566. Py_CLEAR(self->groupindex);
  567. Py_CLEAR(self->indexgroup);
  568. Py_CLEAR(self->pattern);
  569. #ifdef Py_DEBUG
  570. Py_CLEAR(self->fail_after_exc);
  571. #endif
  572. return 0;
  573. }
  574. static void
  575. pattern_dealloc(PatternObject* self)
  576. {
  577. PyTypeObject *tp = Py_TYPE(self);
  578. PyObject_GC_UnTrack(self);
  579. if (self->weakreflist != NULL) {
  580. PyObject_ClearWeakRefs((PyObject *) self);
  581. }
  582. (void)pattern_clear(self);
  583. tp->tp_free(self);
  584. Py_DECREF(tp);
  585. }
  586. LOCAL(Py_ssize_t)
  587. sre_match(SRE_STATE* state, SRE_CODE* pattern)
  588. {
  589. if (state->charsize == 1)
  590. return sre_ucs1_match(state, pattern, 1);
  591. if (state->charsize == 2)
  592. return sre_ucs2_match(state, pattern, 1);
  593. assert(state->charsize == 4);
  594. return sre_ucs4_match(state, pattern, 1);
  595. }
  596. LOCAL(Py_ssize_t)
  597. sre_search(SRE_STATE* state, SRE_CODE* pattern)
  598. {
  599. if (state->charsize == 1)
  600. return sre_ucs1_search(state, pattern);
  601. if (state->charsize == 2)
  602. return sre_ucs2_search(state, pattern);
  603. assert(state->charsize == 4);
  604. return sre_ucs4_search(state, pattern);
  605. }
  606. /*[clinic input]
  607. _sre.SRE_Pattern.match
  608. cls: defining_class
  609. /
  610. string: object
  611. pos: Py_ssize_t = 0
  612. endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
  613. Matches zero or more characters at the beginning of the string.
  614. [clinic start generated code]*/
  615. static PyObject *
  616. _sre_SRE_Pattern_match_impl(PatternObject *self, PyTypeObject *cls,
  617. PyObject *string, Py_ssize_t pos,
  618. Py_ssize_t endpos)
  619. /*[clinic end generated code: output=ec6208ea58a0cca0 input=4bdb9c3e564d13ac]*/
  620. {
  621. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  622. SRE_STATE state;
  623. Py_ssize_t status;
  624. PyObject *match;
  625. if (!state_init(&state, self, string, pos, endpos))
  626. return NULL;
  627. state.ptr = state.start;
  628. TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr));
  629. status = sre_match(&state, PatternObject_GetCode(self));
  630. TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  631. if (PyErr_Occurred()) {
  632. state_fini(&state);
  633. return NULL;
  634. }
  635. match = pattern_new_match(module_state, self, &state, status);
  636. state_fini(&state);
  637. return match;
  638. }
  639. /*[clinic input]
  640. _sre.SRE_Pattern.fullmatch
  641. cls: defining_class
  642. /
  643. string: object
  644. pos: Py_ssize_t = 0
  645. endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
  646. Matches against all of the string.
  647. [clinic start generated code]*/
  648. static PyObject *
  649. _sre_SRE_Pattern_fullmatch_impl(PatternObject *self, PyTypeObject *cls,
  650. PyObject *string, Py_ssize_t pos,
  651. Py_ssize_t endpos)
  652. /*[clinic end generated code: output=625b75b027ef94da input=50981172ab0fcfdd]*/
  653. {
  654. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  655. SRE_STATE state;
  656. Py_ssize_t status;
  657. PyObject *match;
  658. if (!state_init(&state, self, string, pos, endpos))
  659. return NULL;
  660. state.ptr = state.start;
  661. TRACE(("|%p|%p|FULLMATCH\n", PatternObject_GetCode(self), state.ptr));
  662. state.match_all = 1;
  663. status = sre_match(&state, PatternObject_GetCode(self));
  664. TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  665. if (PyErr_Occurred()) {
  666. state_fini(&state);
  667. return NULL;
  668. }
  669. match = pattern_new_match(module_state, self, &state, status);
  670. state_fini(&state);
  671. return match;
  672. }
  673. /*[clinic input]
  674. _sre.SRE_Pattern.search
  675. cls: defining_class
  676. /
  677. string: object
  678. pos: Py_ssize_t = 0
  679. endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
  680. Scan through string looking for a match, and return a corresponding match object instance.
  681. Return None if no position in the string matches.
  682. [clinic start generated code]*/
  683. static PyObject *
  684. _sre_SRE_Pattern_search_impl(PatternObject *self, PyTypeObject *cls,
  685. PyObject *string, Py_ssize_t pos,
  686. Py_ssize_t endpos)
  687. /*[clinic end generated code: output=bd7f2d9d583e1463 input=afa9afb66a74a4b3]*/
  688. {
  689. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  690. SRE_STATE state;
  691. Py_ssize_t status;
  692. PyObject *match;
  693. if (!state_init(&state, self, string, pos, endpos))
  694. return NULL;
  695. TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr));
  696. status = sre_search(&state, PatternObject_GetCode(self));
  697. TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  698. if (PyErr_Occurred()) {
  699. state_fini(&state);
  700. return NULL;
  701. }
  702. match = pattern_new_match(module_state, self, &state, status);
  703. state_fini(&state);
  704. return match;
  705. }
  706. /*[clinic input]
  707. _sre.SRE_Pattern.findall
  708. string: object
  709. pos: Py_ssize_t = 0
  710. endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
  711. Return a list of all non-overlapping matches of pattern in string.
  712. [clinic start generated code]*/
  713. static PyObject *
  714. _sre_SRE_Pattern_findall_impl(PatternObject *self, PyObject *string,
  715. Py_ssize_t pos, Py_ssize_t endpos)
  716. /*[clinic end generated code: output=f4966baceea60aca input=5b6a4ee799741563]*/
  717. {
  718. SRE_STATE state;
  719. PyObject* list;
  720. Py_ssize_t status;
  721. Py_ssize_t i, b, e;
  722. if (!state_init(&state, self, string, pos, endpos))
  723. return NULL;
  724. list = PyList_New(0);
  725. if (!list) {
  726. state_fini(&state);
  727. return NULL;
  728. }
  729. while (state.start <= state.end) {
  730. PyObject* item;
  731. state_reset(&state);
  732. state.ptr = state.start;
  733. status = sre_search(&state, PatternObject_GetCode(self));
  734. if (PyErr_Occurred())
  735. goto error;
  736. if (status <= 0) {
  737. if (status == 0)
  738. break;
  739. pattern_error(status);
  740. goto error;
  741. }
  742. /* don't bother to build a match object */
  743. switch (self->groups) {
  744. case 0:
  745. b = STATE_OFFSET(&state, state.start);
  746. e = STATE_OFFSET(&state, state.ptr);
  747. item = getslice(state.isbytes, state.beginning,
  748. string, b, e);
  749. if (!item)
  750. goto error;
  751. break;
  752. case 1:
  753. item = state_getslice(&state, 1, string, 1);
  754. if (!item)
  755. goto error;
  756. break;
  757. default:
  758. item = PyTuple_New(self->groups);
  759. if (!item)
  760. goto error;
  761. for (i = 0; i < self->groups; i++) {
  762. PyObject* o = state_getslice(&state, i+1, string, 1);
  763. if (!o) {
  764. Py_DECREF(item);
  765. goto error;
  766. }
  767. PyTuple_SET_ITEM(item, i, o);
  768. }
  769. break;
  770. }
  771. status = PyList_Append(list, item);
  772. Py_DECREF(item);
  773. if (status < 0)
  774. goto error;
  775. state.must_advance = (state.ptr == state.start);
  776. state.start = state.ptr;
  777. }
  778. state_fini(&state);
  779. return list;
  780. error:
  781. Py_DECREF(list);
  782. state_fini(&state);
  783. return NULL;
  784. }
  785. /*[clinic input]
  786. _sre.SRE_Pattern.finditer
  787. cls: defining_class
  788. /
  789. string: object
  790. pos: Py_ssize_t = 0
  791. endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
  792. Return an iterator over all non-overlapping matches for the RE pattern in string.
  793. For each match, the iterator returns a match object.
  794. [clinic start generated code]*/
  795. static PyObject *
  796. _sre_SRE_Pattern_finditer_impl(PatternObject *self, PyTypeObject *cls,
  797. PyObject *string, Py_ssize_t pos,
  798. Py_ssize_t endpos)
  799. /*[clinic end generated code: output=1791dbf3618ade56 input=812e332a4848cbaf]*/
  800. {
  801. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  802. PyObject* scanner;
  803. PyObject* search;
  804. PyObject* iterator;
  805. scanner = pattern_scanner(module_state, self, string, pos, endpos);
  806. if (!scanner)
  807. return NULL;
  808. search = PyObject_GetAttrString(scanner, "search");
  809. Py_DECREF(scanner);
  810. if (!search)
  811. return NULL;
  812. iterator = PyCallIter_New(search, Py_None);
  813. Py_DECREF(search);
  814. return iterator;
  815. }
  816. /*[clinic input]
  817. _sre.SRE_Pattern.scanner
  818. cls: defining_class
  819. /
  820. string: object
  821. pos: Py_ssize_t = 0
  822. endpos: Py_ssize_t(c_default="PY_SSIZE_T_MAX") = sys.maxsize
  823. [clinic start generated code]*/
  824. static PyObject *
  825. _sre_SRE_Pattern_scanner_impl(PatternObject *self, PyTypeObject *cls,
  826. PyObject *string, Py_ssize_t pos,
  827. Py_ssize_t endpos)
  828. /*[clinic end generated code: output=f70cd506112f1bd9 input=2e487e5151bcee4c]*/
  829. {
  830. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  831. return pattern_scanner(module_state, self, string, pos, endpos);
  832. }
  833. /*[clinic input]
  834. _sre.SRE_Pattern.split
  835. string: object
  836. maxsplit: Py_ssize_t = 0
  837. Split string by the occurrences of pattern.
  838. [clinic start generated code]*/
  839. static PyObject *
  840. _sre_SRE_Pattern_split_impl(PatternObject *self, PyObject *string,
  841. Py_ssize_t maxsplit)
  842. /*[clinic end generated code: output=7ac66f381c45e0be input=1eeeb10dafc9947a]*/
  843. {
  844. SRE_STATE state;
  845. PyObject* list;
  846. PyObject* item;
  847. Py_ssize_t status;
  848. Py_ssize_t n;
  849. Py_ssize_t i;
  850. const void* last;
  851. assert(self->codesize != 0);
  852. if (!state_init(&state, self, string, 0, PY_SSIZE_T_MAX))
  853. return NULL;
  854. list = PyList_New(0);
  855. if (!list) {
  856. state_fini(&state);
  857. return NULL;
  858. }
  859. n = 0;
  860. last = state.start;
  861. while (!maxsplit || n < maxsplit) {
  862. state_reset(&state);
  863. state.ptr = state.start;
  864. status = sre_search(&state, PatternObject_GetCode(self));
  865. if (PyErr_Occurred())
  866. goto error;
  867. if (status <= 0) {
  868. if (status == 0)
  869. break;
  870. pattern_error(status);
  871. goto error;
  872. }
  873. /* get segment before this match */
  874. item = getslice(state.isbytes, state.beginning,
  875. string, STATE_OFFSET(&state, last),
  876. STATE_OFFSET(&state, state.start)
  877. );
  878. if (!item)
  879. goto error;
  880. status = PyList_Append(list, item);
  881. Py_DECREF(item);
  882. if (status < 0)
  883. goto error;
  884. /* add groups (if any) */
  885. for (i = 0; i < self->groups; i++) {
  886. item = state_getslice(&state, i+1, string, 0);
  887. if (!item)
  888. goto error;
  889. status = PyList_Append(list, item);
  890. Py_DECREF(item);
  891. if (status < 0)
  892. goto error;
  893. }
  894. n = n + 1;
  895. state.must_advance = (state.ptr == state.start);
  896. last = state.start = state.ptr;
  897. }
  898. /* get segment following last match (even if empty) */
  899. item = getslice(state.isbytes, state.beginning,
  900. string, STATE_OFFSET(&state, last), state.endpos
  901. );
  902. if (!item)
  903. goto error;
  904. status = PyList_Append(list, item);
  905. Py_DECREF(item);
  906. if (status < 0)
  907. goto error;
  908. state_fini(&state);
  909. return list;
  910. error:
  911. Py_DECREF(list);
  912. state_fini(&state);
  913. return NULL;
  914. }
  915. static PyObject *
  916. compile_template(_sremodulestate *module_state,
  917. PatternObject *pattern, PyObject *template)
  918. {
  919. /* delegate to Python code */
  920. PyObject *func = module_state->compile_template;
  921. if (func == NULL) {
  922. func = _PyImport_GetModuleAttrString("re", "_compile_template");
  923. if (func == NULL) {
  924. return NULL;
  925. }
  926. Py_XSETREF(module_state->compile_template, func);
  927. }
  928. PyObject *args[] = {(PyObject *)pattern, template};
  929. PyObject *result = PyObject_Vectorcall(func, args, 2, NULL);
  930. if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
  931. /* If the replacement string is unhashable (e.g. bytearray),
  932. * convert it to the basic type (str or bytes) and repeat. */
  933. if (PyUnicode_Check(template) && !PyUnicode_CheckExact(template)) {
  934. PyErr_Clear();
  935. template = _PyUnicode_Copy(template);
  936. }
  937. else if (PyObject_CheckBuffer(template) && !PyBytes_CheckExact(template)) {
  938. PyErr_Clear();
  939. template = PyBytes_FromObject(template);
  940. }
  941. else {
  942. return NULL;
  943. }
  944. if (template == NULL) {
  945. return NULL;
  946. }
  947. args[1] = template;
  948. result = PyObject_Vectorcall(func, args, 2, NULL);
  949. Py_DECREF(template);
  950. }
  951. if (result != NULL && Py_TYPE(result) != module_state->Template_Type) {
  952. PyErr_Format(PyExc_RuntimeError,
  953. "the result of compiling a replacement string is %.200s",
  954. Py_TYPE(result)->tp_name);
  955. Py_DECREF(result);
  956. return NULL;
  957. }
  958. return result;
  959. }
  960. static PyObject *expand_template(TemplateObject *, MatchObject *); /* Forward */
  961. static PyObject*
  962. pattern_subx(_sremodulestate* module_state,
  963. PatternObject* self,
  964. PyObject* ptemplate,
  965. PyObject* string,
  966. Py_ssize_t count,
  967. Py_ssize_t subn)
  968. {
  969. SRE_STATE state;
  970. PyObject* list;
  971. PyObject* joiner;
  972. PyObject* item;
  973. PyObject* filter;
  974. PyObject* match;
  975. const void* ptr;
  976. Py_ssize_t status;
  977. Py_ssize_t n;
  978. Py_ssize_t i, b, e;
  979. int isbytes, charsize;
  980. enum {LITERAL, TEMPLATE, CALLABLE} filter_type;
  981. Py_buffer view;
  982. if (PyCallable_Check(ptemplate)) {
  983. /* sub/subn takes either a function or a template */
  984. filter = Py_NewRef(ptemplate);
  985. filter_type = CALLABLE;
  986. } else {
  987. /* if not callable, check if it's a literal string */
  988. int literal;
  989. view.buf = NULL;
  990. ptr = getstring(ptemplate, &n, &isbytes, &charsize, &view);
  991. if (ptr) {
  992. if (charsize == 1)
  993. literal = memchr(ptr, '\\', n) == NULL;
  994. else
  995. literal = PyUnicode_FindChar(ptemplate, '\\', 0, n, 1) == -1;
  996. } else {
  997. PyErr_Clear();
  998. literal = 0;
  999. }
  1000. if (view.buf)
  1001. PyBuffer_Release(&view);
  1002. if (literal) {
  1003. filter = Py_NewRef(ptemplate);
  1004. filter_type = LITERAL;
  1005. } else {
  1006. /* not a literal; hand it over to the template compiler */
  1007. filter = compile_template(module_state, self, ptemplate);
  1008. if (!filter)
  1009. return NULL;
  1010. assert(Py_TYPE(filter) == module_state->Template_Type);
  1011. if (Py_SIZE(filter) == 0) {
  1012. Py_SETREF(filter,
  1013. Py_NewRef(((TemplateObject *)filter)->literal));
  1014. filter_type = LITERAL;
  1015. }
  1016. else {
  1017. filter_type = TEMPLATE;
  1018. }
  1019. }
  1020. }
  1021. if (!state_init(&state, self, string, 0, PY_SSIZE_T_MAX)) {
  1022. Py_DECREF(filter);
  1023. return NULL;
  1024. }
  1025. list = PyList_New(0);
  1026. if (!list) {
  1027. Py_DECREF(filter);
  1028. state_fini(&state);
  1029. return NULL;
  1030. }
  1031. n = i = 0;
  1032. while (!count || n < count) {
  1033. state_reset(&state);
  1034. state.ptr = state.start;
  1035. status = sre_search(&state, PatternObject_GetCode(self));
  1036. if (PyErr_Occurred())
  1037. goto error;
  1038. if (status <= 0) {
  1039. if (status == 0)
  1040. break;
  1041. pattern_error(status);
  1042. goto error;
  1043. }
  1044. b = STATE_OFFSET(&state, state.start);
  1045. e = STATE_OFFSET(&state, state.ptr);
  1046. if (i < b) {
  1047. /* get segment before this match */
  1048. item = getslice(state.isbytes, state.beginning,
  1049. string, i, b);
  1050. if (!item)
  1051. goto error;
  1052. status = PyList_Append(list, item);
  1053. Py_DECREF(item);
  1054. if (status < 0)
  1055. goto error;
  1056. }
  1057. if (filter_type != LITERAL) {
  1058. /* pass match object through filter */
  1059. match = pattern_new_match(module_state, self, &state, 1);
  1060. if (!match)
  1061. goto error;
  1062. if (filter_type == TEMPLATE) {
  1063. item = expand_template((TemplateObject *)filter,
  1064. (MatchObject *)match);
  1065. }
  1066. else {
  1067. assert(filter_type == CALLABLE);
  1068. item = PyObject_CallOneArg(filter, match);
  1069. }
  1070. Py_DECREF(match);
  1071. if (!item)
  1072. goto error;
  1073. } else {
  1074. /* filter is literal string */
  1075. item = Py_NewRef(filter);
  1076. }
  1077. /* add to list */
  1078. if (item != Py_None) {
  1079. status = PyList_Append(list, item);
  1080. Py_DECREF(item);
  1081. if (status < 0)
  1082. goto error;
  1083. }
  1084. i = e;
  1085. n = n + 1;
  1086. state.must_advance = (state.ptr == state.start);
  1087. state.start = state.ptr;
  1088. }
  1089. /* get segment following last match */
  1090. if (i < state.endpos) {
  1091. item = getslice(state.isbytes, state.beginning,
  1092. string, i, state.endpos);
  1093. if (!item)
  1094. goto error;
  1095. status = PyList_Append(list, item);
  1096. Py_DECREF(item);
  1097. if (status < 0)
  1098. goto error;
  1099. }
  1100. state_fini(&state);
  1101. Py_DECREF(filter);
  1102. /* convert list to single string (also removes list) */
  1103. joiner = getslice(state.isbytes, state.beginning, string, 0, 0);
  1104. if (!joiner) {
  1105. Py_DECREF(list);
  1106. return NULL;
  1107. }
  1108. if (PyList_GET_SIZE(list) == 0) {
  1109. Py_DECREF(list);
  1110. item = joiner;
  1111. }
  1112. else {
  1113. if (state.isbytes)
  1114. item = _PyBytes_Join(joiner, list);
  1115. else
  1116. item = PyUnicode_Join(joiner, list);
  1117. Py_DECREF(joiner);
  1118. Py_DECREF(list);
  1119. if (!item)
  1120. return NULL;
  1121. }
  1122. if (subn)
  1123. return Py_BuildValue("Nn", item, n);
  1124. return item;
  1125. error:
  1126. Py_DECREF(list);
  1127. state_fini(&state);
  1128. Py_DECREF(filter);
  1129. return NULL;
  1130. }
  1131. /*[clinic input]
  1132. _sre.SRE_Pattern.sub
  1133. cls: defining_class
  1134. /
  1135. repl: object
  1136. string: object
  1137. count: Py_ssize_t = 0
  1138. Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.
  1139. [clinic start generated code]*/
  1140. static PyObject *
  1141. _sre_SRE_Pattern_sub_impl(PatternObject *self, PyTypeObject *cls,
  1142. PyObject *repl, PyObject *string, Py_ssize_t count)
  1143. /*[clinic end generated code: output=4be141ab04bca60d input=d8d1d4ac2311a07c]*/
  1144. {
  1145. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  1146. return pattern_subx(module_state, self, repl, string, count, 0);
  1147. }
  1148. /*[clinic input]
  1149. _sre.SRE_Pattern.subn
  1150. cls: defining_class
  1151. /
  1152. repl: object
  1153. string: object
  1154. count: Py_ssize_t = 0
  1155. Return the tuple (new_string, number_of_subs_made) found by replacing the leftmost non-overlapping occurrences of pattern with the replacement repl.
  1156. [clinic start generated code]*/
  1157. static PyObject *
  1158. _sre_SRE_Pattern_subn_impl(PatternObject *self, PyTypeObject *cls,
  1159. PyObject *repl, PyObject *string,
  1160. Py_ssize_t count)
  1161. /*[clinic end generated code: output=da02fd85258b1e1f input=8b78a65b8302e58d]*/
  1162. {
  1163. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  1164. return pattern_subx(module_state, self, repl, string, count, 1);
  1165. }
  1166. /*[clinic input]
  1167. _sre.SRE_Pattern.__copy__
  1168. [clinic start generated code]*/
  1169. static PyObject *
  1170. _sre_SRE_Pattern___copy___impl(PatternObject *self)
  1171. /*[clinic end generated code: output=85dedc2db1bd8694 input=a730a59d863bc9f5]*/
  1172. {
  1173. return Py_NewRef(self);
  1174. }
  1175. /*[clinic input]
  1176. _sre.SRE_Pattern.__deepcopy__
  1177. memo: object
  1178. /
  1179. [clinic start generated code]*/
  1180. static PyObject *
  1181. _sre_SRE_Pattern___deepcopy__(PatternObject *self, PyObject *memo)
  1182. /*[clinic end generated code: output=2ad25679c1f1204a input=a465b1602f997bed]*/
  1183. {
  1184. return Py_NewRef(self);
  1185. }
  1186. #ifdef Py_DEBUG
  1187. /*[clinic input]
  1188. _sre.SRE_Pattern._fail_after
  1189. count: int
  1190. exception: object
  1191. /
  1192. For debugging.
  1193. [clinic start generated code]*/
  1194. static PyObject *
  1195. _sre_SRE_Pattern__fail_after_impl(PatternObject *self, int count,
  1196. PyObject *exception)
  1197. /*[clinic end generated code: output=9a6bf12135ac50c2 input=ef80a45c66c5499d]*/
  1198. {
  1199. self->fail_after_count = count;
  1200. Py_INCREF(exception);
  1201. Py_XSETREF(self->fail_after_exc, exception);
  1202. Py_RETURN_NONE;
  1203. }
  1204. #endif /* Py_DEBUG */
  1205. static PyObject *
  1206. pattern_repr(PatternObject *obj)
  1207. {
  1208. static const struct {
  1209. const char *name;
  1210. int value;
  1211. } flag_names[] = {
  1212. {"re.TEMPLATE", SRE_FLAG_TEMPLATE},
  1213. {"re.IGNORECASE", SRE_FLAG_IGNORECASE},
  1214. {"re.LOCALE", SRE_FLAG_LOCALE},
  1215. {"re.MULTILINE", SRE_FLAG_MULTILINE},
  1216. {"re.DOTALL", SRE_FLAG_DOTALL},
  1217. {"re.UNICODE", SRE_FLAG_UNICODE},
  1218. {"re.VERBOSE", SRE_FLAG_VERBOSE},
  1219. {"re.DEBUG", SRE_FLAG_DEBUG},
  1220. {"re.ASCII", SRE_FLAG_ASCII},
  1221. };
  1222. PyObject *result = NULL;
  1223. PyObject *flag_items;
  1224. size_t i;
  1225. int flags = obj->flags;
  1226. /* Omit re.UNICODE for valid string patterns. */
  1227. if (obj->isbytes == 0 &&
  1228. (flags & (SRE_FLAG_LOCALE|SRE_FLAG_UNICODE|SRE_FLAG_ASCII)) ==
  1229. SRE_FLAG_UNICODE)
  1230. flags &= ~SRE_FLAG_UNICODE;
  1231. flag_items = PyList_New(0);
  1232. if (!flag_items)
  1233. return NULL;
  1234. for (i = 0; i < Py_ARRAY_LENGTH(flag_names); i++) {
  1235. if (flags & flag_names[i].value) {
  1236. PyObject *item = PyUnicode_FromString(flag_names[i].name);
  1237. if (!item)
  1238. goto done;
  1239. if (PyList_Append(flag_items, item) < 0) {
  1240. Py_DECREF(item);
  1241. goto done;
  1242. }
  1243. Py_DECREF(item);
  1244. flags &= ~flag_names[i].value;
  1245. }
  1246. }
  1247. if (flags) {
  1248. PyObject *item = PyUnicode_FromFormat("0x%x", flags);
  1249. if (!item)
  1250. goto done;
  1251. if (PyList_Append(flag_items, item) < 0) {
  1252. Py_DECREF(item);
  1253. goto done;
  1254. }
  1255. Py_DECREF(item);
  1256. }
  1257. if (PyList_Size(flag_items) > 0) {
  1258. PyObject *flags_result;
  1259. PyObject *sep = PyUnicode_FromString("|");
  1260. if (!sep)
  1261. goto done;
  1262. flags_result = PyUnicode_Join(sep, flag_items);
  1263. Py_DECREF(sep);
  1264. if (!flags_result)
  1265. goto done;
  1266. result = PyUnicode_FromFormat("re.compile(%.200R, %S)",
  1267. obj->pattern, flags_result);
  1268. Py_DECREF(flags_result);
  1269. }
  1270. else {
  1271. result = PyUnicode_FromFormat("re.compile(%.200R)", obj->pattern);
  1272. }
  1273. done:
  1274. Py_DECREF(flag_items);
  1275. return result;
  1276. }
  1277. PyDoc_STRVAR(pattern_doc, "Compiled regular expression object.");
  1278. /* PatternObject's 'groupindex' method. */
  1279. static PyObject *
  1280. pattern_groupindex(PatternObject *self, void *Py_UNUSED(ignored))
  1281. {
  1282. if (self->groupindex == NULL)
  1283. return PyDict_New();
  1284. return PyDictProxy_New(self->groupindex);
  1285. }
  1286. static int _validate(PatternObject *self); /* Forward */
  1287. /*[clinic input]
  1288. _sre.compile
  1289. pattern: object
  1290. flags: int
  1291. code: object(subclass_of='&PyList_Type')
  1292. groups: Py_ssize_t
  1293. groupindex: object(subclass_of='&PyDict_Type')
  1294. indexgroup: object(subclass_of='&PyTuple_Type')
  1295. [clinic start generated code]*/
  1296. static PyObject *
  1297. _sre_compile_impl(PyObject *module, PyObject *pattern, int flags,
  1298. PyObject *code, Py_ssize_t groups, PyObject *groupindex,
  1299. PyObject *indexgroup)
  1300. /*[clinic end generated code: output=ef9c2b3693776404 input=0a68476dbbe5db30]*/
  1301. {
  1302. /* "compile" pattern descriptor to pattern object */
  1303. _sremodulestate *module_state = get_sre_module_state(module);
  1304. PatternObject* self;
  1305. Py_ssize_t i, n;
  1306. n = PyList_GET_SIZE(code);
  1307. /* coverity[ampersand_in_size] */
  1308. self = PyObject_GC_NewVar(PatternObject, module_state->Pattern_Type, n);
  1309. if (!self)
  1310. return NULL;
  1311. self->weakreflist = NULL;
  1312. self->pattern = NULL;
  1313. self->groupindex = NULL;
  1314. self->indexgroup = NULL;
  1315. #ifdef Py_DEBUG
  1316. self->fail_after_count = -1;
  1317. self->fail_after_exc = NULL;
  1318. #endif
  1319. self->codesize = n;
  1320. for (i = 0; i < n; i++) {
  1321. PyObject *o = PyList_GET_ITEM(code, i);
  1322. unsigned long value = PyLong_AsUnsignedLong(o);
  1323. if (value == (unsigned long)-1 && PyErr_Occurred()) {
  1324. break;
  1325. }
  1326. self->code[i] = (SRE_CODE) value;
  1327. if ((unsigned long) self->code[i] != value) {
  1328. PyErr_SetString(PyExc_OverflowError,
  1329. "regular expression code size limit exceeded");
  1330. break;
  1331. }
  1332. }
  1333. PyObject_GC_Track(self);
  1334. if (PyErr_Occurred()) {
  1335. Py_DECREF(self);
  1336. return NULL;
  1337. }
  1338. if (pattern == Py_None) {
  1339. self->isbytes = -1;
  1340. }
  1341. else {
  1342. Py_ssize_t p_length;
  1343. int charsize;
  1344. Py_buffer view;
  1345. view.buf = NULL;
  1346. if (!getstring(pattern, &p_length, &self->isbytes,
  1347. &charsize, &view)) {
  1348. Py_DECREF(self);
  1349. return NULL;
  1350. }
  1351. if (view.buf)
  1352. PyBuffer_Release(&view);
  1353. }
  1354. self->pattern = Py_NewRef(pattern);
  1355. self->flags = flags;
  1356. self->groups = groups;
  1357. if (PyDict_GET_SIZE(groupindex) > 0) {
  1358. self->groupindex = Py_NewRef(groupindex);
  1359. if (PyTuple_GET_SIZE(indexgroup) > 0) {
  1360. self->indexgroup = Py_NewRef(indexgroup);
  1361. }
  1362. }
  1363. if (!_validate(self)) {
  1364. Py_DECREF(self);
  1365. return NULL;
  1366. }
  1367. return (PyObject*) self;
  1368. }
  1369. /*[clinic input]
  1370. _sre.template
  1371. pattern: object
  1372. template: object(subclass_of="&PyList_Type")
  1373. A list containing interleaved literal strings (str or bytes) and group
  1374. indices (int), as returned by re._parser.parse_template():
  1375. [literal1, group1, ..., literalN, groupN]
  1376. /
  1377. [clinic start generated code]*/
  1378. static PyObject *
  1379. _sre_template_impl(PyObject *module, PyObject *pattern, PyObject *template)
  1380. /*[clinic end generated code: output=d51290e596ebca86 input=af55380b27f02942]*/
  1381. {
  1382. /* template is a list containing interleaved literal strings (str or bytes)
  1383. * and group indices (int), as returned by _parser.parse_template:
  1384. * [literal1, group1, literal2, ..., literalN].
  1385. */
  1386. _sremodulestate *module_state = get_sre_module_state(module);
  1387. TemplateObject *self = NULL;
  1388. Py_ssize_t n = PyList_GET_SIZE(template);
  1389. if ((n & 1) == 0 || n < 1) {
  1390. goto bad_template;
  1391. }
  1392. n /= 2;
  1393. self = PyObject_GC_NewVar(TemplateObject, module_state->Template_Type, n);
  1394. if (!self)
  1395. return NULL;
  1396. self->chunks = 1 + 2*n;
  1397. self->literal = Py_NewRef(PyList_GET_ITEM(template, 0));
  1398. for (Py_ssize_t i = 0; i < n; i++) {
  1399. Py_ssize_t index = PyLong_AsSsize_t(PyList_GET_ITEM(template, 2*i+1));
  1400. if (index == -1 && PyErr_Occurred()) {
  1401. Py_SET_SIZE(self, i);
  1402. Py_DECREF(self);
  1403. return NULL;
  1404. }
  1405. if (index < 0) {
  1406. Py_SET_SIZE(self, i);
  1407. goto bad_template;
  1408. }
  1409. self->items[i].index = index;
  1410. PyObject *literal = PyList_GET_ITEM(template, 2*i+2);
  1411. // Skip empty literals.
  1412. if ((PyUnicode_Check(literal) && !PyUnicode_GET_LENGTH(literal)) ||
  1413. (PyBytes_Check(literal) && !PyBytes_GET_SIZE(literal)))
  1414. {
  1415. literal = NULL;
  1416. self->chunks--;
  1417. }
  1418. self->items[i].literal = Py_XNewRef(literal);
  1419. }
  1420. PyObject_GC_Track(self);
  1421. return (PyObject*) self;
  1422. bad_template:
  1423. PyErr_SetString(PyExc_TypeError, "invalid template");
  1424. Py_XDECREF(self);
  1425. return NULL;
  1426. }
  1427. /* -------------------------------------------------------------------- */
  1428. /* Code validation */
  1429. /* To learn more about this code, have a look at the _compile() function in
  1430. Lib/sre_compile.py. The validation functions below checks the code array
  1431. for conformance with the code patterns generated there.
  1432. The nice thing about the generated code is that it is position-independent:
  1433. all jumps are relative jumps forward. Also, jumps don't cross each other:
  1434. the target of a later jump is always earlier than the target of an earlier
  1435. jump. IOW, this is okay:
  1436. J---------J-------T--------T
  1437. \ \_____/ /
  1438. \______________________/
  1439. but this is not:
  1440. J---------J-------T--------T
  1441. \_________\_____/ /
  1442. \____________/
  1443. It also helps that SRE_CODE is always an unsigned type.
  1444. */
  1445. /* Defining this one enables tracing of the validator */
  1446. #undef VVERBOSE
  1447. /* Trace macro for the validator */
  1448. #if defined(VVERBOSE)
  1449. #define VTRACE(v) printf v
  1450. #else
  1451. #define VTRACE(v) do {} while(0) /* do nothing */
  1452. #endif
  1453. /* Report failure */
  1454. #define FAIL do { VTRACE(("FAIL: %d\n", __LINE__)); return -1; } while (0)
  1455. /* Extract opcode, argument, or skip count from code array */
  1456. #define GET_OP \
  1457. do { \
  1458. VTRACE(("%p: ", code)); \
  1459. if (code >= end) FAIL; \
  1460. op = *code++; \
  1461. VTRACE(("%lu (op)\n", (unsigned long)op)); \
  1462. } while (0)
  1463. #define GET_ARG \
  1464. do { \
  1465. VTRACE(("%p= ", code)); \
  1466. if (code >= end) FAIL; \
  1467. arg = *code++; \
  1468. VTRACE(("%lu (arg)\n", (unsigned long)arg)); \
  1469. } while (0)
  1470. #define GET_SKIP_ADJ(adj) \
  1471. do { \
  1472. VTRACE(("%p= ", code)); \
  1473. if (code >= end) FAIL; \
  1474. skip = *code; \
  1475. VTRACE(("%lu (skip to %p)\n", \
  1476. (unsigned long)skip, code+skip)); \
  1477. if (skip-adj > (uintptr_t)(end - code)) \
  1478. FAIL; \
  1479. code++; \
  1480. } while (0)
  1481. #define GET_SKIP GET_SKIP_ADJ(0)
  1482. static int
  1483. _validate_charset(SRE_CODE *code, SRE_CODE *end)
  1484. {
  1485. /* Some variables are manipulated by the macros above */
  1486. SRE_CODE op;
  1487. SRE_CODE arg;
  1488. SRE_CODE offset;
  1489. int i;
  1490. while (code < end) {
  1491. GET_OP;
  1492. switch (op) {
  1493. case SRE_OP_NEGATE:
  1494. break;
  1495. case SRE_OP_LITERAL:
  1496. GET_ARG;
  1497. break;
  1498. case SRE_OP_RANGE:
  1499. case SRE_OP_RANGE_UNI_IGNORE:
  1500. GET_ARG;
  1501. GET_ARG;
  1502. break;
  1503. case SRE_OP_CHARSET:
  1504. offset = 256/SRE_CODE_BITS; /* 256-bit bitmap */
  1505. if (offset > (uintptr_t)(end - code))
  1506. FAIL;
  1507. code += offset;
  1508. break;
  1509. case SRE_OP_BIGCHARSET:
  1510. GET_ARG; /* Number of blocks */
  1511. offset = 256/sizeof(SRE_CODE); /* 256-byte table */
  1512. if (offset > (uintptr_t)(end - code))
  1513. FAIL;
  1514. /* Make sure that each byte points to a valid block */
  1515. for (i = 0; i < 256; i++) {
  1516. if (((unsigned char *)code)[i] >= arg)
  1517. FAIL;
  1518. }
  1519. code += offset;
  1520. offset = arg * (256/SRE_CODE_BITS); /* 256-bit bitmap times arg */
  1521. if (offset > (uintptr_t)(end - code))
  1522. FAIL;
  1523. code += offset;
  1524. break;
  1525. case SRE_OP_CATEGORY:
  1526. GET_ARG;
  1527. switch (arg) {
  1528. case SRE_CATEGORY_DIGIT:
  1529. case SRE_CATEGORY_NOT_DIGIT:
  1530. case SRE_CATEGORY_SPACE:
  1531. case SRE_CATEGORY_NOT_SPACE:
  1532. case SRE_CATEGORY_WORD:
  1533. case SRE_CATEGORY_NOT_WORD:
  1534. case SRE_CATEGORY_LINEBREAK:
  1535. case SRE_CATEGORY_NOT_LINEBREAK:
  1536. case SRE_CATEGORY_LOC_WORD:
  1537. case SRE_CATEGORY_LOC_NOT_WORD:
  1538. case SRE_CATEGORY_UNI_DIGIT:
  1539. case SRE_CATEGORY_UNI_NOT_DIGIT:
  1540. case SRE_CATEGORY_UNI_SPACE:
  1541. case SRE_CATEGORY_UNI_NOT_SPACE:
  1542. case SRE_CATEGORY_UNI_WORD:
  1543. case SRE_CATEGORY_UNI_NOT_WORD:
  1544. case SRE_CATEGORY_UNI_LINEBREAK:
  1545. case SRE_CATEGORY_UNI_NOT_LINEBREAK:
  1546. break;
  1547. default:
  1548. FAIL;
  1549. }
  1550. break;
  1551. default:
  1552. FAIL;
  1553. }
  1554. }
  1555. return 0;
  1556. }
  1557. /* Returns 0 on success, -1 on failure, and 1 if the last op is JUMP. */
  1558. static int
  1559. _validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)
  1560. {
  1561. /* Some variables are manipulated by the macros above */
  1562. SRE_CODE op;
  1563. SRE_CODE arg;
  1564. SRE_CODE skip;
  1565. VTRACE(("code=%p, end=%p\n", code, end));
  1566. if (code > end)
  1567. FAIL;
  1568. while (code < end) {
  1569. GET_OP;
  1570. switch (op) {
  1571. case SRE_OP_MARK:
  1572. /* We don't check whether marks are properly nested; the
  1573. sre_match() code is robust even if they don't, and the worst
  1574. you can get is nonsensical match results. */
  1575. GET_ARG;
  1576. if (arg > 2 * (size_t)groups + 1) {
  1577. VTRACE(("arg=%d, groups=%d\n", (int)arg, (int)groups));
  1578. FAIL;
  1579. }
  1580. break;
  1581. case SRE_OP_LITERAL:
  1582. case SRE_OP_NOT_LITERAL:
  1583. case SRE_OP_LITERAL_IGNORE:
  1584. case SRE_OP_NOT_LITERAL_IGNORE:
  1585. case SRE_OP_LITERAL_UNI_IGNORE:
  1586. case SRE_OP_NOT_LITERAL_UNI_IGNORE:
  1587. case SRE_OP_LITERAL_LOC_IGNORE:
  1588. case SRE_OP_NOT_LITERAL_LOC_IGNORE:
  1589. GET_ARG;
  1590. /* The arg is just a character, nothing to check */
  1591. break;
  1592. case SRE_OP_SUCCESS:
  1593. case SRE_OP_FAILURE:
  1594. /* Nothing to check; these normally end the matching process */
  1595. break;
  1596. case SRE_OP_AT:
  1597. GET_ARG;
  1598. switch (arg) {
  1599. case SRE_AT_BEGINNING:
  1600. case SRE_AT_BEGINNING_STRING:
  1601. case SRE_AT_BEGINNING_LINE:
  1602. case SRE_AT_END:
  1603. case SRE_AT_END_LINE:
  1604. case SRE_AT_END_STRING:
  1605. case SRE_AT_BOUNDARY:
  1606. case SRE_AT_NON_BOUNDARY:
  1607. case SRE_AT_LOC_BOUNDARY:
  1608. case SRE_AT_LOC_NON_BOUNDARY:
  1609. case SRE_AT_UNI_BOUNDARY:
  1610. case SRE_AT_UNI_NON_BOUNDARY:
  1611. break;
  1612. default:
  1613. FAIL;
  1614. }
  1615. break;
  1616. case SRE_OP_ANY:
  1617. case SRE_OP_ANY_ALL:
  1618. /* These have no operands */
  1619. break;
  1620. case SRE_OP_IN:
  1621. case SRE_OP_IN_IGNORE:
  1622. case SRE_OP_IN_UNI_IGNORE:
  1623. case SRE_OP_IN_LOC_IGNORE:
  1624. GET_SKIP;
  1625. /* Stop 1 before the end; we check the FAILURE below */
  1626. if (_validate_charset(code, code+skip-2))
  1627. FAIL;
  1628. if (code[skip-2] != SRE_OP_FAILURE)
  1629. FAIL;
  1630. code += skip-1;
  1631. break;
  1632. case SRE_OP_INFO:
  1633. {
  1634. /* A minimal info field is
  1635. <INFO> <1=skip> <2=flags> <3=min> <4=max>;
  1636. If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the flags,
  1637. more follows. */
  1638. SRE_CODE flags, i;
  1639. SRE_CODE *newcode;
  1640. GET_SKIP;
  1641. newcode = code+skip-1;
  1642. GET_ARG; flags = arg;
  1643. GET_ARG;
  1644. GET_ARG;
  1645. /* Check that only valid flags are present */
  1646. if ((flags & ~(SRE_INFO_PREFIX |
  1647. SRE_INFO_LITERAL |
  1648. SRE_INFO_CHARSET)) != 0)
  1649. FAIL;
  1650. /* PREFIX and CHARSET are mutually exclusive */
  1651. if ((flags & SRE_INFO_PREFIX) &&
  1652. (flags & SRE_INFO_CHARSET))
  1653. FAIL;
  1654. /* LITERAL implies PREFIX */
  1655. if ((flags & SRE_INFO_LITERAL) &&
  1656. !(flags & SRE_INFO_PREFIX))
  1657. FAIL;
  1658. /* Validate the prefix */
  1659. if (flags & SRE_INFO_PREFIX) {
  1660. SRE_CODE prefix_len;
  1661. GET_ARG; prefix_len = arg;
  1662. GET_ARG;
  1663. /* Here comes the prefix string */
  1664. if (prefix_len > (uintptr_t)(newcode - code))
  1665. FAIL;
  1666. code += prefix_len;
  1667. /* And here comes the overlap table */
  1668. if (prefix_len > (uintptr_t)(newcode - code))
  1669. FAIL;
  1670. /* Each overlap value should be < prefix_len */
  1671. for (i = 0; i < prefix_len; i++) {
  1672. if (code[i] >= prefix_len)
  1673. FAIL;
  1674. }
  1675. code += prefix_len;
  1676. }
  1677. /* Validate the charset */
  1678. if (flags & SRE_INFO_CHARSET) {
  1679. if (_validate_charset(code, newcode-1))
  1680. FAIL;
  1681. if (newcode[-1] != SRE_OP_FAILURE)
  1682. FAIL;
  1683. code = newcode;
  1684. }
  1685. else if (code != newcode) {
  1686. VTRACE(("code=%p, newcode=%p\n", code, newcode));
  1687. FAIL;
  1688. }
  1689. }
  1690. break;
  1691. case SRE_OP_BRANCH:
  1692. {
  1693. SRE_CODE *target = NULL;
  1694. for (;;) {
  1695. GET_SKIP;
  1696. if (skip == 0)
  1697. break;
  1698. /* Stop 2 before the end; we check the JUMP below */
  1699. if (_validate_inner(code, code+skip-3, groups))
  1700. FAIL;
  1701. code += skip-3;
  1702. /* Check that it ends with a JUMP, and that each JUMP
  1703. has the same target */
  1704. GET_OP;
  1705. if (op != SRE_OP_JUMP)
  1706. FAIL;
  1707. GET_SKIP;
  1708. if (target == NULL)
  1709. target = code+skip-1;
  1710. else if (code+skip-1 != target)
  1711. FAIL;
  1712. }
  1713. if (code != target)
  1714. FAIL;
  1715. }
  1716. break;
  1717. case SRE_OP_REPEAT_ONE:
  1718. case SRE_OP_MIN_REPEAT_ONE:
  1719. case SRE_OP_POSSESSIVE_REPEAT_ONE:
  1720. {
  1721. SRE_CODE min, max;
  1722. GET_SKIP;
  1723. GET_ARG; min = arg;
  1724. GET_ARG; max = arg;
  1725. if (min > max)
  1726. FAIL;
  1727. if (max > SRE_MAXREPEAT)
  1728. FAIL;
  1729. if (_validate_inner(code, code+skip-4, groups))
  1730. FAIL;
  1731. code += skip-4;
  1732. GET_OP;
  1733. if (op != SRE_OP_SUCCESS)
  1734. FAIL;
  1735. }
  1736. break;
  1737. case SRE_OP_REPEAT:
  1738. case SRE_OP_POSSESSIVE_REPEAT:
  1739. {
  1740. SRE_CODE op1 = op, min, max;
  1741. GET_SKIP;
  1742. GET_ARG; min = arg;
  1743. GET_ARG; max = arg;
  1744. if (min > max)
  1745. FAIL;
  1746. if (max > SRE_MAXREPEAT)
  1747. FAIL;
  1748. if (_validate_inner(code, code+skip-3, groups))
  1749. FAIL;
  1750. code += skip-3;
  1751. GET_OP;
  1752. if (op1 == SRE_OP_POSSESSIVE_REPEAT) {
  1753. if (op != SRE_OP_SUCCESS)
  1754. FAIL;
  1755. }
  1756. else {
  1757. if (op != SRE_OP_MAX_UNTIL && op != SRE_OP_MIN_UNTIL)
  1758. FAIL;
  1759. }
  1760. }
  1761. break;
  1762. case SRE_OP_ATOMIC_GROUP:
  1763. {
  1764. GET_SKIP;
  1765. if (_validate_inner(code, code+skip-2, groups))
  1766. FAIL;
  1767. code += skip-2;
  1768. GET_OP;
  1769. if (op != SRE_OP_SUCCESS)
  1770. FAIL;
  1771. }
  1772. break;
  1773. case SRE_OP_GROUPREF:
  1774. case SRE_OP_GROUPREF_IGNORE:
  1775. case SRE_OP_GROUPREF_UNI_IGNORE:
  1776. case SRE_OP_GROUPREF_LOC_IGNORE:
  1777. GET_ARG;
  1778. if (arg >= (size_t)groups)
  1779. FAIL;
  1780. break;
  1781. case SRE_OP_GROUPREF_EXISTS:
  1782. /* The regex syntax for this is: '(?(group)then|else)', where
  1783. 'group' is either an integer group number or a group name,
  1784. 'then' and 'else' are sub-regexes, and 'else' is optional. */
  1785. GET_ARG;
  1786. if (arg >= (size_t)groups)
  1787. FAIL;
  1788. GET_SKIP_ADJ(1);
  1789. code--; /* The skip is relative to the first arg! */
  1790. /* There are two possibilities here: if there is both a 'then'
  1791. part and an 'else' part, the generated code looks like:
  1792. GROUPREF_EXISTS
  1793. <group>
  1794. <skipyes>
  1795. ...then part...
  1796. JUMP
  1797. <skipno>
  1798. (<skipyes> jumps here)
  1799. ...else part...
  1800. (<skipno> jumps here)
  1801. If there is only a 'then' part, it looks like:
  1802. GROUPREF_EXISTS
  1803. <group>
  1804. <skip>
  1805. ...then part...
  1806. (<skip> jumps here)
  1807. There is no direct way to decide which it is, and we don't want
  1808. to allow arbitrary jumps anywhere in the code; so we just look
  1809. for a JUMP opcode preceding our skip target.
  1810. */
  1811. VTRACE(("then part:\n"));
  1812. int rc = _validate_inner(code+1, code+skip-1, groups);
  1813. if (rc == 1) {
  1814. VTRACE(("else part:\n"));
  1815. code += skip-2; /* Position after JUMP, at <skipno> */
  1816. GET_SKIP;
  1817. rc = _validate_inner(code, code+skip-1, groups);
  1818. }
  1819. if (rc)
  1820. FAIL;
  1821. code += skip-1;
  1822. break;
  1823. case SRE_OP_ASSERT:
  1824. case SRE_OP_ASSERT_NOT:
  1825. GET_SKIP;
  1826. GET_ARG; /* 0 for lookahead, width for lookbehind */
  1827. code--; /* Back up over arg to simplify math below */
  1828. /* Stop 1 before the end; we check the SUCCESS below */
  1829. if (_validate_inner(code+1, code+skip-2, groups))
  1830. FAIL;
  1831. code += skip-2;
  1832. GET_OP;
  1833. if (op != SRE_OP_SUCCESS)
  1834. FAIL;
  1835. break;
  1836. case SRE_OP_JUMP:
  1837. if (code + 1 != end)
  1838. FAIL;
  1839. VTRACE(("JUMP: %d\n", __LINE__));
  1840. return 1;
  1841. default:
  1842. FAIL;
  1843. }
  1844. }
  1845. VTRACE(("okay\n"));
  1846. return 0;
  1847. }
  1848. static int
  1849. _validate_outer(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups)
  1850. {
  1851. if (groups < 0 || (size_t)groups > SRE_MAXGROUPS ||
  1852. code >= end || end[-1] != SRE_OP_SUCCESS)
  1853. FAIL;
  1854. return _validate_inner(code, end-1, groups);
  1855. }
  1856. static int
  1857. _validate(PatternObject *self)
  1858. {
  1859. if (_validate_outer(self->code, self->code+self->codesize, self->groups))
  1860. {
  1861. PyErr_SetString(PyExc_RuntimeError, "invalid SRE code");
  1862. return 0;
  1863. }
  1864. else
  1865. VTRACE(("Success!\n"));
  1866. return 1;
  1867. }
  1868. /* -------------------------------------------------------------------- */
  1869. /* match methods */
  1870. static int
  1871. match_traverse(MatchObject *self, visitproc visit, void *arg)
  1872. {
  1873. Py_VISIT(Py_TYPE(self));
  1874. Py_VISIT(self->string);
  1875. Py_VISIT(self->regs);
  1876. Py_VISIT(self->pattern);
  1877. return 0;
  1878. }
  1879. static int
  1880. match_clear(MatchObject *self)
  1881. {
  1882. Py_CLEAR(self->string);
  1883. Py_CLEAR(self->regs);
  1884. Py_CLEAR(self->pattern);
  1885. return 0;
  1886. }
  1887. static void
  1888. match_dealloc(MatchObject* self)
  1889. {
  1890. PyTypeObject *tp = Py_TYPE(self);
  1891. PyObject_GC_UnTrack(self);
  1892. (void)match_clear(self);
  1893. tp->tp_free(self);
  1894. Py_DECREF(tp);
  1895. }
  1896. static PyObject*
  1897. match_getslice_by_index(MatchObject* self, Py_ssize_t index, PyObject* def)
  1898. {
  1899. Py_ssize_t length;
  1900. int isbytes, charsize;
  1901. Py_buffer view;
  1902. PyObject *result;
  1903. const void* ptr;
  1904. Py_ssize_t i, j;
  1905. assert(0 <= index && index < self->groups);
  1906. index *= 2;
  1907. if (self->string == Py_None || self->mark[index] < 0) {
  1908. /* return default value if the string or group is undefined */
  1909. return Py_NewRef(def);
  1910. }
  1911. ptr = getstring(self->string, &length, &isbytes, &charsize, &view);
  1912. if (ptr == NULL)
  1913. return NULL;
  1914. i = self->mark[index];
  1915. j = self->mark[index+1];
  1916. i = Py_MIN(i, length);
  1917. j = Py_MIN(j, length);
  1918. result = getslice(isbytes, ptr, self->string, i, j);
  1919. if (isbytes && view.buf != NULL)
  1920. PyBuffer_Release(&view);
  1921. return result;
  1922. }
  1923. static Py_ssize_t
  1924. match_getindex(MatchObject* self, PyObject* index)
  1925. {
  1926. Py_ssize_t i;
  1927. if (index == NULL)
  1928. /* Default value */
  1929. return 0;
  1930. if (PyIndex_Check(index)) {
  1931. i = PyNumber_AsSsize_t(index, NULL);
  1932. }
  1933. else {
  1934. i = -1;
  1935. if (self->pattern->groupindex) {
  1936. index = PyDict_GetItemWithError(self->pattern->groupindex, index);
  1937. if (index && PyLong_Check(index)) {
  1938. i = PyLong_AsSsize_t(index);
  1939. }
  1940. }
  1941. }
  1942. if (i < 0 || i >= self->groups) {
  1943. /* raise IndexError if we were given a bad group number */
  1944. if (!PyErr_Occurred()) {
  1945. PyErr_SetString(PyExc_IndexError, "no such group");
  1946. }
  1947. return -1;
  1948. }
  1949. // Check that i*2 cannot overflow to make static analyzers happy
  1950. assert(i <= SRE_MAXGROUPS);
  1951. return i;
  1952. }
  1953. static PyObject*
  1954. match_getslice(MatchObject* self, PyObject* index, PyObject* def)
  1955. {
  1956. Py_ssize_t i = match_getindex(self, index);
  1957. if (i < 0) {
  1958. return NULL;
  1959. }
  1960. return match_getslice_by_index(self, i, def);
  1961. }
  1962. /*[clinic input]
  1963. _sre.SRE_Match.expand
  1964. template: object
  1965. Return the string obtained by doing backslash substitution on the string template, as done by the sub() method.
  1966. [clinic start generated code]*/
  1967. static PyObject *
  1968. _sre_SRE_Match_expand_impl(MatchObject *self, PyObject *template)
  1969. /*[clinic end generated code: output=931b58ccc323c3a1 input=4bfdb22c2f8b146a]*/
  1970. {
  1971. _sremodulestate *module_state = get_sre_module_state_by_class(Py_TYPE(self));
  1972. PyObject *filter = compile_template(module_state, self->pattern, template);
  1973. if (filter == NULL) {
  1974. return NULL;
  1975. }
  1976. PyObject *result = expand_template((TemplateObject *)filter, self);
  1977. Py_DECREF(filter);
  1978. return result;
  1979. }
  1980. static PyObject*
  1981. match_group(MatchObject* self, PyObject* args)
  1982. {
  1983. PyObject* result;
  1984. Py_ssize_t i, size;
  1985. size = PyTuple_GET_SIZE(args);
  1986. switch (size) {
  1987. case 0:
  1988. result = match_getslice(self, _PyLong_GetZero(), Py_None);
  1989. break;
  1990. case 1:
  1991. result = match_getslice(self, PyTuple_GET_ITEM(args, 0), Py_None);
  1992. break;
  1993. default:
  1994. /* fetch multiple items */
  1995. result = PyTuple_New(size);
  1996. if (!result)
  1997. return NULL;
  1998. for (i = 0; i < size; i++) {
  1999. PyObject* item = match_getslice(
  2000. self, PyTuple_GET_ITEM(args, i), Py_None
  2001. );
  2002. if (!item) {
  2003. Py_DECREF(result);
  2004. return NULL;
  2005. }
  2006. PyTuple_SET_ITEM(result, i, item);
  2007. }
  2008. break;
  2009. }
  2010. return result;
  2011. }
  2012. static PyObject*
  2013. match_getitem(MatchObject* self, PyObject* name)
  2014. {
  2015. return match_getslice(self, name, Py_None);
  2016. }
  2017. /*[clinic input]
  2018. _sre.SRE_Match.groups
  2019. default: object = None
  2020. Is used for groups that did not participate in the match.
  2021. Return a tuple containing all the subgroups of the match, from 1.
  2022. [clinic start generated code]*/
  2023. static PyObject *
  2024. _sre_SRE_Match_groups_impl(MatchObject *self, PyObject *default_value)
  2025. /*[clinic end generated code: output=daf8e2641537238a input=bb069ef55dabca91]*/
  2026. {
  2027. PyObject* result;
  2028. Py_ssize_t index;
  2029. result = PyTuple_New(self->groups-1);
  2030. if (!result)
  2031. return NULL;
  2032. for (index = 1; index < self->groups; index++) {
  2033. PyObject* item;
  2034. item = match_getslice_by_index(self, index, default_value);
  2035. if (!item) {
  2036. Py_DECREF(result);
  2037. return NULL;
  2038. }
  2039. PyTuple_SET_ITEM(result, index-1, item);
  2040. }
  2041. return result;
  2042. }
  2043. /*[clinic input]
  2044. _sre.SRE_Match.groupdict
  2045. default: object = None
  2046. Is used for groups that did not participate in the match.
  2047. Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
  2048. [clinic start generated code]*/
  2049. static PyObject *
  2050. _sre_SRE_Match_groupdict_impl(MatchObject *self, PyObject *default_value)
  2051. /*[clinic end generated code: output=29917c9073e41757 input=0ded7960b23780aa]*/
  2052. {
  2053. PyObject *result;
  2054. PyObject *key;
  2055. PyObject *value;
  2056. Py_ssize_t pos = 0;
  2057. Py_hash_t hash;
  2058. result = PyDict_New();
  2059. if (!result || !self->pattern->groupindex)
  2060. return result;
  2061. while (_PyDict_Next(self->pattern->groupindex, &pos, &key, &value, &hash)) {
  2062. int status;
  2063. Py_INCREF(key);
  2064. value = match_getslice(self, key, default_value);
  2065. if (!value) {
  2066. Py_DECREF(key);
  2067. goto failed;
  2068. }
  2069. status = _PyDict_SetItem_KnownHash(result, key, value, hash);
  2070. Py_DECREF(value);
  2071. Py_DECREF(key);
  2072. if (status < 0)
  2073. goto failed;
  2074. }
  2075. return result;
  2076. failed:
  2077. Py_DECREF(result);
  2078. return NULL;
  2079. }
  2080. /*[clinic input]
  2081. _sre.SRE_Match.start -> Py_ssize_t
  2082. group: object(c_default="NULL") = 0
  2083. /
  2084. Return index of the start of the substring matched by group.
  2085. [clinic start generated code]*/
  2086. static Py_ssize_t
  2087. _sre_SRE_Match_start_impl(MatchObject *self, PyObject *group)
  2088. /*[clinic end generated code: output=3f6e7f9df2fb5201 input=ced8e4ed4b33ee6c]*/
  2089. {
  2090. Py_ssize_t index = match_getindex(self, group);
  2091. if (index < 0) {
  2092. return -1;
  2093. }
  2094. /* mark is -1 if group is undefined */
  2095. return self->mark[index*2];
  2096. }
  2097. /*[clinic input]
  2098. _sre.SRE_Match.end -> Py_ssize_t
  2099. group: object(c_default="NULL") = 0
  2100. /
  2101. Return index of the end of the substring matched by group.
  2102. [clinic start generated code]*/
  2103. static Py_ssize_t
  2104. _sre_SRE_Match_end_impl(MatchObject *self, PyObject *group)
  2105. /*[clinic end generated code: output=f4240b09911f7692 input=1b799560c7f3d7e6]*/
  2106. {
  2107. Py_ssize_t index = match_getindex(self, group);
  2108. if (index < 0) {
  2109. return -1;
  2110. }
  2111. /* mark is -1 if group is undefined */
  2112. return self->mark[index*2+1];
  2113. }
  2114. LOCAL(PyObject*)
  2115. _pair(Py_ssize_t i1, Py_ssize_t i2)
  2116. {
  2117. PyObject* pair;
  2118. PyObject* item;
  2119. pair = PyTuple_New(2);
  2120. if (!pair)
  2121. return NULL;
  2122. item = PyLong_FromSsize_t(i1);
  2123. if (!item)
  2124. goto error;
  2125. PyTuple_SET_ITEM(pair, 0, item);
  2126. item = PyLong_FromSsize_t(i2);
  2127. if (!item)
  2128. goto error;
  2129. PyTuple_SET_ITEM(pair, 1, item);
  2130. return pair;
  2131. error:
  2132. Py_DECREF(pair);
  2133. return NULL;
  2134. }
  2135. /*[clinic input]
  2136. _sre.SRE_Match.span
  2137. group: object(c_default="NULL") = 0
  2138. /
  2139. For match object m, return the 2-tuple (m.start(group), m.end(group)).
  2140. [clinic start generated code]*/
  2141. static PyObject *
  2142. _sre_SRE_Match_span_impl(MatchObject *self, PyObject *group)
  2143. /*[clinic end generated code: output=f02ae40594d14fe6 input=8fa6014e982d71d4]*/
  2144. {
  2145. Py_ssize_t index = match_getindex(self, group);
  2146. if (index < 0) {
  2147. return NULL;
  2148. }
  2149. /* marks are -1 if group is undefined */
  2150. return _pair(self->mark[index*2], self->mark[index*2+1]);
  2151. }
  2152. static PyObject*
  2153. match_regs(MatchObject* self)
  2154. {
  2155. PyObject* regs;
  2156. PyObject* item;
  2157. Py_ssize_t index;
  2158. regs = PyTuple_New(self->groups);
  2159. if (!regs)
  2160. return NULL;
  2161. for (index = 0; index < self->groups; index++) {
  2162. item = _pair(self->mark[index*2], self->mark[index*2+1]);
  2163. if (!item) {
  2164. Py_DECREF(regs);
  2165. return NULL;
  2166. }
  2167. PyTuple_SET_ITEM(regs, index, item);
  2168. }
  2169. self->regs = Py_NewRef(regs);
  2170. return regs;
  2171. }
  2172. /*[clinic input]
  2173. _sre.SRE_Match.__copy__
  2174. [clinic start generated code]*/
  2175. static PyObject *
  2176. _sre_SRE_Match___copy___impl(MatchObject *self)
  2177. /*[clinic end generated code: output=a779c5fc8b5b4eb4 input=3bb4d30b6baddb5b]*/
  2178. {
  2179. return Py_NewRef(self);
  2180. }
  2181. /*[clinic input]
  2182. _sre.SRE_Match.__deepcopy__
  2183. memo: object
  2184. /
  2185. [clinic start generated code]*/
  2186. static PyObject *
  2187. _sre_SRE_Match___deepcopy__(MatchObject *self, PyObject *memo)
  2188. /*[clinic end generated code: output=ba7cb46d655e4ee2 input=779d12a31c2c325e]*/
  2189. {
  2190. return Py_NewRef(self);
  2191. }
  2192. PyDoc_STRVAR(match_doc,
  2193. "The result of re.match() and re.search().\n\
  2194. Match objects always have a boolean value of True.");
  2195. PyDoc_STRVAR(match_group_doc,
  2196. "group([group1, ...]) -> str or tuple.\n\
  2197. Return subgroup(s) of the match by indices or names.\n\
  2198. For 0 returns the entire match.");
  2199. static PyObject *
  2200. match_lastindex_get(MatchObject *self, void *Py_UNUSED(ignored))
  2201. {
  2202. if (self->lastindex >= 0)
  2203. return PyLong_FromSsize_t(self->lastindex);
  2204. Py_RETURN_NONE;
  2205. }
  2206. static PyObject *
  2207. match_lastgroup_get(MatchObject *self, void *Py_UNUSED(ignored))
  2208. {
  2209. if (self->pattern->indexgroup &&
  2210. self->lastindex >= 0 &&
  2211. self->lastindex < PyTuple_GET_SIZE(self->pattern->indexgroup))
  2212. {
  2213. PyObject *result = PyTuple_GET_ITEM(self->pattern->indexgroup,
  2214. self->lastindex);
  2215. return Py_NewRef(result);
  2216. }
  2217. Py_RETURN_NONE;
  2218. }
  2219. static PyObject *
  2220. match_regs_get(MatchObject *self, void *Py_UNUSED(ignored))
  2221. {
  2222. if (self->regs) {
  2223. return Py_NewRef(self->regs);
  2224. } else
  2225. return match_regs(self);
  2226. }
  2227. static PyObject *
  2228. match_repr(MatchObject *self)
  2229. {
  2230. PyObject *result;
  2231. PyObject *group0 = match_getslice_by_index(self, 0, Py_None);
  2232. if (group0 == NULL)
  2233. return NULL;
  2234. result = PyUnicode_FromFormat(
  2235. "<%s object; span=(%zd, %zd), match=%.50R>",
  2236. Py_TYPE(self)->tp_name,
  2237. self->mark[0], self->mark[1], group0);
  2238. Py_DECREF(group0);
  2239. return result;
  2240. }
  2241. static PyObject*
  2242. pattern_new_match(_sremodulestate* module_state,
  2243. PatternObject* pattern,
  2244. SRE_STATE* state,
  2245. Py_ssize_t status)
  2246. {
  2247. /* create match object (from state object) */
  2248. MatchObject* match;
  2249. Py_ssize_t i, j;
  2250. char* base;
  2251. int n;
  2252. if (status > 0) {
  2253. /* create match object (with room for extra group marks) */
  2254. /* coverity[ampersand_in_size] */
  2255. match = PyObject_GC_NewVar(MatchObject,
  2256. module_state->Match_Type,
  2257. 2*(pattern->groups+1));
  2258. if (!match)
  2259. return NULL;
  2260. Py_INCREF(pattern);
  2261. match->pattern = pattern;
  2262. match->string = Py_NewRef(state->string);
  2263. match->regs = NULL;
  2264. match->groups = pattern->groups+1;
  2265. /* fill in group slices */
  2266. base = (char*) state->beginning;
  2267. n = state->charsize;
  2268. match->mark[0] = ((char*) state->start - base) / n;
  2269. match->mark[1] = ((char*) state->ptr - base) / n;
  2270. for (i = j = 0; i < pattern->groups; i++, j+=2)
  2271. if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) {
  2272. match->mark[j+2] = ((char*) state->mark[j] - base) / n;
  2273. match->mark[j+3] = ((char*) state->mark[j+1] - base) / n;
  2274. /* check wrong span */
  2275. if (match->mark[j+2] > match->mark[j+3]) {
  2276. PyErr_SetString(PyExc_SystemError,
  2277. "The span of capturing group is wrong,"
  2278. " please report a bug for the re module.");
  2279. Py_DECREF(match);
  2280. return NULL;
  2281. }
  2282. } else
  2283. match->mark[j+2] = match->mark[j+3] = -1; /* undefined */
  2284. match->pos = state->pos;
  2285. match->endpos = state->endpos;
  2286. match->lastindex = state->lastindex;
  2287. PyObject_GC_Track(match);
  2288. return (PyObject*) match;
  2289. } else if (status == 0) {
  2290. /* no match */
  2291. Py_RETURN_NONE;
  2292. }
  2293. /* internal error */
  2294. pattern_error(status);
  2295. return NULL;
  2296. }
  2297. /* -------------------------------------------------------------------- */
  2298. /* scanner methods (experimental) */
  2299. static int
  2300. scanner_traverse(ScannerObject *self, visitproc visit, void *arg)
  2301. {
  2302. Py_VISIT(Py_TYPE(self));
  2303. Py_VISIT(self->pattern);
  2304. return 0;
  2305. }
  2306. static int
  2307. scanner_clear(ScannerObject *self)
  2308. {
  2309. Py_CLEAR(self->pattern);
  2310. return 0;
  2311. }
  2312. static void
  2313. scanner_dealloc(ScannerObject* self)
  2314. {
  2315. PyTypeObject *tp = Py_TYPE(self);
  2316. PyObject_GC_UnTrack(self);
  2317. state_fini(&self->state);
  2318. (void)scanner_clear(self);
  2319. tp->tp_free(self);
  2320. Py_DECREF(tp);
  2321. }
  2322. static int
  2323. scanner_begin(ScannerObject* self)
  2324. {
  2325. if (self->executing) {
  2326. PyErr_SetString(PyExc_ValueError,
  2327. "regular expression scanner already executing");
  2328. return 0;
  2329. }
  2330. self->executing = 1;
  2331. return 1;
  2332. }
  2333. static void
  2334. scanner_end(ScannerObject* self)
  2335. {
  2336. assert(self->executing);
  2337. self->executing = 0;
  2338. }
  2339. /*[clinic input]
  2340. _sre.SRE_Scanner.match
  2341. cls: defining_class
  2342. /
  2343. [clinic start generated code]*/
  2344. static PyObject *
  2345. _sre_SRE_Scanner_match_impl(ScannerObject *self, PyTypeObject *cls)
  2346. /*[clinic end generated code: output=6e22c149dc0f0325 input=b5146e1f30278cb7]*/
  2347. {
  2348. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  2349. SRE_STATE* state = &self->state;
  2350. PyObject* match;
  2351. Py_ssize_t status;
  2352. if (!scanner_begin(self)) {
  2353. return NULL;
  2354. }
  2355. if (state->start == NULL) {
  2356. scanner_end(self);
  2357. Py_RETURN_NONE;
  2358. }
  2359. state_reset(state);
  2360. state->ptr = state->start;
  2361. status = sre_match(state, PatternObject_GetCode(self->pattern));
  2362. if (PyErr_Occurred()) {
  2363. scanner_end(self);
  2364. return NULL;
  2365. }
  2366. match = pattern_new_match(module_state, self->pattern,
  2367. state, status);
  2368. if (status == 0)
  2369. state->start = NULL;
  2370. else {
  2371. state->must_advance = (state->ptr == state->start);
  2372. state->start = state->ptr;
  2373. }
  2374. scanner_end(self);
  2375. return match;
  2376. }
  2377. /*[clinic input]
  2378. _sre.SRE_Scanner.search
  2379. cls: defining_class
  2380. /
  2381. [clinic start generated code]*/
  2382. static PyObject *
  2383. _sre_SRE_Scanner_search_impl(ScannerObject *self, PyTypeObject *cls)
  2384. /*[clinic end generated code: output=23e8fc78013f9161 input=056c2d37171d0bf2]*/
  2385. {
  2386. _sremodulestate *module_state = get_sre_module_state_by_class(cls);
  2387. SRE_STATE* state = &self->state;
  2388. PyObject* match;
  2389. Py_ssize_t status;
  2390. if (!scanner_begin(self)) {
  2391. return NULL;
  2392. }
  2393. if (state->start == NULL) {
  2394. scanner_end(self);
  2395. Py_RETURN_NONE;
  2396. }
  2397. state_reset(state);
  2398. state->ptr = state->start;
  2399. status = sre_search(state, PatternObject_GetCode(self->pattern));
  2400. if (PyErr_Occurred()) {
  2401. scanner_end(self);
  2402. return NULL;
  2403. }
  2404. match = pattern_new_match(module_state, self->pattern,
  2405. state, status);
  2406. if (status == 0)
  2407. state->start = NULL;
  2408. else {
  2409. state->must_advance = (state->ptr == state->start);
  2410. state->start = state->ptr;
  2411. }
  2412. scanner_end(self);
  2413. return match;
  2414. }
  2415. static PyObject *
  2416. pattern_scanner(_sremodulestate *module_state,
  2417. PatternObject *self,
  2418. PyObject *string,
  2419. Py_ssize_t pos,
  2420. Py_ssize_t endpos)
  2421. {
  2422. ScannerObject* scanner;
  2423. /* create scanner object */
  2424. scanner = PyObject_GC_New(ScannerObject, module_state->Scanner_Type);
  2425. if (!scanner)
  2426. return NULL;
  2427. scanner->pattern = NULL;
  2428. scanner->executing = 0;
  2429. /* create search state object */
  2430. if (!state_init(&scanner->state, self, string, pos, endpos)) {
  2431. Py_DECREF(scanner);
  2432. return NULL;
  2433. }
  2434. Py_INCREF(self);
  2435. scanner->pattern = self;
  2436. PyObject_GC_Track(scanner);
  2437. return (PyObject*) scanner;
  2438. }
  2439. /* -------------------------------------------------------------------- */
  2440. /* template methods */
  2441. static int
  2442. template_traverse(TemplateObject *self, visitproc visit, void *arg)
  2443. {
  2444. Py_VISIT(Py_TYPE(self));
  2445. Py_VISIT(self->literal);
  2446. for (Py_ssize_t i = 0, n = Py_SIZE(self); i < n; i++) {
  2447. Py_VISIT(self->items[i].literal);
  2448. }
  2449. return 0;
  2450. }
  2451. static int
  2452. template_clear(TemplateObject *self)
  2453. {
  2454. Py_CLEAR(self->literal);
  2455. for (Py_ssize_t i = 0, n = Py_SIZE(self); i < n; i++) {
  2456. Py_CLEAR(self->items[i].literal);
  2457. }
  2458. return 0;
  2459. }
  2460. static void
  2461. template_dealloc(TemplateObject *self)
  2462. {
  2463. PyTypeObject *tp = Py_TYPE(self);
  2464. PyObject_GC_UnTrack(self);
  2465. (void)template_clear(self);
  2466. tp->tp_free(self);
  2467. Py_DECREF(tp);
  2468. }
  2469. static PyObject *
  2470. expand_template(TemplateObject *self, MatchObject *match)
  2471. {
  2472. if (Py_SIZE(self) == 0) {
  2473. return Py_NewRef(self->literal);
  2474. }
  2475. PyObject *result = NULL;
  2476. Py_ssize_t count = 0; // the number of non-empty chunks
  2477. /* For small number of strings use a buffer allocated on the stack,
  2478. * otherwise use a list object. */
  2479. PyObject *buffer[10];
  2480. PyObject **out = buffer;
  2481. PyObject *list = NULL;
  2482. if (self->chunks > (int)Py_ARRAY_LENGTH(buffer) ||
  2483. !PyUnicode_Check(self->literal))
  2484. {
  2485. list = PyList_New(self->chunks);
  2486. if (!list) {
  2487. return NULL;
  2488. }
  2489. out = &PyList_GET_ITEM(list, 0);
  2490. }
  2491. out[count++] = Py_NewRef(self->literal);
  2492. for (Py_ssize_t i = 0; i < Py_SIZE(self); i++) {
  2493. Py_ssize_t index = self->items[i].index;
  2494. if (index >= match->groups) {
  2495. PyErr_SetString(PyExc_IndexError, "no such group");
  2496. goto cleanup;
  2497. }
  2498. PyObject *item = match_getslice_by_index(match, index, Py_None);
  2499. if (item == NULL) {
  2500. goto cleanup;
  2501. }
  2502. if (item != Py_None) {
  2503. out[count++] = Py_NewRef(item);
  2504. }
  2505. Py_DECREF(item);
  2506. PyObject *literal = self->items[i].literal;
  2507. if (literal != NULL) {
  2508. out[count++] = Py_NewRef(literal);
  2509. }
  2510. }
  2511. if (PyUnicode_Check(self->literal)) {
  2512. result = _PyUnicode_JoinArray(&_Py_STR(empty), out, count);
  2513. }
  2514. else {
  2515. Py_SET_SIZE(list, count);
  2516. result = _PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), list);
  2517. }
  2518. cleanup:
  2519. if (list) {
  2520. Py_DECREF(list);
  2521. }
  2522. else {
  2523. for (Py_ssize_t i = 0; i < count; i++) {
  2524. Py_DECREF(out[i]);
  2525. }
  2526. }
  2527. return result;
  2528. }
  2529. static Py_hash_t
  2530. pattern_hash(PatternObject *self)
  2531. {
  2532. Py_hash_t hash, hash2;
  2533. hash = PyObject_Hash(self->pattern);
  2534. if (hash == -1) {
  2535. return -1;
  2536. }
  2537. hash2 = _Py_HashBytes(self->code, sizeof(self->code[0]) * self->codesize);
  2538. hash ^= hash2;
  2539. hash ^= self->flags;
  2540. hash ^= self->isbytes;
  2541. hash ^= self->codesize;
  2542. if (hash == -1) {
  2543. hash = -2;
  2544. }
  2545. return hash;
  2546. }
  2547. static PyObject*
  2548. pattern_richcompare(PyObject *lefto, PyObject *righto, int op)
  2549. {
  2550. PyTypeObject *tp = Py_TYPE(lefto);
  2551. _sremodulestate *module_state = get_sre_module_state_by_class(tp);
  2552. PatternObject *left, *right;
  2553. int cmp;
  2554. if (op != Py_EQ && op != Py_NE) {
  2555. Py_RETURN_NOTIMPLEMENTED;
  2556. }
  2557. if (!Py_IS_TYPE(righto, module_state->Pattern_Type))
  2558. {
  2559. Py_RETURN_NOTIMPLEMENTED;
  2560. }
  2561. if (lefto == righto) {
  2562. /* a pattern is equal to itself */
  2563. return PyBool_FromLong(op == Py_EQ);
  2564. }
  2565. left = (PatternObject *)lefto;
  2566. right = (PatternObject *)righto;
  2567. cmp = (left->flags == right->flags
  2568. && left->isbytes == right->isbytes
  2569. && left->codesize == right->codesize);
  2570. if (cmp) {
  2571. /* Compare the code and the pattern because the same pattern can
  2572. produce different codes depending on the locale used to compile the
  2573. pattern when the re.LOCALE flag is used. Don't compare groups,
  2574. indexgroup nor groupindex: they are derivated from the pattern. */
  2575. cmp = (memcmp(left->code, right->code,
  2576. sizeof(left->code[0]) * left->codesize) == 0);
  2577. }
  2578. if (cmp) {
  2579. cmp = PyObject_RichCompareBool(left->pattern, right->pattern,
  2580. Py_EQ);
  2581. if (cmp < 0) {
  2582. return NULL;
  2583. }
  2584. }
  2585. if (op == Py_NE) {
  2586. cmp = !cmp;
  2587. }
  2588. return PyBool_FromLong(cmp);
  2589. }
  2590. #include "clinic/sre.c.h"
  2591. static PyMethodDef pattern_methods[] = {
  2592. _SRE_SRE_PATTERN_MATCH_METHODDEF
  2593. _SRE_SRE_PATTERN_FULLMATCH_METHODDEF
  2594. _SRE_SRE_PATTERN_SEARCH_METHODDEF
  2595. _SRE_SRE_PATTERN_SUB_METHODDEF
  2596. _SRE_SRE_PATTERN_SUBN_METHODDEF
  2597. _SRE_SRE_PATTERN_FINDALL_METHODDEF
  2598. _SRE_SRE_PATTERN_SPLIT_METHODDEF
  2599. _SRE_SRE_PATTERN_FINDITER_METHODDEF
  2600. _SRE_SRE_PATTERN_SCANNER_METHODDEF
  2601. _SRE_SRE_PATTERN___COPY___METHODDEF
  2602. _SRE_SRE_PATTERN___DEEPCOPY___METHODDEF
  2603. _SRE_SRE_PATTERN__FAIL_AFTER_METHODDEF
  2604. {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
  2605. PyDoc_STR("See PEP 585")},
  2606. {NULL, NULL}
  2607. };
  2608. static PyGetSetDef pattern_getset[] = {
  2609. {"groupindex", (getter)pattern_groupindex, (setter)NULL,
  2610. "A dictionary mapping group names to group numbers."},
  2611. {NULL} /* Sentinel */
  2612. };
  2613. #define PAT_OFF(x) offsetof(PatternObject, x)
  2614. static PyMemberDef pattern_members[] = {
  2615. {"pattern", T_OBJECT, PAT_OFF(pattern), READONLY,
  2616. "The pattern string from which the RE object was compiled."},
  2617. {"flags", T_INT, PAT_OFF(flags), READONLY,
  2618. "The regex matching flags."},
  2619. {"groups", T_PYSSIZET, PAT_OFF(groups), READONLY,
  2620. "The number of capturing groups in the pattern."},
  2621. {"__weaklistoffset__", T_PYSSIZET, offsetof(PatternObject, weakreflist), READONLY},
  2622. {NULL} /* Sentinel */
  2623. };
  2624. static PyType_Slot pattern_slots[] = {
  2625. {Py_tp_dealloc, (destructor)pattern_dealloc},
  2626. {Py_tp_repr, (reprfunc)pattern_repr},
  2627. {Py_tp_hash, (hashfunc)pattern_hash},
  2628. {Py_tp_doc, (void *)pattern_doc},
  2629. {Py_tp_richcompare, pattern_richcompare},
  2630. {Py_tp_methods, pattern_methods},
  2631. {Py_tp_members, pattern_members},
  2632. {Py_tp_getset, pattern_getset},
  2633. {Py_tp_traverse, pattern_traverse},
  2634. {Py_tp_clear, pattern_clear},
  2635. {0, NULL},
  2636. };
  2637. static PyType_Spec pattern_spec = {
  2638. .name = "re.Pattern",
  2639. .basicsize = sizeof(PatternObject),
  2640. .itemsize = sizeof(SRE_CODE),
  2641. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
  2642. Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
  2643. .slots = pattern_slots,
  2644. };
  2645. static PyMethodDef match_methods[] = {
  2646. {"group", (PyCFunction) match_group, METH_VARARGS, match_group_doc},
  2647. _SRE_SRE_MATCH_START_METHODDEF
  2648. _SRE_SRE_MATCH_END_METHODDEF
  2649. _SRE_SRE_MATCH_SPAN_METHODDEF
  2650. _SRE_SRE_MATCH_GROUPS_METHODDEF
  2651. _SRE_SRE_MATCH_GROUPDICT_METHODDEF
  2652. _SRE_SRE_MATCH_EXPAND_METHODDEF
  2653. _SRE_SRE_MATCH___COPY___METHODDEF
  2654. _SRE_SRE_MATCH___DEEPCOPY___METHODDEF
  2655. {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
  2656. PyDoc_STR("See PEP 585")},
  2657. {NULL, NULL}
  2658. };
  2659. static PyGetSetDef match_getset[] = {
  2660. {"lastindex", (getter)match_lastindex_get, (setter)NULL,
  2661. "The integer index of the last matched capturing group."},
  2662. {"lastgroup", (getter)match_lastgroup_get, (setter)NULL,
  2663. "The name of the last matched capturing group."},
  2664. {"regs", (getter)match_regs_get, (setter)NULL},
  2665. {NULL}
  2666. };
  2667. #define MATCH_OFF(x) offsetof(MatchObject, x)
  2668. static PyMemberDef match_members[] = {
  2669. {"string", T_OBJECT, MATCH_OFF(string), READONLY,
  2670. "The string passed to match() or search()."},
  2671. {"re", T_OBJECT, MATCH_OFF(pattern), READONLY,
  2672. "The regular expression object."},
  2673. {"pos", T_PYSSIZET, MATCH_OFF(pos), READONLY,
  2674. "The index into the string at which the RE engine started looking for a match."},
  2675. {"endpos", T_PYSSIZET, MATCH_OFF(endpos), READONLY,
  2676. "The index into the string beyond which the RE engine will not go."},
  2677. {NULL}
  2678. };
  2679. /* FIXME: implement setattr("string", None) as a special case (to
  2680. detach the associated string, if any */
  2681. static PyType_Slot match_slots[] = {
  2682. {Py_tp_dealloc, match_dealloc},
  2683. {Py_tp_repr, match_repr},
  2684. {Py_tp_doc, (void *)match_doc},
  2685. {Py_tp_methods, match_methods},
  2686. {Py_tp_members, match_members},
  2687. {Py_tp_getset, match_getset},
  2688. {Py_tp_traverse, match_traverse},
  2689. {Py_tp_clear, match_clear},
  2690. /* As mapping.
  2691. *
  2692. * Match objects do not support length or assignment, but do support
  2693. * __getitem__.
  2694. */
  2695. {Py_mp_subscript, match_getitem},
  2696. {0, NULL},
  2697. };
  2698. static PyType_Spec match_spec = {
  2699. .name = "re.Match",
  2700. .basicsize = sizeof(MatchObject),
  2701. .itemsize = sizeof(Py_ssize_t),
  2702. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
  2703. Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
  2704. .slots = match_slots,
  2705. };
  2706. static PyMethodDef scanner_methods[] = {
  2707. _SRE_SRE_SCANNER_MATCH_METHODDEF
  2708. _SRE_SRE_SCANNER_SEARCH_METHODDEF
  2709. {NULL, NULL}
  2710. };
  2711. #define SCAN_OFF(x) offsetof(ScannerObject, x)
  2712. static PyMemberDef scanner_members[] = {
  2713. {"pattern", T_OBJECT, SCAN_OFF(pattern), READONLY},
  2714. {NULL} /* Sentinel */
  2715. };
  2716. static PyType_Slot scanner_slots[] = {
  2717. {Py_tp_dealloc, scanner_dealloc},
  2718. {Py_tp_methods, scanner_methods},
  2719. {Py_tp_members, scanner_members},
  2720. {Py_tp_traverse, scanner_traverse},
  2721. {Py_tp_clear, scanner_clear},
  2722. {0, NULL},
  2723. };
  2724. static PyType_Spec scanner_spec = {
  2725. .name = "_sre.SRE_Scanner",
  2726. .basicsize = sizeof(ScannerObject),
  2727. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
  2728. Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
  2729. .slots = scanner_slots,
  2730. };
  2731. static PyType_Slot template_slots[] = {
  2732. {Py_tp_dealloc, template_dealloc},
  2733. {Py_tp_traverse, template_traverse},
  2734. {Py_tp_clear, template_clear},
  2735. {0, NULL},
  2736. };
  2737. static PyType_Spec template_spec = {
  2738. .name = "_sre.SRE_Template",
  2739. .basicsize = sizeof(TemplateObject),
  2740. .itemsize = sizeof(((TemplateObject *)0)->items[0]),
  2741. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
  2742. Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_HAVE_GC),
  2743. .slots = template_slots,
  2744. };
  2745. static PyMethodDef _functions[] = {
  2746. _SRE_COMPILE_METHODDEF
  2747. _SRE_TEMPLATE_METHODDEF
  2748. _SRE_GETCODESIZE_METHODDEF
  2749. _SRE_ASCII_ISCASED_METHODDEF
  2750. _SRE_UNICODE_ISCASED_METHODDEF
  2751. _SRE_ASCII_TOLOWER_METHODDEF
  2752. _SRE_UNICODE_TOLOWER_METHODDEF
  2753. {NULL, NULL}
  2754. };
  2755. static int
  2756. sre_traverse(PyObject *module, visitproc visit, void *arg)
  2757. {
  2758. _sremodulestate *state = get_sre_module_state(module);
  2759. Py_VISIT(state->Pattern_Type);
  2760. Py_VISIT(state->Match_Type);
  2761. Py_VISIT(state->Scanner_Type);
  2762. Py_VISIT(state->Template_Type);
  2763. Py_VISIT(state->compile_template);
  2764. return 0;
  2765. }
  2766. static int
  2767. sre_clear(PyObject *module)
  2768. {
  2769. _sremodulestate *state = get_sre_module_state(module);
  2770. Py_CLEAR(state->Pattern_Type);
  2771. Py_CLEAR(state->Match_Type);
  2772. Py_CLEAR(state->Scanner_Type);
  2773. Py_CLEAR(state->Template_Type);
  2774. Py_CLEAR(state->compile_template);
  2775. return 0;
  2776. }
  2777. static void
  2778. sre_free(void *module)
  2779. {
  2780. sre_clear((PyObject *)module);
  2781. }
  2782. #define CREATE_TYPE(m, type, spec) \
  2783. do { \
  2784. type = (PyTypeObject *)PyType_FromModuleAndSpec(m, spec, NULL); \
  2785. if (type == NULL) { \
  2786. goto error; \
  2787. } \
  2788. } while (0)
  2789. #define ADD_ULONG_CONSTANT(module, name, value) \
  2790. do { \
  2791. PyObject *o = PyLong_FromUnsignedLong(value); \
  2792. if (!o) \
  2793. goto error; \
  2794. int res = PyModule_AddObjectRef(module, name, o); \
  2795. Py_DECREF(o); \
  2796. if (res < 0) { \
  2797. goto error; \
  2798. } \
  2799. } while (0)
  2800. static int
  2801. sre_exec(PyObject *m)
  2802. {
  2803. _sremodulestate *state;
  2804. /* Create heap types */
  2805. state = get_sre_module_state(m);
  2806. CREATE_TYPE(m, state->Pattern_Type, &pattern_spec);
  2807. CREATE_TYPE(m, state->Match_Type, &match_spec);
  2808. CREATE_TYPE(m, state->Scanner_Type, &scanner_spec);
  2809. CREATE_TYPE(m, state->Template_Type, &template_spec);
  2810. if (PyModule_AddIntConstant(m, "MAGIC", SRE_MAGIC) < 0) {
  2811. goto error;
  2812. }
  2813. if (PyModule_AddIntConstant(m, "CODESIZE", sizeof(SRE_CODE)) < 0) {
  2814. goto error;
  2815. }
  2816. ADD_ULONG_CONSTANT(m, "MAXREPEAT", SRE_MAXREPEAT);
  2817. ADD_ULONG_CONSTANT(m, "MAXGROUPS", SRE_MAXGROUPS);
  2818. if (PyModule_AddStringConstant(m, "copyright", copyright) < 0) {
  2819. goto error;
  2820. }
  2821. return 0;
  2822. error:
  2823. return -1;
  2824. }
  2825. static PyModuleDef_Slot sre_slots[] = {
  2826. {Py_mod_exec, sre_exec},
  2827. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  2828. {0, NULL},
  2829. };
  2830. static struct PyModuleDef sremodule = {
  2831. .m_base = PyModuleDef_HEAD_INIT,
  2832. .m_name = "_sre",
  2833. .m_size = sizeof(_sremodulestate),
  2834. .m_methods = _functions,
  2835. .m_slots = sre_slots,
  2836. .m_traverse = sre_traverse,
  2837. .m_free = sre_free,
  2838. .m_clear = sre_clear,
  2839. };
  2840. PyMODINIT_FUNC
  2841. PyInit__sre(void)
  2842. {
  2843. return PyModuleDef_Init(&sremodule);
  2844. }
  2845. /* vim:ts=4:sw=4:et
  2846. */