regcomp.c 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922
  1. /* Extended regular expression matching and search library.
  2. Copyright (C) 2002-2013 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public
  7. License as published by the Free Software Foundation; either
  8. version 3 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. static reg_errcode_t re_compile_internal (regex_t *preg, const char * pattern,
  17. size_t length, reg_syntax_t syntax);
  18. static void re_compile_fastmap_iter (regex_t *bufp,
  19. const re_dfastate_t *init_state,
  20. char *fastmap);
  21. static reg_errcode_t init_dfa (re_dfa_t *dfa, size_t pat_len);
  22. #ifdef RE_ENABLE_I18N
  23. static void free_charset (re_charset_t *cset);
  24. #endif /* RE_ENABLE_I18N */
  25. static void free_workarea_compile (regex_t *preg);
  26. static reg_errcode_t create_initial_state (re_dfa_t *dfa);
  27. #ifdef RE_ENABLE_I18N
  28. static void optimize_utf8 (re_dfa_t *dfa);
  29. #endif
  30. static reg_errcode_t analyze (regex_t *preg);
  31. static reg_errcode_t preorder (bin_tree_t *root,
  32. reg_errcode_t (fn (void *, bin_tree_t *)),
  33. void *extra);
  34. static reg_errcode_t postorder (bin_tree_t *root,
  35. reg_errcode_t (fn (void *, bin_tree_t *)),
  36. void *extra);
  37. static reg_errcode_t optimize_subexps (void *extra, bin_tree_t *node);
  38. static reg_errcode_t lower_subexps (void *extra, bin_tree_t *node);
  39. static bin_tree_t *lower_subexp (reg_errcode_t *err, regex_t *preg,
  40. bin_tree_t *node);
  41. static reg_errcode_t calc_first (void *extra, bin_tree_t *node);
  42. static reg_errcode_t calc_next (void *extra, bin_tree_t *node);
  43. static reg_errcode_t link_nfa_nodes (void *extra, bin_tree_t *node);
  44. static Idx duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint);
  45. static Idx search_duplicated_node (const re_dfa_t *dfa, Idx org_node,
  46. unsigned int constraint);
  47. static reg_errcode_t calc_eclosure (re_dfa_t *dfa);
  48. static reg_errcode_t calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa,
  49. Idx node, bool root);
  50. static reg_errcode_t calc_inveclosure (re_dfa_t *dfa);
  51. static Idx fetch_number (re_string_t *input, re_token_t *token,
  52. reg_syntax_t syntax);
  53. static int peek_token (re_token_t *token, re_string_t *input,
  54. reg_syntax_t syntax) internal_function;
  55. static bin_tree_t *parse (re_string_t *regexp, regex_t *preg,
  56. reg_syntax_t syntax, reg_errcode_t *err);
  57. static bin_tree_t *parse_reg_exp (re_string_t *regexp, regex_t *preg,
  58. re_token_t *token, reg_syntax_t syntax,
  59. Idx nest, reg_errcode_t *err);
  60. static bin_tree_t *parse_branch (re_string_t *regexp, regex_t *preg,
  61. re_token_t *token, reg_syntax_t syntax,
  62. Idx nest, reg_errcode_t *err);
  63. static bin_tree_t *parse_expression (re_string_t *regexp, regex_t *preg,
  64. re_token_t *token, reg_syntax_t syntax,
  65. Idx nest, reg_errcode_t *err);
  66. static bin_tree_t *parse_sub_exp (re_string_t *regexp, regex_t *preg,
  67. re_token_t *token, reg_syntax_t syntax,
  68. Idx nest, reg_errcode_t *err);
  69. static bin_tree_t *parse_dup_op (bin_tree_t *dup_elem, re_string_t *regexp,
  70. re_dfa_t *dfa, re_token_t *token,
  71. reg_syntax_t syntax, reg_errcode_t *err);
  72. static bin_tree_t *parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa,
  73. re_token_t *token, reg_syntax_t syntax,
  74. reg_errcode_t *err);
  75. static reg_errcode_t parse_bracket_element (bracket_elem_t *elem,
  76. re_string_t *regexp,
  77. re_token_t *token, int token_len,
  78. re_dfa_t *dfa,
  79. reg_syntax_t syntax,
  80. bool accept_hyphen);
  81. static reg_errcode_t parse_bracket_symbol (bracket_elem_t *elem,
  82. re_string_t *regexp,
  83. re_token_t *token);
  84. #ifdef RE_ENABLE_I18N
  85. static reg_errcode_t build_equiv_class (bitset_t sbcset,
  86. re_charset_t *mbcset,
  87. Idx *equiv_class_alloc,
  88. const unsigned char *name);
  89. static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
  90. bitset_t sbcset,
  91. re_charset_t *mbcset,
  92. Idx *char_class_alloc,
  93. const char *class_name,
  94. reg_syntax_t syntax);
  95. #else /* not RE_ENABLE_I18N */
  96. static reg_errcode_t build_equiv_class (bitset_t sbcset,
  97. const unsigned char *name);
  98. static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
  99. bitset_t sbcset,
  100. const char *class_name,
  101. reg_syntax_t syntax);
  102. #endif /* not RE_ENABLE_I18N */
  103. static bin_tree_t *build_charclass_op (re_dfa_t *dfa,
  104. RE_TRANSLATE_TYPE trans,
  105. const char *class_name,
  106. const char *extra,
  107. bool non_match, reg_errcode_t *err);
  108. static bin_tree_t *create_tree (re_dfa_t *dfa,
  109. bin_tree_t *left, bin_tree_t *right,
  110. re_token_type_t type);
  111. static bin_tree_t *create_token_tree (re_dfa_t *dfa,
  112. bin_tree_t *left, bin_tree_t *right,
  113. const re_token_t *token);
  114. static bin_tree_t *duplicate_tree (const bin_tree_t *src, re_dfa_t *dfa);
  115. static void free_token (re_token_t *node);
  116. static reg_errcode_t free_tree (void *extra, bin_tree_t *node);
  117. static reg_errcode_t mark_opt_subexp (void *extra, bin_tree_t *node);
  118. /* This table gives an error message for each of the error codes listed
  119. in regex.h. Obviously the order here has to be same as there.
  120. POSIX doesn't require that we do anything for REG_NOERROR,
  121. but why not be nice? */
  122. static const char __re_error_msgid[] =
  123. {
  124. #define REG_NOERROR_IDX 0
  125. gettext_noop ("Success") /* REG_NOERROR */
  126. "\0"
  127. #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
  128. gettext_noop ("No match") /* REG_NOMATCH */
  129. "\0"
  130. #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
  131. gettext_noop ("Invalid regular expression") /* REG_BADPAT */
  132. "\0"
  133. #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
  134. gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
  135. "\0"
  136. #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
  137. gettext_noop ("Invalid character class name") /* REG_ECTYPE */
  138. "\0"
  139. #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
  140. gettext_noop ("Trailing backslash") /* REG_EESCAPE */
  141. "\0"
  142. #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
  143. gettext_noop ("Invalid back reference") /* REG_ESUBREG */
  144. "\0"
  145. #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
  146. gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
  147. "\0"
  148. #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
  149. gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
  150. "\0"
  151. #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
  152. gettext_noop ("Unmatched \\{") /* REG_EBRACE */
  153. "\0"
  154. #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
  155. gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
  156. "\0"
  157. #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
  158. gettext_noop ("Invalid range end") /* REG_ERANGE */
  159. "\0"
  160. #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
  161. gettext_noop ("Memory exhausted") /* REG_ESPACE */
  162. "\0"
  163. #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
  164. gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
  165. "\0"
  166. #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
  167. gettext_noop ("Premature end of regular expression") /* REG_EEND */
  168. "\0"
  169. #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
  170. gettext_noop ("Regular expression too big") /* REG_ESIZE */
  171. "\0"
  172. #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
  173. gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
  174. };
  175. static const size_t __re_error_msgid_idx[] =
  176. {
  177. REG_NOERROR_IDX,
  178. REG_NOMATCH_IDX,
  179. REG_BADPAT_IDX,
  180. REG_ECOLLATE_IDX,
  181. REG_ECTYPE_IDX,
  182. REG_EESCAPE_IDX,
  183. REG_ESUBREG_IDX,
  184. REG_EBRACK_IDX,
  185. REG_EPAREN_IDX,
  186. REG_EBRACE_IDX,
  187. REG_BADBR_IDX,
  188. REG_ERANGE_IDX,
  189. REG_ESPACE_IDX,
  190. REG_BADRPT_IDX,
  191. REG_EEND_IDX,
  192. REG_ESIZE_IDX,
  193. REG_ERPAREN_IDX
  194. };
  195. /* Entry points for GNU code. */
  196. /* re_compile_pattern is the GNU regular expression compiler: it
  197. compiles PATTERN (of length LENGTH) and puts the result in BUFP.
  198. Returns 0 if the pattern was valid, otherwise an error string.
  199. Assumes the 'allocated' (and perhaps 'buffer') and 'translate' fields
  200. are set in BUFP on entry. */
  201. #ifdef _LIBC
  202. const char *
  203. re_compile_pattern (pattern, length, bufp)
  204. const char *pattern;
  205. size_t length;
  206. struct re_pattern_buffer *bufp;
  207. #else /* size_t might promote */
  208. const char *
  209. re_compile_pattern (const char *pattern, size_t length,
  210. struct re_pattern_buffer *bufp)
  211. #endif
  212. {
  213. reg_errcode_t ret;
  214. /* And GNU code determines whether or not to get register information
  215. by passing null for the REGS argument to re_match, etc., not by
  216. setting no_sub, unless RE_NO_SUB is set. */
  217. bufp->no_sub = !!(re_syntax_options & RE_NO_SUB);
  218. /* Match anchors at newline. */
  219. bufp->newline_anchor = 1;
  220. ret = re_compile_internal (bufp, pattern, length, re_syntax_options);
  221. if (!ret)
  222. return NULL;
  223. return gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
  224. }
  225. #ifdef _LIBC
  226. weak_alias (__re_compile_pattern, re_compile_pattern)
  227. #endif
  228. /* Set by 're_set_syntax' to the current regexp syntax to recognize. Can
  229. also be assigned to arbitrarily: each pattern buffer stores its own
  230. syntax, so it can be changed between regex compilations. */
  231. /* This has no initializer because initialized variables in Emacs
  232. become read-only after dumping. */
  233. reg_syntax_t re_syntax_options;
  234. /* Specify the precise syntax of regexps for compilation. This provides
  235. for compatibility for various utilities which historically have
  236. different, incompatible syntaxes.
  237. The argument SYNTAX is a bit mask comprised of the various bits
  238. defined in regex.h. We return the old syntax. */
  239. reg_syntax_t
  240. re_set_syntax (syntax)
  241. reg_syntax_t syntax;
  242. {
  243. reg_syntax_t ret = re_syntax_options;
  244. re_syntax_options = syntax;
  245. return ret;
  246. }
  247. #ifdef _LIBC
  248. weak_alias (__re_set_syntax, re_set_syntax)
  249. #endif
  250. int
  251. re_compile_fastmap (bufp)
  252. struct re_pattern_buffer *bufp;
  253. {
  254. re_dfa_t *dfa = bufp->buffer;
  255. char *fastmap = bufp->fastmap;
  256. memset (fastmap, '\0', sizeof (char) * SBC_MAX);
  257. re_compile_fastmap_iter (bufp, dfa->init_state, fastmap);
  258. if (dfa->init_state != dfa->init_state_word)
  259. re_compile_fastmap_iter (bufp, dfa->init_state_word, fastmap);
  260. if (dfa->init_state != dfa->init_state_nl)
  261. re_compile_fastmap_iter (bufp, dfa->init_state_nl, fastmap);
  262. if (dfa->init_state != dfa->init_state_begbuf)
  263. re_compile_fastmap_iter (bufp, dfa->init_state_begbuf, fastmap);
  264. bufp->fastmap_accurate = 1;
  265. return 0;
  266. }
  267. #ifdef _LIBC
  268. weak_alias (__re_compile_fastmap, re_compile_fastmap)
  269. #endif
  270. static inline void
  271. __attribute__ ((always_inline))
  272. re_set_fastmap (char *fastmap, bool icase, int ch)
  273. {
  274. fastmap[ch] = 1;
  275. if (icase)
  276. fastmap[tolower (ch)] = 1;
  277. }
  278. /* Helper function for re_compile_fastmap.
  279. Compile fastmap for the initial_state INIT_STATE. */
  280. static void
  281. re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state,
  282. char *fastmap)
  283. {
  284. re_dfa_t *dfa = bufp->buffer;
  285. Idx node_cnt;
  286. bool icase = (dfa->mb_cur_max == 1 && (bufp->syntax & RE_ICASE));
  287. for (node_cnt = 0; node_cnt < init_state->nodes.nelem; ++node_cnt)
  288. {
  289. Idx node = init_state->nodes.elems[node_cnt];
  290. re_token_type_t type = dfa->nodes[node].type;
  291. if (type == CHARACTER)
  292. {
  293. re_set_fastmap (fastmap, icase, dfa->nodes[node].opr.c);
  294. #ifdef RE_ENABLE_I18N
  295. if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
  296. {
  297. unsigned char buf[MB_LEN_MAX];
  298. unsigned char *p;
  299. wchar_t wc;
  300. mbstate_t state;
  301. p = buf;
  302. *p++ = dfa->nodes[node].opr.c;
  303. while (++node < dfa->nodes_len
  304. && dfa->nodes[node].type == CHARACTER
  305. && dfa->nodes[node].mb_partial)
  306. *p++ = dfa->nodes[node].opr.c;
  307. memset (&state, '\0', sizeof (state));
  308. if (__mbrtowc (&wc, (const char *) buf, p - buf,
  309. &state) == p - buf
  310. && (__wcrtomb ((char *) buf, towlower (wc), &state)
  311. != (size_t) -1))
  312. re_set_fastmap (fastmap, false, buf[0]);
  313. }
  314. #endif
  315. }
  316. else if (type == SIMPLE_BRACKET)
  317. {
  318. int i, ch;
  319. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  320. {
  321. int j;
  322. bitset_word_t w = dfa->nodes[node].opr.sbcset[i];
  323. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  324. if (w & ((bitset_word_t) 1 << j))
  325. re_set_fastmap (fastmap, icase, ch);
  326. }
  327. }
  328. #ifdef RE_ENABLE_I18N
  329. else if (type == COMPLEX_BRACKET)
  330. {
  331. re_charset_t *cset = dfa->nodes[node].opr.mbcset;
  332. Idx i;
  333. # ifdef _LIBC
  334. /* See if we have to try all bytes which start multiple collation
  335. elements.
  336. e.g. In da_DK, we want to catch 'a' since "aa" is a valid
  337. collation element, and don't catch 'b' since 'b' is
  338. the only collation element which starts from 'b' (and
  339. it is caught by SIMPLE_BRACKET). */
  340. if (_NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES) != 0
  341. && (cset->ncoll_syms || cset->nranges))
  342. {
  343. const int32_t *table = (const int32_t *)
  344. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  345. for (i = 0; i < SBC_MAX; ++i)
  346. if (table[i] < 0)
  347. re_set_fastmap (fastmap, icase, i);
  348. }
  349. # endif /* _LIBC */
  350. /* See if we have to start the match at all multibyte characters,
  351. i.e. where we would not find an invalid sequence. This only
  352. applies to multibyte character sets; for single byte character
  353. sets, the SIMPLE_BRACKET again suffices. */
  354. if (dfa->mb_cur_max > 1
  355. && (cset->nchar_classes || cset->non_match || cset->nranges
  356. # ifdef _LIBC
  357. || cset->nequiv_classes
  358. # endif /* _LIBC */
  359. ))
  360. {
  361. unsigned char c = 0;
  362. do
  363. {
  364. mbstate_t mbs;
  365. memset (&mbs, 0, sizeof (mbs));
  366. if (__mbrtowc (NULL, (char *) &c, 1, &mbs) == (size_t) -2)
  367. re_set_fastmap (fastmap, false, (int) c);
  368. }
  369. while (++c != 0);
  370. }
  371. else
  372. {
  373. /* ... Else catch all bytes which can start the mbchars. */
  374. for (i = 0; i < cset->nmbchars; ++i)
  375. {
  376. char buf[256];
  377. mbstate_t state;
  378. memset (&state, '\0', sizeof (state));
  379. if (__wcrtomb (buf, cset->mbchars[i], &state) != (size_t) -1)
  380. re_set_fastmap (fastmap, icase, *(unsigned char *) buf);
  381. if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
  382. {
  383. if (__wcrtomb (buf, towlower (cset->mbchars[i]), &state)
  384. != (size_t) -1)
  385. re_set_fastmap (fastmap, false, *(unsigned char *) buf);
  386. }
  387. }
  388. }
  389. }
  390. #endif /* RE_ENABLE_I18N */
  391. else if (type == OP_PERIOD
  392. #ifdef RE_ENABLE_I18N
  393. || type == OP_UTF8_PERIOD
  394. #endif /* RE_ENABLE_I18N */
  395. || type == END_OF_RE)
  396. {
  397. memset (fastmap, '\1', sizeof (char) * SBC_MAX);
  398. if (type == END_OF_RE)
  399. bufp->can_be_null = 1;
  400. return;
  401. }
  402. }
  403. }
  404. /* Entry point for POSIX code. */
  405. /* regcomp takes a regular expression as a string and compiles it.
  406. PREG is a regex_t *. We do not expect any fields to be initialized,
  407. since POSIX says we shouldn't. Thus, we set
  408. 'buffer' to the compiled pattern;
  409. 'used' to the length of the compiled pattern;
  410. 'syntax' to RE_SYNTAX_POSIX_EXTENDED if the
  411. REG_EXTENDED bit in CFLAGS is set; otherwise, to
  412. RE_SYNTAX_POSIX_BASIC;
  413. 'newline_anchor' to REG_NEWLINE being set in CFLAGS;
  414. 'fastmap' to an allocated space for the fastmap;
  415. 'fastmap_accurate' to zero;
  416. 're_nsub' to the number of subexpressions in PATTERN.
  417. PATTERN is the address of the pattern string.
  418. CFLAGS is a series of bits which affect compilation.
  419. If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
  420. use POSIX basic syntax.
  421. If REG_NEWLINE is set, then . and [^...] don't match newline.
  422. Also, regexec will try a match beginning after every newline.
  423. If REG_ICASE is set, then we considers upper- and lowercase
  424. versions of letters to be equivalent when matching.
  425. If REG_NOSUB is set, then when PREG is passed to regexec, that
  426. routine will report only success or failure, and nothing about the
  427. registers.
  428. It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
  429. the return codes and their meanings.) */
  430. int
  431. regcomp (preg, pattern, cflags)
  432. regex_t *_Restrict_ preg;
  433. const char *_Restrict_ pattern;
  434. int cflags;
  435. {
  436. reg_errcode_t ret;
  437. reg_syntax_t syntax = ((cflags & REG_EXTENDED) ? RE_SYNTAX_POSIX_EXTENDED
  438. : RE_SYNTAX_POSIX_BASIC);
  439. preg->buffer = NULL;
  440. preg->allocated = 0;
  441. preg->used = 0;
  442. /* Try to allocate space for the fastmap. */
  443. preg->fastmap = re_malloc (char, SBC_MAX);
  444. if (BE (preg->fastmap == NULL, 0))
  445. return REG_ESPACE;
  446. syntax |= (cflags & REG_ICASE) ? RE_ICASE : 0;
  447. /* If REG_NEWLINE is set, newlines are treated differently. */
  448. if (cflags & REG_NEWLINE)
  449. { /* REG_NEWLINE implies neither . nor [^...] match newline. */
  450. syntax &= ~RE_DOT_NEWLINE;
  451. syntax |= RE_HAT_LISTS_NOT_NEWLINE;
  452. /* It also changes the matching behavior. */
  453. preg->newline_anchor = 1;
  454. }
  455. else
  456. preg->newline_anchor = 0;
  457. preg->no_sub = !!(cflags & REG_NOSUB);
  458. preg->translate = NULL;
  459. ret = re_compile_internal (preg, pattern, strlen (pattern), syntax);
  460. /* POSIX doesn't distinguish between an unmatched open-group and an
  461. unmatched close-group: both are REG_EPAREN. */
  462. if (ret == REG_ERPAREN)
  463. ret = REG_EPAREN;
  464. /* We have already checked preg->fastmap != NULL. */
  465. if (BE (ret == REG_NOERROR, 1))
  466. /* Compute the fastmap now, since regexec cannot modify the pattern
  467. buffer. This function never fails in this implementation. */
  468. (void) re_compile_fastmap (preg);
  469. else
  470. {
  471. /* Some error occurred while compiling the expression. */
  472. re_free (preg->fastmap);
  473. preg->fastmap = NULL;
  474. }
  475. return (int) ret;
  476. }
  477. #ifdef _LIBC
  478. weak_alias (__regcomp, regcomp)
  479. #endif
  480. /* Returns a message corresponding to an error code, ERRCODE, returned
  481. from either regcomp or regexec. We don't use PREG here. */
  482. #ifdef _LIBC
  483. size_t
  484. regerror (errcode, preg, errbuf, errbuf_size)
  485. int errcode;
  486. const regex_t *_Restrict_ preg;
  487. char *_Restrict_ errbuf;
  488. size_t errbuf_size;
  489. #else /* size_t might promote */
  490. size_t
  491. regerror (int errcode, const regex_t *_Restrict_ preg,
  492. char *_Restrict_ errbuf, size_t errbuf_size)
  493. #endif
  494. {
  495. const char *msg;
  496. size_t msg_size;
  497. if (BE (errcode < 0
  498. || errcode >= (int) (sizeof (__re_error_msgid_idx)
  499. / sizeof (__re_error_msgid_idx[0])), 0))
  500. /* Only error codes returned by the rest of the code should be passed
  501. to this routine. If we are given anything else, or if other regex
  502. code generates an invalid error code, then the program has a bug.
  503. Dump core so we can fix it. */
  504. abort ();
  505. msg = gettext (__re_error_msgid + __re_error_msgid_idx[errcode]);
  506. msg_size = strlen (msg) + 1; /* Includes the null. */
  507. if (BE (errbuf_size != 0, 1))
  508. {
  509. size_t cpy_size = msg_size;
  510. if (BE (msg_size > errbuf_size, 0))
  511. {
  512. cpy_size = errbuf_size - 1;
  513. errbuf[cpy_size] = '\0';
  514. }
  515. memcpy (errbuf, msg, cpy_size);
  516. }
  517. return msg_size;
  518. }
  519. #ifdef _LIBC
  520. weak_alias (__regerror, regerror)
  521. #endif
  522. #ifdef RE_ENABLE_I18N
  523. /* This static array is used for the map to single-byte characters when
  524. UTF-8 is used. Otherwise we would allocate memory just to initialize
  525. it the same all the time. UTF-8 is the preferred encoding so this is
  526. a worthwhile optimization. */
  527. static const bitset_t utf8_sb_map =
  528. {
  529. /* Set the first 128 bits. */
  530. # if defined __GNUC__ && !defined __STRICT_ANSI__
  531. [0 ... 0x80 / BITSET_WORD_BITS - 1] = BITSET_WORD_MAX
  532. # else
  533. # if 4 * BITSET_WORD_BITS < ASCII_CHARS
  534. # error "bitset_word_t is narrower than 32 bits"
  535. # elif 3 * BITSET_WORD_BITS < ASCII_CHARS
  536. BITSET_WORD_MAX, BITSET_WORD_MAX, BITSET_WORD_MAX,
  537. # elif 2 * BITSET_WORD_BITS < ASCII_CHARS
  538. BITSET_WORD_MAX, BITSET_WORD_MAX,
  539. # elif 1 * BITSET_WORD_BITS < ASCII_CHARS
  540. BITSET_WORD_MAX,
  541. # endif
  542. (BITSET_WORD_MAX
  543. >> (SBC_MAX % BITSET_WORD_BITS == 0
  544. ? 0
  545. : BITSET_WORD_BITS - SBC_MAX % BITSET_WORD_BITS))
  546. # endif
  547. };
  548. #endif
  549. static void
  550. free_dfa_content (re_dfa_t *dfa)
  551. {
  552. Idx i, j;
  553. if (dfa->nodes)
  554. for (i = 0; i < dfa->nodes_len; ++i)
  555. free_token (dfa->nodes + i);
  556. re_free (dfa->nexts);
  557. for (i = 0; i < dfa->nodes_len; ++i)
  558. {
  559. if (dfa->eclosures != NULL)
  560. re_node_set_free (dfa->eclosures + i);
  561. if (dfa->inveclosures != NULL)
  562. re_node_set_free (dfa->inveclosures + i);
  563. if (dfa->edests != NULL)
  564. re_node_set_free (dfa->edests + i);
  565. }
  566. re_free (dfa->edests);
  567. re_free (dfa->eclosures);
  568. re_free (dfa->inveclosures);
  569. re_free (dfa->nodes);
  570. if (dfa->state_table)
  571. for (i = 0; i <= dfa->state_hash_mask; ++i)
  572. {
  573. struct re_state_table_entry *entry = dfa->state_table + i;
  574. for (j = 0; j < entry->num; ++j)
  575. {
  576. re_dfastate_t *state = entry->array[j];
  577. free_state (state);
  578. }
  579. re_free (entry->array);
  580. }
  581. re_free (dfa->state_table);
  582. #ifdef RE_ENABLE_I18N
  583. if (dfa->sb_char != utf8_sb_map)
  584. re_free (dfa->sb_char);
  585. #endif
  586. re_free (dfa->subexp_map);
  587. #ifdef DEBUG
  588. re_free (dfa->re_str);
  589. #endif
  590. re_free (dfa);
  591. }
  592. /* Free dynamically allocated space used by PREG. */
  593. void
  594. regfree (preg)
  595. regex_t *preg;
  596. {
  597. re_dfa_t *dfa = preg->buffer;
  598. if (BE (dfa != NULL, 1))
  599. {
  600. lock_fini (dfa->lock);
  601. free_dfa_content (dfa);
  602. }
  603. preg->buffer = NULL;
  604. preg->allocated = 0;
  605. re_free (preg->fastmap);
  606. preg->fastmap = NULL;
  607. re_free (preg->translate);
  608. preg->translate = NULL;
  609. }
  610. #ifdef _LIBC
  611. weak_alias (__regfree, regfree)
  612. #endif
  613. /* Entry points compatible with 4.2 BSD regex library. We don't define
  614. them unless specifically requested. */
  615. #if defined _REGEX_RE_COMP || defined _LIBC
  616. /* BSD has one and only one pattern buffer. */
  617. static struct re_pattern_buffer re_comp_buf;
  618. char *
  619. # ifdef _LIBC
  620. /* Make these definitions weak in libc, so POSIX programs can redefine
  621. these names if they don't use our functions, and still use
  622. regcomp/regexec above without link errors. */
  623. weak_function
  624. # endif
  625. re_comp (s)
  626. const char *s;
  627. {
  628. reg_errcode_t ret;
  629. char *fastmap;
  630. if (!s)
  631. {
  632. if (!re_comp_buf.buffer)
  633. return gettext ("No previous regular expression");
  634. return 0;
  635. }
  636. if (re_comp_buf.buffer)
  637. {
  638. fastmap = re_comp_buf.fastmap;
  639. re_comp_buf.fastmap = NULL;
  640. __regfree (&re_comp_buf);
  641. memset (&re_comp_buf, '\0', sizeof (re_comp_buf));
  642. re_comp_buf.fastmap = fastmap;
  643. }
  644. if (re_comp_buf.fastmap == NULL)
  645. {
  646. re_comp_buf.fastmap = (char *) malloc (SBC_MAX);
  647. if (re_comp_buf.fastmap == NULL)
  648. return (char *) gettext (__re_error_msgid
  649. + __re_error_msgid_idx[(int) REG_ESPACE]);
  650. }
  651. /* Since 're_exec' always passes NULL for the 'regs' argument, we
  652. don't need to initialize the pattern buffer fields which affect it. */
  653. /* Match anchors at newlines. */
  654. re_comp_buf.newline_anchor = 1;
  655. ret = re_compile_internal (&re_comp_buf, s, strlen (s), re_syntax_options);
  656. if (!ret)
  657. return NULL;
  658. /* Yes, we're discarding 'const' here if !HAVE_LIBINTL. */
  659. return (char *) gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
  660. }
  661. #ifdef _LIBC
  662. libc_freeres_fn (free_mem)
  663. {
  664. __regfree (&re_comp_buf);
  665. }
  666. #endif
  667. #endif /* _REGEX_RE_COMP */
  668. /* Internal entry point.
  669. Compile the regular expression PATTERN, whose length is LENGTH.
  670. SYNTAX indicate regular expression's syntax. */
  671. static reg_errcode_t
  672. re_compile_internal (regex_t *preg, const char * pattern, size_t length,
  673. reg_syntax_t syntax)
  674. {
  675. reg_errcode_t err = REG_NOERROR;
  676. re_dfa_t *dfa;
  677. re_string_t regexp;
  678. /* Initialize the pattern buffer. */
  679. preg->fastmap_accurate = 0;
  680. preg->syntax = syntax;
  681. preg->not_bol = preg->not_eol = 0;
  682. preg->used = 0;
  683. preg->re_nsub = 0;
  684. preg->can_be_null = 0;
  685. preg->regs_allocated = REGS_UNALLOCATED;
  686. /* Initialize the dfa. */
  687. dfa = preg->buffer;
  688. if (BE (preg->allocated < sizeof (re_dfa_t), 0))
  689. {
  690. /* If zero allocated, but buffer is non-null, try to realloc
  691. enough space. This loses if buffer's address is bogus, but
  692. that is the user's responsibility. If ->buffer is NULL this
  693. is a simple allocation. */
  694. dfa = re_realloc (preg->buffer, re_dfa_t, 1);
  695. if (dfa == NULL)
  696. return REG_ESPACE;
  697. preg->allocated = sizeof (re_dfa_t);
  698. preg->buffer = dfa;
  699. }
  700. preg->used = sizeof (re_dfa_t);
  701. err = init_dfa (dfa, length);
  702. if (BE (err == REG_NOERROR && lock_init (dfa->lock) != 0, 0))
  703. err = REG_ESPACE;
  704. if (BE (err != REG_NOERROR, 0))
  705. {
  706. free_dfa_content (dfa);
  707. preg->buffer = NULL;
  708. preg->allocated = 0;
  709. return err;
  710. }
  711. #ifdef DEBUG
  712. /* Note: length+1 will not overflow since it is checked in init_dfa. */
  713. dfa->re_str = re_malloc (char, length + 1);
  714. strncpy (dfa->re_str, pattern, length + 1);
  715. #endif
  716. err = re_string_construct (&regexp, pattern, length, preg->translate,
  717. (syntax & RE_ICASE) != 0, dfa);
  718. if (BE (err != REG_NOERROR, 0))
  719. {
  720. re_compile_internal_free_return:
  721. free_workarea_compile (preg);
  722. re_string_destruct (&regexp);
  723. lock_fini (dfa->lock);
  724. free_dfa_content (dfa);
  725. preg->buffer = NULL;
  726. preg->allocated = 0;
  727. return err;
  728. }
  729. /* Parse the regular expression, and build a structure tree. */
  730. preg->re_nsub = 0;
  731. dfa->str_tree = parse (&regexp, preg, syntax, &err);
  732. if (BE (dfa->str_tree == NULL, 0))
  733. goto re_compile_internal_free_return;
  734. /* Analyze the tree and create the nfa. */
  735. err = analyze (preg);
  736. if (BE (err != REG_NOERROR, 0))
  737. goto re_compile_internal_free_return;
  738. #ifdef RE_ENABLE_I18N
  739. /* If possible, do searching in single byte encoding to speed things up. */
  740. if (dfa->is_utf8 && !(syntax & RE_ICASE) && preg->translate == NULL)
  741. optimize_utf8 (dfa);
  742. #endif
  743. /* Then create the initial state of the dfa. */
  744. err = create_initial_state (dfa);
  745. /* Release work areas. */
  746. free_workarea_compile (preg);
  747. re_string_destruct (&regexp);
  748. if (BE (err != REG_NOERROR, 0))
  749. {
  750. lock_fini (dfa->lock);
  751. free_dfa_content (dfa);
  752. preg->buffer = NULL;
  753. preg->allocated = 0;
  754. }
  755. return err;
  756. }
  757. /* Initialize DFA. We use the length of the regular expression PAT_LEN
  758. as the initial length of some arrays. */
  759. static reg_errcode_t
  760. init_dfa (re_dfa_t *dfa, size_t pat_len)
  761. {
  762. __re_size_t table_size;
  763. #ifndef _LIBC
  764. const char *codeset_name;
  765. #endif
  766. #ifdef RE_ENABLE_I18N
  767. size_t max_i18n_object_size = MAX (sizeof (wchar_t), sizeof (wctype_t));
  768. #else
  769. size_t max_i18n_object_size = 0;
  770. #endif
  771. size_t max_object_size =
  772. MAX (sizeof (struct re_state_table_entry),
  773. MAX (sizeof (re_token_t),
  774. MAX (sizeof (re_node_set),
  775. MAX (sizeof (regmatch_t),
  776. max_i18n_object_size))));
  777. memset (dfa, '\0', sizeof (re_dfa_t));
  778. /* Force allocation of str_tree_storage the first time. */
  779. dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE;
  780. /* Avoid overflows. The extra "/ 2" is for the table_size doubling
  781. calculation below, and for similar doubling calculations
  782. elsewhere. And it's <= rather than <, because some of the
  783. doubling calculations add 1 afterwards. */
  784. if (BE (MIN (IDX_MAX, SIZE_MAX / max_object_size) / 2 <= pat_len, 0))
  785. return REG_ESPACE;
  786. dfa->nodes_alloc = pat_len + 1;
  787. dfa->nodes = re_malloc (re_token_t, dfa->nodes_alloc);
  788. /* table_size = 2 ^ ceil(log pat_len) */
  789. for (table_size = 1; ; table_size <<= 1)
  790. if (table_size > pat_len)
  791. break;
  792. dfa->state_table = calloc (sizeof (struct re_state_table_entry), table_size);
  793. dfa->state_hash_mask = table_size - 1;
  794. dfa->mb_cur_max = MB_CUR_MAX;
  795. #ifdef _LIBC
  796. if (dfa->mb_cur_max == 6
  797. && strcmp (_NL_CURRENT (LC_CTYPE, _NL_CTYPE_CODESET_NAME), "UTF-8") == 0)
  798. dfa->is_utf8 = 1;
  799. dfa->map_notascii = (_NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MAP_TO_NONASCII)
  800. != 0);
  801. #else
  802. codeset_name = nl_langinfo (CODESET);
  803. if ((codeset_name[0] == 'U' || codeset_name[0] == 'u')
  804. && (codeset_name[1] == 'T' || codeset_name[1] == 't')
  805. && (codeset_name[2] == 'F' || codeset_name[2] == 'f')
  806. && strcmp (codeset_name + 3 + (codeset_name[3] == '-'), "8") == 0)
  807. dfa->is_utf8 = 1;
  808. /* We check exhaustively in the loop below if this charset is a
  809. superset of ASCII. */
  810. dfa->map_notascii = 0;
  811. #endif
  812. #ifdef RE_ENABLE_I18N
  813. if (dfa->mb_cur_max > 1)
  814. {
  815. if (dfa->is_utf8)
  816. dfa->sb_char = (re_bitset_ptr_t) utf8_sb_map;
  817. else
  818. {
  819. int i, j, ch;
  820. dfa->sb_char = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  821. if (BE (dfa->sb_char == NULL, 0))
  822. return REG_ESPACE;
  823. /* Set the bits corresponding to single byte chars. */
  824. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  825. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  826. {
  827. wint_t wch = __btowc (ch);
  828. if (wch != WEOF)
  829. dfa->sb_char[i] |= (bitset_word_t) 1 << j;
  830. # ifndef _LIBC
  831. if (isascii (ch) && wch != ch)
  832. dfa->map_notascii = 1;
  833. # endif
  834. }
  835. }
  836. }
  837. #endif
  838. if (BE (dfa->nodes == NULL || dfa->state_table == NULL, 0))
  839. return REG_ESPACE;
  840. return REG_NOERROR;
  841. }
  842. /* Initialize WORD_CHAR table, which indicate which character is
  843. "word". In this case "word" means that it is the word construction
  844. character used by some operators like "\<", "\>", etc. */
  845. static void
  846. internal_function
  847. init_word_char (re_dfa_t *dfa)
  848. {
  849. int i = 0;
  850. int j;
  851. int ch = 0;
  852. dfa->word_ops_used = 1;
  853. if (BE (dfa->map_notascii == 0, 1))
  854. {
  855. bitset_word_t bits0 = 0x00000000;
  856. bitset_word_t bits1 = 0x03ff0000;
  857. bitset_word_t bits2 = 0x87fffffe;
  858. bitset_word_t bits3 = 0x07fffffe;
  859. if (BITSET_WORD_BITS == 64)
  860. {
  861. dfa->word_char[0] = bits1 << 31 << 1 | bits0;
  862. dfa->word_char[1] = bits3 << 31 << 1 | bits2;
  863. i = 2;
  864. }
  865. else if (BITSET_WORD_BITS == 32)
  866. {
  867. dfa->word_char[0] = bits0;
  868. dfa->word_char[1] = bits1;
  869. dfa->word_char[2] = bits2;
  870. dfa->word_char[3] = bits3;
  871. i = 4;
  872. }
  873. else
  874. goto general_case;
  875. ch = 128;
  876. if (BE (dfa->is_utf8, 1))
  877. {
  878. memset (&dfa->word_char[i], '\0', (SBC_MAX - ch) / 8);
  879. return;
  880. }
  881. }
  882. general_case:
  883. for (; i < BITSET_WORDS; ++i)
  884. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  885. if (isalnum (ch) || ch == '_')
  886. dfa->word_char[i] |= (bitset_word_t) 1 << j;
  887. }
  888. /* Free the work area which are only used while compiling. */
  889. static void
  890. free_workarea_compile (regex_t *preg)
  891. {
  892. re_dfa_t *dfa = preg->buffer;
  893. bin_tree_storage_t *storage, *next;
  894. for (storage = dfa->str_tree_storage; storage; storage = next)
  895. {
  896. next = storage->next;
  897. re_free (storage);
  898. }
  899. dfa->str_tree_storage = NULL;
  900. dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE;
  901. dfa->str_tree = NULL;
  902. re_free (dfa->org_indices);
  903. dfa->org_indices = NULL;
  904. }
  905. /* Create initial states for all contexts. */
  906. static reg_errcode_t
  907. create_initial_state (re_dfa_t *dfa)
  908. {
  909. Idx first, i;
  910. reg_errcode_t err;
  911. re_node_set init_nodes;
  912. /* Initial states have the epsilon closure of the node which is
  913. the first node of the regular expression. */
  914. first = dfa->str_tree->first->node_idx;
  915. dfa->init_node = first;
  916. err = re_node_set_init_copy (&init_nodes, dfa->eclosures + first);
  917. if (BE (err != REG_NOERROR, 0))
  918. return err;
  919. /* The back-references which are in initial states can epsilon transit,
  920. since in this case all of the subexpressions can be null.
  921. Then we add epsilon closures of the nodes which are the next nodes of
  922. the back-references. */
  923. if (dfa->nbackref > 0)
  924. for (i = 0; i < init_nodes.nelem; ++i)
  925. {
  926. Idx node_idx = init_nodes.elems[i];
  927. re_token_type_t type = dfa->nodes[node_idx].type;
  928. Idx clexp_idx;
  929. if (type != OP_BACK_REF)
  930. continue;
  931. for (clexp_idx = 0; clexp_idx < init_nodes.nelem; ++clexp_idx)
  932. {
  933. re_token_t *clexp_node;
  934. clexp_node = dfa->nodes + init_nodes.elems[clexp_idx];
  935. if (clexp_node->type == OP_CLOSE_SUBEXP
  936. && clexp_node->opr.idx == dfa->nodes[node_idx].opr.idx)
  937. break;
  938. }
  939. if (clexp_idx == init_nodes.nelem)
  940. continue;
  941. if (type == OP_BACK_REF)
  942. {
  943. Idx dest_idx = dfa->edests[node_idx].elems[0];
  944. if (!re_node_set_contains (&init_nodes, dest_idx))
  945. {
  946. reg_errcode_t merge_err
  947. = re_node_set_merge (&init_nodes, dfa->eclosures + dest_idx);
  948. if (merge_err != REG_NOERROR)
  949. return merge_err;
  950. i = 0;
  951. }
  952. }
  953. }
  954. /* It must be the first time to invoke acquire_state. */
  955. dfa->init_state = re_acquire_state_context (&err, dfa, &init_nodes, 0);
  956. /* We don't check ERR here, since the initial state must not be NULL. */
  957. if (BE (dfa->init_state == NULL, 0))
  958. return err;
  959. if (dfa->init_state->has_constraint)
  960. {
  961. dfa->init_state_word = re_acquire_state_context (&err, dfa, &init_nodes,
  962. CONTEXT_WORD);
  963. dfa->init_state_nl = re_acquire_state_context (&err, dfa, &init_nodes,
  964. CONTEXT_NEWLINE);
  965. dfa->init_state_begbuf = re_acquire_state_context (&err, dfa,
  966. &init_nodes,
  967. CONTEXT_NEWLINE
  968. | CONTEXT_BEGBUF);
  969. if (BE (dfa->init_state_word == NULL || dfa->init_state_nl == NULL
  970. || dfa->init_state_begbuf == NULL, 0))
  971. return err;
  972. }
  973. else
  974. dfa->init_state_word = dfa->init_state_nl
  975. = dfa->init_state_begbuf = dfa->init_state;
  976. re_node_set_free (&init_nodes);
  977. return REG_NOERROR;
  978. }
  979. #ifdef RE_ENABLE_I18N
  980. /* If it is possible to do searching in single byte encoding instead of UTF-8
  981. to speed things up, set dfa->mb_cur_max to 1, clear is_utf8 and change
  982. DFA nodes where needed. */
  983. static void
  984. optimize_utf8 (re_dfa_t *dfa)
  985. {
  986. Idx node;
  987. int i;
  988. bool mb_chars = false;
  989. bool has_period = false;
  990. for (node = 0; node < dfa->nodes_len; ++node)
  991. switch (dfa->nodes[node].type)
  992. {
  993. case CHARACTER:
  994. if (dfa->nodes[node].opr.c >= ASCII_CHARS)
  995. mb_chars = true;
  996. break;
  997. case ANCHOR:
  998. switch (dfa->nodes[node].opr.ctx_type)
  999. {
  1000. case LINE_FIRST:
  1001. case LINE_LAST:
  1002. case BUF_FIRST:
  1003. case BUF_LAST:
  1004. break;
  1005. default:
  1006. /* Word anchors etc. cannot be handled. It's okay to test
  1007. opr.ctx_type since constraints (for all DFA nodes) are
  1008. created by ORing one or more opr.ctx_type values. */
  1009. return;
  1010. }
  1011. break;
  1012. case OP_PERIOD:
  1013. has_period = true;
  1014. break;
  1015. case OP_BACK_REF:
  1016. case OP_ALT:
  1017. case END_OF_RE:
  1018. case OP_DUP_ASTERISK:
  1019. case OP_OPEN_SUBEXP:
  1020. case OP_CLOSE_SUBEXP:
  1021. break;
  1022. case COMPLEX_BRACKET:
  1023. return;
  1024. case SIMPLE_BRACKET:
  1025. /* Just double check. */
  1026. {
  1027. int rshift = (ASCII_CHARS % BITSET_WORD_BITS == 0
  1028. ? 0
  1029. : BITSET_WORD_BITS - ASCII_CHARS % BITSET_WORD_BITS);
  1030. for (i = ASCII_CHARS / BITSET_WORD_BITS; i < BITSET_WORDS; ++i)
  1031. {
  1032. if (dfa->nodes[node].opr.sbcset[i] >> rshift != 0)
  1033. return;
  1034. rshift = 0;
  1035. }
  1036. }
  1037. break;
  1038. default:
  1039. abort ();
  1040. }
  1041. if (mb_chars || has_period)
  1042. for (node = 0; node < dfa->nodes_len; ++node)
  1043. {
  1044. if (dfa->nodes[node].type == CHARACTER
  1045. && dfa->nodes[node].opr.c >= ASCII_CHARS)
  1046. dfa->nodes[node].mb_partial = 0;
  1047. else if (dfa->nodes[node].type == OP_PERIOD)
  1048. dfa->nodes[node].type = OP_UTF8_PERIOD;
  1049. }
  1050. /* The search can be in single byte locale. */
  1051. dfa->mb_cur_max = 1;
  1052. dfa->is_utf8 = 0;
  1053. dfa->has_mb_node = dfa->nbackref > 0 || has_period;
  1054. }
  1055. #endif
  1056. /* Analyze the structure tree, and calculate "first", "next", "edest",
  1057. "eclosure", and "inveclosure". */
  1058. static reg_errcode_t
  1059. analyze (regex_t *preg)
  1060. {
  1061. re_dfa_t *dfa = preg->buffer;
  1062. reg_errcode_t ret;
  1063. /* Allocate arrays. */
  1064. dfa->nexts = re_malloc (Idx, dfa->nodes_alloc);
  1065. dfa->org_indices = re_malloc (Idx, dfa->nodes_alloc);
  1066. dfa->edests = re_malloc (re_node_set, dfa->nodes_alloc);
  1067. dfa->eclosures = re_malloc (re_node_set, dfa->nodes_alloc);
  1068. if (BE (dfa->nexts == NULL || dfa->org_indices == NULL || dfa->edests == NULL
  1069. || dfa->eclosures == NULL, 0))
  1070. return REG_ESPACE;
  1071. dfa->subexp_map = re_malloc (Idx, preg->re_nsub);
  1072. if (dfa->subexp_map != NULL)
  1073. {
  1074. Idx i;
  1075. for (i = 0; i < preg->re_nsub; i++)
  1076. dfa->subexp_map[i] = i;
  1077. preorder (dfa->str_tree, optimize_subexps, dfa);
  1078. for (i = 0; i < preg->re_nsub; i++)
  1079. if (dfa->subexp_map[i] != i)
  1080. break;
  1081. if (i == preg->re_nsub)
  1082. {
  1083. free (dfa->subexp_map);
  1084. dfa->subexp_map = NULL;
  1085. }
  1086. }
  1087. ret = postorder (dfa->str_tree, lower_subexps, preg);
  1088. if (BE (ret != REG_NOERROR, 0))
  1089. return ret;
  1090. ret = postorder (dfa->str_tree, calc_first, dfa);
  1091. if (BE (ret != REG_NOERROR, 0))
  1092. return ret;
  1093. preorder (dfa->str_tree, calc_next, dfa);
  1094. ret = preorder (dfa->str_tree, link_nfa_nodes, dfa);
  1095. if (BE (ret != REG_NOERROR, 0))
  1096. return ret;
  1097. ret = calc_eclosure (dfa);
  1098. if (BE (ret != REG_NOERROR, 0))
  1099. return ret;
  1100. /* We only need this during the prune_impossible_nodes pass in regexec.c;
  1101. skip it if p_i_n will not run, as calc_inveclosure can be quadratic. */
  1102. if ((!preg->no_sub && preg->re_nsub > 0 && dfa->has_plural_match)
  1103. || dfa->nbackref)
  1104. {
  1105. dfa->inveclosures = re_malloc (re_node_set, dfa->nodes_len);
  1106. if (BE (dfa->inveclosures == NULL, 0))
  1107. return REG_ESPACE;
  1108. ret = calc_inveclosure (dfa);
  1109. }
  1110. return ret;
  1111. }
  1112. /* Our parse trees are very unbalanced, so we cannot use a stack to
  1113. implement parse tree visits. Instead, we use parent pointers and
  1114. some hairy code in these two functions. */
  1115. static reg_errcode_t
  1116. postorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
  1117. void *extra)
  1118. {
  1119. bin_tree_t *node, *prev;
  1120. for (node = root; ; )
  1121. {
  1122. /* Descend down the tree, preferably to the left (or to the right
  1123. if that's the only child). */
  1124. while (node->left || node->right)
  1125. if (node->left)
  1126. node = node->left;
  1127. else
  1128. node = node->right;
  1129. do
  1130. {
  1131. reg_errcode_t err = fn (extra, node);
  1132. if (BE (err != REG_NOERROR, 0))
  1133. return err;
  1134. if (node->parent == NULL)
  1135. return REG_NOERROR;
  1136. prev = node;
  1137. node = node->parent;
  1138. }
  1139. /* Go up while we have a node that is reached from the right. */
  1140. while (node->right == prev || node->right == NULL);
  1141. node = node->right;
  1142. }
  1143. }
  1144. static reg_errcode_t
  1145. preorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
  1146. void *extra)
  1147. {
  1148. bin_tree_t *node;
  1149. for (node = root; ; )
  1150. {
  1151. reg_errcode_t err = fn (extra, node);
  1152. if (BE (err != REG_NOERROR, 0))
  1153. return err;
  1154. /* Go to the left node, or up and to the right. */
  1155. if (node->left)
  1156. node = node->left;
  1157. else
  1158. {
  1159. bin_tree_t *prev = NULL;
  1160. while (node->right == prev || node->right == NULL)
  1161. {
  1162. prev = node;
  1163. node = node->parent;
  1164. if (!node)
  1165. return REG_NOERROR;
  1166. }
  1167. node = node->right;
  1168. }
  1169. }
  1170. }
  1171. /* Optimization pass: if a SUBEXP is entirely contained, strip it and tell
  1172. re_search_internal to map the inner one's opr.idx to this one's. Adjust
  1173. backreferences as well. Requires a preorder visit. */
  1174. static reg_errcode_t
  1175. optimize_subexps (void *extra, bin_tree_t *node)
  1176. {
  1177. re_dfa_t *dfa = (re_dfa_t *) extra;
  1178. if (node->token.type == OP_BACK_REF && dfa->subexp_map)
  1179. {
  1180. int idx = node->token.opr.idx;
  1181. node->token.opr.idx = dfa->subexp_map[idx];
  1182. dfa->used_bkref_map |= 1 << node->token.opr.idx;
  1183. }
  1184. else if (node->token.type == SUBEXP
  1185. && node->left && node->left->token.type == SUBEXP)
  1186. {
  1187. Idx other_idx = node->left->token.opr.idx;
  1188. node->left = node->left->left;
  1189. if (node->left)
  1190. node->left->parent = node;
  1191. dfa->subexp_map[other_idx] = dfa->subexp_map[node->token.opr.idx];
  1192. if (other_idx < BITSET_WORD_BITS)
  1193. dfa->used_bkref_map &= ~((bitset_word_t) 1 << other_idx);
  1194. }
  1195. return REG_NOERROR;
  1196. }
  1197. /* Lowering pass: Turn each SUBEXP node into the appropriate concatenation
  1198. of OP_OPEN_SUBEXP, the body of the SUBEXP (if any) and OP_CLOSE_SUBEXP. */
  1199. static reg_errcode_t
  1200. lower_subexps (void *extra, bin_tree_t *node)
  1201. {
  1202. regex_t *preg = (regex_t *) extra;
  1203. reg_errcode_t err = REG_NOERROR;
  1204. if (node->left && node->left->token.type == SUBEXP)
  1205. {
  1206. node->left = lower_subexp (&err, preg, node->left);
  1207. if (node->left)
  1208. node->left->parent = node;
  1209. }
  1210. if (node->right && node->right->token.type == SUBEXP)
  1211. {
  1212. node->right = lower_subexp (&err, preg, node->right);
  1213. if (node->right)
  1214. node->right->parent = node;
  1215. }
  1216. return err;
  1217. }
  1218. static bin_tree_t *
  1219. lower_subexp (reg_errcode_t *err, regex_t *preg, bin_tree_t *node)
  1220. {
  1221. re_dfa_t *dfa = preg->buffer;
  1222. bin_tree_t *body = node->left;
  1223. bin_tree_t *op, *cls, *tree1, *tree;
  1224. if (preg->no_sub
  1225. /* We do not optimize empty subexpressions, because otherwise we may
  1226. have bad CONCAT nodes with NULL children. This is obviously not
  1227. very common, so we do not lose much. An example that triggers
  1228. this case is the sed "script" /\(\)/x. */
  1229. && node->left != NULL
  1230. && (node->token.opr.idx >= BITSET_WORD_BITS
  1231. || !(dfa->used_bkref_map
  1232. & ((bitset_word_t) 1 << node->token.opr.idx))))
  1233. return node->left;
  1234. /* Convert the SUBEXP node to the concatenation of an
  1235. OP_OPEN_SUBEXP, the contents, and an OP_CLOSE_SUBEXP. */
  1236. op = create_tree (dfa, NULL, NULL, OP_OPEN_SUBEXP);
  1237. cls = create_tree (dfa, NULL, NULL, OP_CLOSE_SUBEXP);
  1238. tree1 = body ? create_tree (dfa, body, cls, CONCAT) : cls;
  1239. tree = create_tree (dfa, op, tree1, CONCAT);
  1240. if (BE (tree == NULL || tree1 == NULL || op == NULL || cls == NULL, 0))
  1241. {
  1242. *err = REG_ESPACE;
  1243. return NULL;
  1244. }
  1245. op->token.opr.idx = cls->token.opr.idx = node->token.opr.idx;
  1246. op->token.opt_subexp = cls->token.opt_subexp = node->token.opt_subexp;
  1247. return tree;
  1248. }
  1249. /* Pass 1 in building the NFA: compute FIRST and create unlinked automaton
  1250. nodes. Requires a postorder visit. */
  1251. static reg_errcode_t
  1252. calc_first (void *extra, bin_tree_t *node)
  1253. {
  1254. re_dfa_t *dfa = (re_dfa_t *) extra;
  1255. if (node->token.type == CONCAT)
  1256. {
  1257. node->first = node->left->first;
  1258. node->node_idx = node->left->node_idx;
  1259. }
  1260. else
  1261. {
  1262. node->first = node;
  1263. node->node_idx = re_dfa_add_node (dfa, node->token);
  1264. if (BE (node->node_idx == REG_MISSING, 0))
  1265. return REG_ESPACE;
  1266. if (node->token.type == ANCHOR)
  1267. dfa->nodes[node->node_idx].constraint = node->token.opr.ctx_type;
  1268. }
  1269. return REG_NOERROR;
  1270. }
  1271. /* Pass 2: compute NEXT on the tree. Preorder visit. */
  1272. static reg_errcode_t
  1273. calc_next (void *extra, bin_tree_t *node)
  1274. {
  1275. switch (node->token.type)
  1276. {
  1277. case OP_DUP_ASTERISK:
  1278. node->left->next = node;
  1279. break;
  1280. case CONCAT:
  1281. node->left->next = node->right->first;
  1282. node->right->next = node->next;
  1283. break;
  1284. default:
  1285. if (node->left)
  1286. node->left->next = node->next;
  1287. if (node->right)
  1288. node->right->next = node->next;
  1289. break;
  1290. }
  1291. return REG_NOERROR;
  1292. }
  1293. /* Pass 3: link all DFA nodes to their NEXT node (any order will do). */
  1294. static reg_errcode_t
  1295. link_nfa_nodes (void *extra, bin_tree_t *node)
  1296. {
  1297. re_dfa_t *dfa = (re_dfa_t *) extra;
  1298. Idx idx = node->node_idx;
  1299. reg_errcode_t err = REG_NOERROR;
  1300. switch (node->token.type)
  1301. {
  1302. case CONCAT:
  1303. break;
  1304. case END_OF_RE:
  1305. assert (node->next == NULL);
  1306. break;
  1307. case OP_DUP_ASTERISK:
  1308. case OP_ALT:
  1309. {
  1310. Idx left, right;
  1311. dfa->has_plural_match = 1;
  1312. if (node->left != NULL)
  1313. left = node->left->first->node_idx;
  1314. else
  1315. left = node->next->node_idx;
  1316. if (node->right != NULL)
  1317. right = node->right->first->node_idx;
  1318. else
  1319. right = node->next->node_idx;
  1320. assert (REG_VALID_INDEX (left));
  1321. assert (REG_VALID_INDEX (right));
  1322. err = re_node_set_init_2 (dfa->edests + idx, left, right);
  1323. }
  1324. break;
  1325. case ANCHOR:
  1326. case OP_OPEN_SUBEXP:
  1327. case OP_CLOSE_SUBEXP:
  1328. err = re_node_set_init_1 (dfa->edests + idx, node->next->node_idx);
  1329. break;
  1330. case OP_BACK_REF:
  1331. dfa->nexts[idx] = node->next->node_idx;
  1332. if (node->token.type == OP_BACK_REF)
  1333. err = re_node_set_init_1 (dfa->edests + idx, dfa->nexts[idx]);
  1334. break;
  1335. default:
  1336. assert (!IS_EPSILON_NODE (node->token.type));
  1337. dfa->nexts[idx] = node->next->node_idx;
  1338. break;
  1339. }
  1340. return err;
  1341. }
  1342. /* Duplicate the epsilon closure of the node ROOT_NODE.
  1343. Note that duplicated nodes have constraint INIT_CONSTRAINT in addition
  1344. to their own constraint. */
  1345. static reg_errcode_t
  1346. internal_function
  1347. duplicate_node_closure (re_dfa_t *dfa, Idx top_org_node, Idx top_clone_node,
  1348. Idx root_node, unsigned int init_constraint)
  1349. {
  1350. Idx org_node, clone_node;
  1351. bool ok;
  1352. unsigned int constraint = init_constraint;
  1353. for (org_node = top_org_node, clone_node = top_clone_node;;)
  1354. {
  1355. Idx org_dest, clone_dest;
  1356. if (dfa->nodes[org_node].type == OP_BACK_REF)
  1357. {
  1358. /* If the back reference epsilon-transit, its destination must
  1359. also have the constraint. Then duplicate the epsilon closure
  1360. of the destination of the back reference, and store it in
  1361. edests of the back reference. */
  1362. org_dest = dfa->nexts[org_node];
  1363. re_node_set_empty (dfa->edests + clone_node);
  1364. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1365. if (BE (clone_dest == REG_MISSING, 0))
  1366. return REG_ESPACE;
  1367. dfa->nexts[clone_node] = dfa->nexts[org_node];
  1368. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1369. if (BE (! ok, 0))
  1370. return REG_ESPACE;
  1371. }
  1372. else if (dfa->edests[org_node].nelem == 0)
  1373. {
  1374. /* In case of the node can't epsilon-transit, don't duplicate the
  1375. destination and store the original destination as the
  1376. destination of the node. */
  1377. dfa->nexts[clone_node] = dfa->nexts[org_node];
  1378. break;
  1379. }
  1380. else if (dfa->edests[org_node].nelem == 1)
  1381. {
  1382. /* In case of the node can epsilon-transit, and it has only one
  1383. destination. */
  1384. org_dest = dfa->edests[org_node].elems[0];
  1385. re_node_set_empty (dfa->edests + clone_node);
  1386. /* If the node is root_node itself, it means the epsilon closure
  1387. has a loop. Then tie it to the destination of the root_node. */
  1388. if (org_node == root_node && clone_node != org_node)
  1389. {
  1390. ok = re_node_set_insert (dfa->edests + clone_node, org_dest);
  1391. if (BE (! ok, 0))
  1392. return REG_ESPACE;
  1393. break;
  1394. }
  1395. /* In case the node has another constraint, append it. */
  1396. constraint |= dfa->nodes[org_node].constraint;
  1397. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1398. if (BE (clone_dest == REG_MISSING, 0))
  1399. return REG_ESPACE;
  1400. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1401. if (BE (! ok, 0))
  1402. return REG_ESPACE;
  1403. }
  1404. else /* dfa->edests[org_node].nelem == 2 */
  1405. {
  1406. /* In case of the node can epsilon-transit, and it has two
  1407. destinations. In the bin_tree_t and DFA, that's '|' and '*'. */
  1408. org_dest = dfa->edests[org_node].elems[0];
  1409. re_node_set_empty (dfa->edests + clone_node);
  1410. /* Search for a duplicated node which satisfies the constraint. */
  1411. clone_dest = search_duplicated_node (dfa, org_dest, constraint);
  1412. if (clone_dest == REG_MISSING)
  1413. {
  1414. /* There is no such duplicated node, create a new one. */
  1415. reg_errcode_t err;
  1416. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1417. if (BE (clone_dest == REG_MISSING, 0))
  1418. return REG_ESPACE;
  1419. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1420. if (BE (! ok, 0))
  1421. return REG_ESPACE;
  1422. err = duplicate_node_closure (dfa, org_dest, clone_dest,
  1423. root_node, constraint);
  1424. if (BE (err != REG_NOERROR, 0))
  1425. return err;
  1426. }
  1427. else
  1428. {
  1429. /* There is a duplicated node which satisfies the constraint,
  1430. use it to avoid infinite loop. */
  1431. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1432. if (BE (! ok, 0))
  1433. return REG_ESPACE;
  1434. }
  1435. org_dest = dfa->edests[org_node].elems[1];
  1436. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1437. if (BE (clone_dest == REG_MISSING, 0))
  1438. return REG_ESPACE;
  1439. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1440. if (BE (! ok, 0))
  1441. return REG_ESPACE;
  1442. }
  1443. org_node = org_dest;
  1444. clone_node = clone_dest;
  1445. }
  1446. return REG_NOERROR;
  1447. }
  1448. /* Search for a node which is duplicated from the node ORG_NODE, and
  1449. satisfies the constraint CONSTRAINT. */
  1450. static Idx
  1451. search_duplicated_node (const re_dfa_t *dfa, Idx org_node,
  1452. unsigned int constraint)
  1453. {
  1454. Idx idx;
  1455. for (idx = dfa->nodes_len - 1; dfa->nodes[idx].duplicated && idx > 0; --idx)
  1456. {
  1457. if (org_node == dfa->org_indices[idx]
  1458. && constraint == dfa->nodes[idx].constraint)
  1459. return idx; /* Found. */
  1460. }
  1461. return REG_MISSING; /* Not found. */
  1462. }
  1463. /* Duplicate the node whose index is ORG_IDX and set the constraint CONSTRAINT.
  1464. Return the index of the new node, or REG_MISSING if insufficient storage is
  1465. available. */
  1466. static Idx
  1467. duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint)
  1468. {
  1469. Idx dup_idx = re_dfa_add_node (dfa, dfa->nodes[org_idx]);
  1470. if (BE (dup_idx != REG_MISSING, 1))
  1471. {
  1472. dfa->nodes[dup_idx].constraint = constraint;
  1473. dfa->nodes[dup_idx].constraint |= dfa->nodes[org_idx].constraint;
  1474. dfa->nodes[dup_idx].duplicated = 1;
  1475. /* Store the index of the original node. */
  1476. dfa->org_indices[dup_idx] = org_idx;
  1477. }
  1478. return dup_idx;
  1479. }
  1480. static reg_errcode_t
  1481. calc_inveclosure (re_dfa_t *dfa)
  1482. {
  1483. Idx src, idx;
  1484. bool ok;
  1485. for (idx = 0; idx < dfa->nodes_len; ++idx)
  1486. re_node_set_init_empty (dfa->inveclosures + idx);
  1487. for (src = 0; src < dfa->nodes_len; ++src)
  1488. {
  1489. Idx *elems = dfa->eclosures[src].elems;
  1490. for (idx = 0; idx < dfa->eclosures[src].nelem; ++idx)
  1491. {
  1492. ok = re_node_set_insert_last (dfa->inveclosures + elems[idx], src);
  1493. if (BE (! ok, 0))
  1494. return REG_ESPACE;
  1495. }
  1496. }
  1497. return REG_NOERROR;
  1498. }
  1499. /* Calculate "eclosure" for all the node in DFA. */
  1500. static reg_errcode_t
  1501. calc_eclosure (re_dfa_t *dfa)
  1502. {
  1503. Idx node_idx;
  1504. bool incomplete;
  1505. #ifdef DEBUG
  1506. assert (dfa->nodes_len > 0);
  1507. #endif
  1508. incomplete = false;
  1509. /* For each nodes, calculate epsilon closure. */
  1510. for (node_idx = 0; ; ++node_idx)
  1511. {
  1512. reg_errcode_t err;
  1513. re_node_set eclosure_elem;
  1514. if (node_idx == dfa->nodes_len)
  1515. {
  1516. if (!incomplete)
  1517. break;
  1518. incomplete = false;
  1519. node_idx = 0;
  1520. }
  1521. #ifdef DEBUG
  1522. assert (dfa->eclosures[node_idx].nelem != REG_MISSING);
  1523. #endif
  1524. /* If we have already calculated, skip it. */
  1525. if (dfa->eclosures[node_idx].nelem != 0)
  1526. continue;
  1527. /* Calculate epsilon closure of 'node_idx'. */
  1528. err = calc_eclosure_iter (&eclosure_elem, dfa, node_idx, true);
  1529. if (BE (err != REG_NOERROR, 0))
  1530. return err;
  1531. if (dfa->eclosures[node_idx].nelem == 0)
  1532. {
  1533. incomplete = true;
  1534. re_node_set_free (&eclosure_elem);
  1535. }
  1536. }
  1537. return REG_NOERROR;
  1538. }
  1539. /* Calculate epsilon closure of NODE. */
  1540. static reg_errcode_t
  1541. calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, Idx node, bool root)
  1542. {
  1543. reg_errcode_t err;
  1544. Idx i;
  1545. re_node_set eclosure;
  1546. bool ok;
  1547. bool incomplete = false;
  1548. err = re_node_set_alloc (&eclosure, dfa->edests[node].nelem + 1);
  1549. if (BE (err != REG_NOERROR, 0))
  1550. return err;
  1551. /* This indicates that we are calculating this node now.
  1552. We reference this value to avoid infinite loop. */
  1553. dfa->eclosures[node].nelem = REG_MISSING;
  1554. /* If the current node has constraints, duplicate all nodes
  1555. since they must inherit the constraints. */
  1556. if (dfa->nodes[node].constraint
  1557. && dfa->edests[node].nelem
  1558. && !dfa->nodes[dfa->edests[node].elems[0]].duplicated)
  1559. {
  1560. err = duplicate_node_closure (dfa, node, node, node,
  1561. dfa->nodes[node].constraint);
  1562. if (BE (err != REG_NOERROR, 0))
  1563. return err;
  1564. }
  1565. /* Expand each epsilon destination nodes. */
  1566. if (IS_EPSILON_NODE(dfa->nodes[node].type))
  1567. for (i = 0; i < dfa->edests[node].nelem; ++i)
  1568. {
  1569. re_node_set eclosure_elem;
  1570. Idx edest = dfa->edests[node].elems[i];
  1571. /* If calculating the epsilon closure of 'edest' is in progress,
  1572. return intermediate result. */
  1573. if (dfa->eclosures[edest].nelem == REG_MISSING)
  1574. {
  1575. incomplete = true;
  1576. continue;
  1577. }
  1578. /* If we haven't calculated the epsilon closure of 'edest' yet,
  1579. calculate now. Otherwise use calculated epsilon closure. */
  1580. if (dfa->eclosures[edest].nelem == 0)
  1581. {
  1582. err = calc_eclosure_iter (&eclosure_elem, dfa, edest, false);
  1583. if (BE (err != REG_NOERROR, 0))
  1584. return err;
  1585. }
  1586. else
  1587. eclosure_elem = dfa->eclosures[edest];
  1588. /* Merge the epsilon closure of 'edest'. */
  1589. err = re_node_set_merge (&eclosure, &eclosure_elem);
  1590. if (BE (err != REG_NOERROR, 0))
  1591. return err;
  1592. /* If the epsilon closure of 'edest' is incomplete,
  1593. the epsilon closure of this node is also incomplete. */
  1594. if (dfa->eclosures[edest].nelem == 0)
  1595. {
  1596. incomplete = true;
  1597. re_node_set_free (&eclosure_elem);
  1598. }
  1599. }
  1600. /* An epsilon closure includes itself. */
  1601. ok = re_node_set_insert (&eclosure, node);
  1602. if (BE (! ok, 0))
  1603. return REG_ESPACE;
  1604. if (incomplete && !root)
  1605. dfa->eclosures[node].nelem = 0;
  1606. else
  1607. dfa->eclosures[node] = eclosure;
  1608. *new_set = eclosure;
  1609. return REG_NOERROR;
  1610. }
  1611. /* Functions for token which are used in the parser. */
  1612. /* Fetch a token from INPUT.
  1613. We must not use this function inside bracket expressions. */
  1614. static void
  1615. internal_function
  1616. fetch_token (re_token_t *result, re_string_t *input, reg_syntax_t syntax)
  1617. {
  1618. re_string_skip_bytes (input, peek_token (result, input, syntax));
  1619. }
  1620. /* Peek a token from INPUT, and return the length of the token.
  1621. We must not use this function inside bracket expressions. */
  1622. static int
  1623. internal_function
  1624. peek_token (re_token_t *token, re_string_t *input, reg_syntax_t syntax)
  1625. {
  1626. unsigned char c;
  1627. if (re_string_eoi (input))
  1628. {
  1629. token->type = END_OF_RE;
  1630. return 0;
  1631. }
  1632. c = re_string_peek_byte (input, 0);
  1633. token->opr.c = c;
  1634. token->word_char = 0;
  1635. #ifdef RE_ENABLE_I18N
  1636. token->mb_partial = 0;
  1637. if (input->mb_cur_max > 1 &&
  1638. !re_string_first_byte (input, re_string_cur_idx (input)))
  1639. {
  1640. token->type = CHARACTER;
  1641. token->mb_partial = 1;
  1642. return 1;
  1643. }
  1644. #endif
  1645. if (c == '\\')
  1646. {
  1647. unsigned char c2;
  1648. if (re_string_cur_idx (input) + 1 >= re_string_length (input))
  1649. {
  1650. token->type = BACK_SLASH;
  1651. return 1;
  1652. }
  1653. c2 = re_string_peek_byte_case (input, 1);
  1654. token->opr.c = c2;
  1655. token->type = CHARACTER;
  1656. #ifdef RE_ENABLE_I18N
  1657. if (input->mb_cur_max > 1)
  1658. {
  1659. wint_t wc = re_string_wchar_at (input,
  1660. re_string_cur_idx (input) + 1);
  1661. token->word_char = IS_WIDE_WORD_CHAR (wc) != 0;
  1662. }
  1663. else
  1664. #endif
  1665. token->word_char = IS_WORD_CHAR (c2) != 0;
  1666. switch (c2)
  1667. {
  1668. case '|':
  1669. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_NO_BK_VBAR))
  1670. token->type = OP_ALT;
  1671. break;
  1672. case '1': case '2': case '3': case '4': case '5':
  1673. case '6': case '7': case '8': case '9':
  1674. if (!(syntax & RE_NO_BK_REFS))
  1675. {
  1676. token->type = OP_BACK_REF;
  1677. token->opr.idx = c2 - '1';
  1678. }
  1679. break;
  1680. case '<':
  1681. if (!(syntax & RE_NO_GNU_OPS))
  1682. {
  1683. token->type = ANCHOR;
  1684. token->opr.ctx_type = WORD_FIRST;
  1685. }
  1686. break;
  1687. case '>':
  1688. if (!(syntax & RE_NO_GNU_OPS))
  1689. {
  1690. token->type = ANCHOR;
  1691. token->opr.ctx_type = WORD_LAST;
  1692. }
  1693. break;
  1694. case 'b':
  1695. if (!(syntax & RE_NO_GNU_OPS))
  1696. {
  1697. token->type = ANCHOR;
  1698. token->opr.ctx_type = WORD_DELIM;
  1699. }
  1700. break;
  1701. case 'B':
  1702. if (!(syntax & RE_NO_GNU_OPS))
  1703. {
  1704. token->type = ANCHOR;
  1705. token->opr.ctx_type = NOT_WORD_DELIM;
  1706. }
  1707. break;
  1708. case 'w':
  1709. if (!(syntax & RE_NO_GNU_OPS))
  1710. token->type = OP_WORD;
  1711. break;
  1712. case 'W':
  1713. if (!(syntax & RE_NO_GNU_OPS))
  1714. token->type = OP_NOTWORD;
  1715. break;
  1716. case 's':
  1717. if (!(syntax & RE_NO_GNU_OPS))
  1718. token->type = OP_SPACE;
  1719. break;
  1720. case 'S':
  1721. if (!(syntax & RE_NO_GNU_OPS))
  1722. token->type = OP_NOTSPACE;
  1723. break;
  1724. case '`':
  1725. if (!(syntax & RE_NO_GNU_OPS))
  1726. {
  1727. token->type = ANCHOR;
  1728. token->opr.ctx_type = BUF_FIRST;
  1729. }
  1730. break;
  1731. case '\'':
  1732. if (!(syntax & RE_NO_GNU_OPS))
  1733. {
  1734. token->type = ANCHOR;
  1735. token->opr.ctx_type = BUF_LAST;
  1736. }
  1737. break;
  1738. case '(':
  1739. if (!(syntax & RE_NO_BK_PARENS))
  1740. token->type = OP_OPEN_SUBEXP;
  1741. break;
  1742. case ')':
  1743. if (!(syntax & RE_NO_BK_PARENS))
  1744. token->type = OP_CLOSE_SUBEXP;
  1745. break;
  1746. case '+':
  1747. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM))
  1748. token->type = OP_DUP_PLUS;
  1749. break;
  1750. case '?':
  1751. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM))
  1752. token->type = OP_DUP_QUESTION;
  1753. break;
  1754. case '{':
  1755. if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES)))
  1756. token->type = OP_OPEN_DUP_NUM;
  1757. break;
  1758. case '}':
  1759. if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES)))
  1760. token->type = OP_CLOSE_DUP_NUM;
  1761. break;
  1762. default:
  1763. break;
  1764. }
  1765. return 2;
  1766. }
  1767. token->type = CHARACTER;
  1768. #ifdef RE_ENABLE_I18N
  1769. if (input->mb_cur_max > 1)
  1770. {
  1771. wint_t wc = re_string_wchar_at (input, re_string_cur_idx (input));
  1772. token->word_char = IS_WIDE_WORD_CHAR (wc) != 0;
  1773. }
  1774. else
  1775. #endif
  1776. token->word_char = IS_WORD_CHAR (token->opr.c);
  1777. switch (c)
  1778. {
  1779. case '\n':
  1780. if (syntax & RE_NEWLINE_ALT)
  1781. token->type = OP_ALT;
  1782. break;
  1783. case '|':
  1784. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_NO_BK_VBAR))
  1785. token->type = OP_ALT;
  1786. break;
  1787. case '*':
  1788. token->type = OP_DUP_ASTERISK;
  1789. break;
  1790. case '+':
  1791. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM))
  1792. token->type = OP_DUP_PLUS;
  1793. break;
  1794. case '?':
  1795. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM))
  1796. token->type = OP_DUP_QUESTION;
  1797. break;
  1798. case '{':
  1799. if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  1800. token->type = OP_OPEN_DUP_NUM;
  1801. break;
  1802. case '}':
  1803. if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  1804. token->type = OP_CLOSE_DUP_NUM;
  1805. break;
  1806. case '(':
  1807. if (syntax & RE_NO_BK_PARENS)
  1808. token->type = OP_OPEN_SUBEXP;
  1809. break;
  1810. case ')':
  1811. if (syntax & RE_NO_BK_PARENS)
  1812. token->type = OP_CLOSE_SUBEXP;
  1813. break;
  1814. case '[':
  1815. token->type = OP_OPEN_BRACKET;
  1816. break;
  1817. case '.':
  1818. token->type = OP_PERIOD;
  1819. break;
  1820. case '^':
  1821. if (!(syntax & (RE_CONTEXT_INDEP_ANCHORS | RE_CARET_ANCHORS_HERE)) &&
  1822. re_string_cur_idx (input) != 0)
  1823. {
  1824. char prev = re_string_peek_byte (input, -1);
  1825. if (!(syntax & RE_NEWLINE_ALT) || prev != '\n')
  1826. break;
  1827. }
  1828. token->type = ANCHOR;
  1829. token->opr.ctx_type = LINE_FIRST;
  1830. break;
  1831. case '$':
  1832. if (!(syntax & RE_CONTEXT_INDEP_ANCHORS) &&
  1833. re_string_cur_idx (input) + 1 != re_string_length (input))
  1834. {
  1835. re_token_t next;
  1836. re_string_skip_bytes (input, 1);
  1837. peek_token (&next, input, syntax);
  1838. re_string_skip_bytes (input, -1);
  1839. if (next.type != OP_ALT && next.type != OP_CLOSE_SUBEXP)
  1840. break;
  1841. }
  1842. token->type = ANCHOR;
  1843. token->opr.ctx_type = LINE_LAST;
  1844. break;
  1845. default:
  1846. break;
  1847. }
  1848. return 1;
  1849. }
  1850. /* Peek a token from INPUT, and return the length of the token.
  1851. We must not use this function out of bracket expressions. */
  1852. static int
  1853. internal_function
  1854. peek_token_bracket (re_token_t *token, re_string_t *input, reg_syntax_t syntax)
  1855. {
  1856. unsigned char c;
  1857. if (re_string_eoi (input))
  1858. {
  1859. token->type = END_OF_RE;
  1860. return 0;
  1861. }
  1862. c = re_string_peek_byte (input, 0);
  1863. token->opr.c = c;
  1864. #ifdef RE_ENABLE_I18N
  1865. if (input->mb_cur_max > 1 &&
  1866. !re_string_first_byte (input, re_string_cur_idx (input)))
  1867. {
  1868. token->type = CHARACTER;
  1869. return 1;
  1870. }
  1871. #endif /* RE_ENABLE_I18N */
  1872. if (c == '\\' && (syntax & RE_BACKSLASH_ESCAPE_IN_LISTS)
  1873. && re_string_cur_idx (input) + 1 < re_string_length (input))
  1874. {
  1875. /* In this case, '\' escape a character. */
  1876. unsigned char c2;
  1877. re_string_skip_bytes (input, 1);
  1878. c2 = re_string_peek_byte (input, 0);
  1879. token->opr.c = c2;
  1880. token->type = CHARACTER;
  1881. return 1;
  1882. }
  1883. if (c == '[') /* '[' is a special char in a bracket exps. */
  1884. {
  1885. unsigned char c2;
  1886. int token_len;
  1887. if (re_string_cur_idx (input) + 1 < re_string_length (input))
  1888. c2 = re_string_peek_byte (input, 1);
  1889. else
  1890. c2 = 0;
  1891. token->opr.c = c2;
  1892. token_len = 2;
  1893. switch (c2)
  1894. {
  1895. case '.':
  1896. token->type = OP_OPEN_COLL_ELEM;
  1897. break;
  1898. case '=':
  1899. token->type = OP_OPEN_EQUIV_CLASS;
  1900. break;
  1901. case ':':
  1902. if (syntax & RE_CHAR_CLASSES)
  1903. {
  1904. token->type = OP_OPEN_CHAR_CLASS;
  1905. break;
  1906. }
  1907. /* else fall through. */
  1908. default:
  1909. token->type = CHARACTER;
  1910. token->opr.c = c;
  1911. token_len = 1;
  1912. break;
  1913. }
  1914. return token_len;
  1915. }
  1916. switch (c)
  1917. {
  1918. case '-':
  1919. token->type = OP_CHARSET_RANGE;
  1920. break;
  1921. case ']':
  1922. token->type = OP_CLOSE_BRACKET;
  1923. break;
  1924. case '^':
  1925. token->type = OP_NON_MATCH_LIST;
  1926. break;
  1927. default:
  1928. token->type = CHARACTER;
  1929. }
  1930. return 1;
  1931. }
  1932. /* Functions for parser. */
  1933. /* Entry point of the parser.
  1934. Parse the regular expression REGEXP and return the structure tree.
  1935. If an error occurs, ERR is set by error code, and return NULL.
  1936. This function build the following tree, from regular expression <reg_exp>:
  1937. CAT
  1938. / \
  1939. / \
  1940. <reg_exp> EOR
  1941. CAT means concatenation.
  1942. EOR means end of regular expression. */
  1943. static bin_tree_t *
  1944. parse (re_string_t *regexp, regex_t *preg, reg_syntax_t syntax,
  1945. reg_errcode_t *err)
  1946. {
  1947. re_dfa_t *dfa = preg->buffer;
  1948. bin_tree_t *tree, *eor, *root;
  1949. re_token_t current_token;
  1950. dfa->syntax = syntax;
  1951. fetch_token (&current_token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  1952. tree = parse_reg_exp (regexp, preg, &current_token, syntax, 0, err);
  1953. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  1954. return NULL;
  1955. eor = create_tree (dfa, NULL, NULL, END_OF_RE);
  1956. if (tree != NULL)
  1957. root = create_tree (dfa, tree, eor, CONCAT);
  1958. else
  1959. root = eor;
  1960. if (BE (eor == NULL || root == NULL, 0))
  1961. {
  1962. *err = REG_ESPACE;
  1963. return NULL;
  1964. }
  1965. return root;
  1966. }
  1967. /* This function build the following tree, from regular expression
  1968. <branch1>|<branch2>:
  1969. ALT
  1970. / \
  1971. / \
  1972. <branch1> <branch2>
  1973. ALT means alternative, which represents the operator '|'. */
  1974. static bin_tree_t *
  1975. parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
  1976. reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
  1977. {
  1978. re_dfa_t *dfa = preg->buffer;
  1979. bin_tree_t *tree, *branch = NULL;
  1980. tree = parse_branch (regexp, preg, token, syntax, nest, err);
  1981. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  1982. return NULL;
  1983. while (token->type == OP_ALT)
  1984. {
  1985. fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  1986. if (token->type != OP_ALT && token->type != END_OF_RE
  1987. && (nest == 0 || token->type != OP_CLOSE_SUBEXP))
  1988. {
  1989. branch = parse_branch (regexp, preg, token, syntax, nest, err);
  1990. if (BE (*err != REG_NOERROR && branch == NULL, 0))
  1991. return NULL;
  1992. }
  1993. else
  1994. branch = NULL;
  1995. tree = create_tree (dfa, tree, branch, OP_ALT);
  1996. if (BE (tree == NULL, 0))
  1997. {
  1998. *err = REG_ESPACE;
  1999. return NULL;
  2000. }
  2001. }
  2002. return tree;
  2003. }
  2004. /* This function build the following tree, from regular expression
  2005. <exp1><exp2>:
  2006. CAT
  2007. / \
  2008. / \
  2009. <exp1> <exp2>
  2010. CAT means concatenation. */
  2011. static bin_tree_t *
  2012. parse_branch (re_string_t *regexp, regex_t *preg, re_token_t *token,
  2013. reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
  2014. {
  2015. bin_tree_t *tree, *expr;
  2016. re_dfa_t *dfa = preg->buffer;
  2017. tree = parse_expression (regexp, preg, token, syntax, nest, err);
  2018. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  2019. return NULL;
  2020. while (token->type != OP_ALT && token->type != END_OF_RE
  2021. && (nest == 0 || token->type != OP_CLOSE_SUBEXP))
  2022. {
  2023. expr = parse_expression (regexp, preg, token, syntax, nest, err);
  2024. if (BE (*err != REG_NOERROR && expr == NULL, 0))
  2025. {
  2026. if (tree != NULL)
  2027. postorder (tree, free_tree, NULL);
  2028. return NULL;
  2029. }
  2030. if (tree != NULL && expr != NULL)
  2031. {
  2032. bin_tree_t *newtree = create_tree (dfa, tree, expr, CONCAT);
  2033. if (newtree == NULL)
  2034. {
  2035. postorder (expr, free_tree, NULL);
  2036. postorder (tree, free_tree, NULL);
  2037. *err = REG_ESPACE;
  2038. return NULL;
  2039. }
  2040. tree = newtree;
  2041. }
  2042. else if (tree == NULL)
  2043. tree = expr;
  2044. /* Otherwise expr == NULL, we don't need to create new tree. */
  2045. }
  2046. return tree;
  2047. }
  2048. /* This function build the following tree, from regular expression a*:
  2049. *
  2050. |
  2051. a
  2052. */
  2053. static bin_tree_t *
  2054. parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
  2055. reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
  2056. {
  2057. re_dfa_t *dfa = preg->buffer;
  2058. bin_tree_t *tree;
  2059. switch (token->type)
  2060. {
  2061. case CHARACTER:
  2062. tree = create_token_tree (dfa, NULL, NULL, token);
  2063. if (BE (tree == NULL, 0))
  2064. {
  2065. *err = REG_ESPACE;
  2066. return NULL;
  2067. }
  2068. #ifdef RE_ENABLE_I18N
  2069. if (dfa->mb_cur_max > 1)
  2070. {
  2071. while (!re_string_eoi (regexp)
  2072. && !re_string_first_byte (regexp, re_string_cur_idx (regexp)))
  2073. {
  2074. bin_tree_t *mbc_remain;
  2075. fetch_token (token, regexp, syntax);
  2076. mbc_remain = create_token_tree (dfa, NULL, NULL, token);
  2077. tree = create_tree (dfa, tree, mbc_remain, CONCAT);
  2078. if (BE (mbc_remain == NULL || tree == NULL, 0))
  2079. {
  2080. *err = REG_ESPACE;
  2081. return NULL;
  2082. }
  2083. }
  2084. }
  2085. #endif
  2086. break;
  2087. case OP_OPEN_SUBEXP:
  2088. tree = parse_sub_exp (regexp, preg, token, syntax, nest + 1, err);
  2089. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  2090. return NULL;
  2091. break;
  2092. case OP_OPEN_BRACKET:
  2093. tree = parse_bracket_exp (regexp, dfa, token, syntax, err);
  2094. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  2095. return NULL;
  2096. break;
  2097. case OP_BACK_REF:
  2098. if (!BE (dfa->completed_bkref_map & (1 << token->opr.idx), 1))
  2099. {
  2100. *err = REG_ESUBREG;
  2101. return NULL;
  2102. }
  2103. dfa->used_bkref_map |= 1 << token->opr.idx;
  2104. tree = create_token_tree (dfa, NULL, NULL, token);
  2105. if (BE (tree == NULL, 0))
  2106. {
  2107. *err = REG_ESPACE;
  2108. return NULL;
  2109. }
  2110. ++dfa->nbackref;
  2111. dfa->has_mb_node = 1;
  2112. break;
  2113. case OP_OPEN_DUP_NUM:
  2114. if (syntax & RE_CONTEXT_INVALID_DUP)
  2115. {
  2116. *err = REG_BADRPT;
  2117. return NULL;
  2118. }
  2119. /* FALLTHROUGH */
  2120. case OP_DUP_ASTERISK:
  2121. case OP_DUP_PLUS:
  2122. case OP_DUP_QUESTION:
  2123. if (syntax & RE_CONTEXT_INVALID_OPS)
  2124. {
  2125. *err = REG_BADRPT;
  2126. return NULL;
  2127. }
  2128. else if (syntax & RE_CONTEXT_INDEP_OPS)
  2129. {
  2130. fetch_token (token, regexp, syntax);
  2131. return parse_expression (regexp, preg, token, syntax, nest, err);
  2132. }
  2133. /* else fall through */
  2134. case OP_CLOSE_SUBEXP:
  2135. if ((token->type == OP_CLOSE_SUBEXP) &&
  2136. !(syntax & RE_UNMATCHED_RIGHT_PAREN_ORD))
  2137. {
  2138. *err = REG_ERPAREN;
  2139. return NULL;
  2140. }
  2141. /* else fall through */
  2142. case OP_CLOSE_DUP_NUM:
  2143. /* We treat it as a normal character. */
  2144. /* Then we can these characters as normal characters. */
  2145. token->type = CHARACTER;
  2146. /* mb_partial and word_char bits should be initialized already
  2147. by peek_token. */
  2148. tree = create_token_tree (dfa, NULL, NULL, token);
  2149. if (BE (tree == NULL, 0))
  2150. {
  2151. *err = REG_ESPACE;
  2152. return NULL;
  2153. }
  2154. break;
  2155. case ANCHOR:
  2156. if ((token->opr.ctx_type
  2157. & (WORD_DELIM | NOT_WORD_DELIM | WORD_FIRST | WORD_LAST))
  2158. && dfa->word_ops_used == 0)
  2159. init_word_char (dfa);
  2160. if (token->opr.ctx_type == WORD_DELIM
  2161. || token->opr.ctx_type == NOT_WORD_DELIM)
  2162. {
  2163. bin_tree_t *tree_first, *tree_last;
  2164. if (token->opr.ctx_type == WORD_DELIM)
  2165. {
  2166. token->opr.ctx_type = WORD_FIRST;
  2167. tree_first = create_token_tree (dfa, NULL, NULL, token);
  2168. token->opr.ctx_type = WORD_LAST;
  2169. }
  2170. else
  2171. {
  2172. token->opr.ctx_type = INSIDE_WORD;
  2173. tree_first = create_token_tree (dfa, NULL, NULL, token);
  2174. token->opr.ctx_type = INSIDE_NOTWORD;
  2175. }
  2176. tree_last = create_token_tree (dfa, NULL, NULL, token);
  2177. tree = create_tree (dfa, tree_first, tree_last, OP_ALT);
  2178. if (BE (tree_first == NULL || tree_last == NULL || tree == NULL, 0))
  2179. {
  2180. *err = REG_ESPACE;
  2181. return NULL;
  2182. }
  2183. }
  2184. else
  2185. {
  2186. tree = create_token_tree (dfa, NULL, NULL, token);
  2187. if (BE (tree == NULL, 0))
  2188. {
  2189. *err = REG_ESPACE;
  2190. return NULL;
  2191. }
  2192. }
  2193. /* We must return here, since ANCHORs can't be followed
  2194. by repetition operators.
  2195. eg. RE"^*" is invalid or "<ANCHOR(^)><CHAR(*)>",
  2196. it must not be "<ANCHOR(^)><REPEAT(*)>". */
  2197. fetch_token (token, regexp, syntax);
  2198. return tree;
  2199. case OP_PERIOD:
  2200. tree = create_token_tree (dfa, NULL, NULL, token);
  2201. if (BE (tree == NULL, 0))
  2202. {
  2203. *err = REG_ESPACE;
  2204. return NULL;
  2205. }
  2206. if (dfa->mb_cur_max > 1)
  2207. dfa->has_mb_node = 1;
  2208. break;
  2209. case OP_WORD:
  2210. case OP_NOTWORD:
  2211. tree = build_charclass_op (dfa, regexp->trans,
  2212. "alnum",
  2213. "_",
  2214. token->type == OP_NOTWORD, err);
  2215. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  2216. return NULL;
  2217. break;
  2218. case OP_SPACE:
  2219. case OP_NOTSPACE:
  2220. tree = build_charclass_op (dfa, regexp->trans,
  2221. "space",
  2222. "",
  2223. token->type == OP_NOTSPACE, err);
  2224. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  2225. return NULL;
  2226. break;
  2227. case OP_ALT:
  2228. case END_OF_RE:
  2229. return NULL;
  2230. case BACK_SLASH:
  2231. *err = REG_EESCAPE;
  2232. return NULL;
  2233. default:
  2234. /* Must not happen? */
  2235. #ifdef DEBUG
  2236. assert (0);
  2237. #endif
  2238. return NULL;
  2239. }
  2240. fetch_token (token, regexp, syntax);
  2241. while (token->type == OP_DUP_ASTERISK || token->type == OP_DUP_PLUS
  2242. || token->type == OP_DUP_QUESTION || token->type == OP_OPEN_DUP_NUM)
  2243. {
  2244. tree = parse_dup_op (tree, regexp, dfa, token, syntax, err);
  2245. if (BE (*err != REG_NOERROR && tree == NULL, 0))
  2246. return NULL;
  2247. /* In BRE consecutive duplications are not allowed. */
  2248. if ((syntax & RE_CONTEXT_INVALID_DUP)
  2249. && (token->type == OP_DUP_ASTERISK
  2250. || token->type == OP_OPEN_DUP_NUM))
  2251. {
  2252. *err = REG_BADRPT;
  2253. return NULL;
  2254. }
  2255. }
  2256. return tree;
  2257. }
  2258. /* This function build the following tree, from regular expression
  2259. (<reg_exp>):
  2260. SUBEXP
  2261. |
  2262. <reg_exp>
  2263. */
  2264. static bin_tree_t *
  2265. parse_sub_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
  2266. reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
  2267. {
  2268. re_dfa_t *dfa = preg->buffer;
  2269. bin_tree_t *tree;
  2270. size_t cur_nsub;
  2271. cur_nsub = preg->re_nsub++;
  2272. fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  2273. /* The subexpression may be a null string. */
  2274. if (token->type == OP_CLOSE_SUBEXP)
  2275. tree = NULL;
  2276. else
  2277. {
  2278. tree = parse_reg_exp (regexp, preg, token, syntax, nest, err);
  2279. if (BE (*err == REG_NOERROR && token->type != OP_CLOSE_SUBEXP, 0))
  2280. {
  2281. if (tree != NULL)
  2282. postorder (tree, free_tree, NULL);
  2283. *err = REG_EPAREN;
  2284. }
  2285. if (BE (*err != REG_NOERROR, 0))
  2286. return NULL;
  2287. }
  2288. if (cur_nsub <= '9' - '1')
  2289. dfa->completed_bkref_map |= 1 << cur_nsub;
  2290. tree = create_tree (dfa, tree, NULL, SUBEXP);
  2291. if (BE (tree == NULL, 0))
  2292. {
  2293. *err = REG_ESPACE;
  2294. return NULL;
  2295. }
  2296. tree->token.opr.idx = cur_nsub;
  2297. return tree;
  2298. }
  2299. /* This function parse repetition operators like "*", "+", "{1,3}" etc. */
  2300. static bin_tree_t *
  2301. parse_dup_op (bin_tree_t *elem, re_string_t *regexp, re_dfa_t *dfa,
  2302. re_token_t *token, reg_syntax_t syntax, reg_errcode_t *err)
  2303. {
  2304. bin_tree_t *tree = NULL, *old_tree = NULL;
  2305. Idx i, start, end, start_idx = re_string_cur_idx (regexp);
  2306. re_token_t start_token = *token;
  2307. if (token->type == OP_OPEN_DUP_NUM)
  2308. {
  2309. end = 0;
  2310. start = fetch_number (regexp, token, syntax);
  2311. if (start == REG_MISSING)
  2312. {
  2313. if (token->type == CHARACTER && token->opr.c == ',')
  2314. start = 0; /* We treat "{,m}" as "{0,m}". */
  2315. else
  2316. {
  2317. *err = REG_BADBR; /* <re>{} is invalid. */
  2318. return NULL;
  2319. }
  2320. }
  2321. if (BE (start != REG_ERROR, 1))
  2322. {
  2323. /* We treat "{n}" as "{n,n}". */
  2324. end = ((token->type == OP_CLOSE_DUP_NUM) ? start
  2325. : ((token->type == CHARACTER && token->opr.c == ',')
  2326. ? fetch_number (regexp, token, syntax) : REG_ERROR));
  2327. }
  2328. if (BE (start == REG_ERROR || end == REG_ERROR, 0))
  2329. {
  2330. /* Invalid sequence. */
  2331. if (BE (!(syntax & RE_INVALID_INTERVAL_ORD), 0))
  2332. {
  2333. if (token->type == END_OF_RE)
  2334. *err = REG_EBRACE;
  2335. else
  2336. *err = REG_BADBR;
  2337. return NULL;
  2338. }
  2339. /* If the syntax bit is set, rollback. */
  2340. re_string_set_index (regexp, start_idx);
  2341. *token = start_token;
  2342. token->type = CHARACTER;
  2343. /* mb_partial and word_char bits should be already initialized by
  2344. peek_token. */
  2345. return elem;
  2346. }
  2347. if (BE ((end != REG_MISSING && start > end)
  2348. || token->type != OP_CLOSE_DUP_NUM, 0))
  2349. {
  2350. /* First number greater than second. */
  2351. *err = REG_BADBR;
  2352. return NULL;
  2353. }
  2354. if (BE (RE_DUP_MAX < (end == REG_MISSING ? start : end), 0))
  2355. {
  2356. *err = REG_ESIZE;
  2357. return NULL;
  2358. }
  2359. }
  2360. else
  2361. {
  2362. start = (token->type == OP_DUP_PLUS) ? 1 : 0;
  2363. end = (token->type == OP_DUP_QUESTION) ? 1 : REG_MISSING;
  2364. }
  2365. fetch_token (token, regexp, syntax);
  2366. if (BE (elem == NULL, 0))
  2367. return NULL;
  2368. if (BE (start == 0 && end == 0, 0))
  2369. {
  2370. postorder (elem, free_tree, NULL);
  2371. return NULL;
  2372. }
  2373. /* Extract "<re>{n,m}" to "<re><re>...<re><re>{0,<m-n>}". */
  2374. if (BE (start > 0, 0))
  2375. {
  2376. tree = elem;
  2377. for (i = 2; i <= start; ++i)
  2378. {
  2379. elem = duplicate_tree (elem, dfa);
  2380. tree = create_tree (dfa, tree, elem, CONCAT);
  2381. if (BE (elem == NULL || tree == NULL, 0))
  2382. goto parse_dup_op_espace;
  2383. }
  2384. if (start == end)
  2385. return tree;
  2386. /* Duplicate ELEM before it is marked optional. */
  2387. elem = duplicate_tree (elem, dfa);
  2388. old_tree = tree;
  2389. }
  2390. else
  2391. old_tree = NULL;
  2392. if (elem->token.type == SUBEXP)
  2393. {
  2394. uintptr_t subidx = elem->token.opr.idx;
  2395. postorder (elem, mark_opt_subexp, (void *) subidx);
  2396. }
  2397. tree = create_tree (dfa, elem, NULL,
  2398. (end == REG_MISSING ? OP_DUP_ASTERISK : OP_ALT));
  2399. if (BE (tree == NULL, 0))
  2400. goto parse_dup_op_espace;
  2401. /* From gnulib's "intprops.h":
  2402. True if the arithmetic type T is signed. */
  2403. #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
  2404. /* This loop is actually executed only when end != REG_MISSING,
  2405. to rewrite <re>{0,n} as (<re>(<re>...<re>?)?)?... We have
  2406. already created the start+1-th copy. */
  2407. if (TYPE_SIGNED (Idx) || end != REG_MISSING)
  2408. for (i = start + 2; i <= end; ++i)
  2409. {
  2410. elem = duplicate_tree (elem, dfa);
  2411. tree = create_tree (dfa, tree, elem, CONCAT);
  2412. if (BE (elem == NULL || tree == NULL, 0))
  2413. goto parse_dup_op_espace;
  2414. tree = create_tree (dfa, tree, NULL, OP_ALT);
  2415. if (BE (tree == NULL, 0))
  2416. goto parse_dup_op_espace;
  2417. }
  2418. if (old_tree)
  2419. tree = create_tree (dfa, old_tree, tree, CONCAT);
  2420. return tree;
  2421. parse_dup_op_espace:
  2422. *err = REG_ESPACE;
  2423. return NULL;
  2424. }
  2425. /* Size of the names for collating symbol/equivalence_class/character_class.
  2426. I'm not sure, but maybe enough. */
  2427. #define BRACKET_NAME_BUF_SIZE 32
  2428. #ifndef _LIBC
  2429. /* Local function for parse_bracket_exp only used in case of NOT _LIBC.
  2430. Build the range expression which starts from START_ELEM, and ends
  2431. at END_ELEM. The result are written to MBCSET and SBCSET.
  2432. RANGE_ALLOC is the allocated size of mbcset->range_starts, and
  2433. mbcset->range_ends, is a pointer argument since we may
  2434. update it. */
  2435. static reg_errcode_t
  2436. internal_function
  2437. # ifdef RE_ENABLE_I18N
  2438. build_range_exp (const reg_syntax_t syntax,
  2439. bitset_t sbcset,
  2440. re_charset_t *mbcset,
  2441. Idx *range_alloc,
  2442. const bracket_elem_t *start_elem,
  2443. const bracket_elem_t *end_elem)
  2444. # else /* not RE_ENABLE_I18N */
  2445. build_range_exp (const reg_syntax_t syntax,
  2446. bitset_t sbcset,
  2447. const bracket_elem_t *start_elem,
  2448. const bracket_elem_t *end_elem)
  2449. # endif /* not RE_ENABLE_I18N */
  2450. {
  2451. unsigned int start_ch, end_ch;
  2452. /* Equivalence Classes and Character Classes can't be a range start/end. */
  2453. if (BE (start_elem->type == EQUIV_CLASS || start_elem->type == CHAR_CLASS
  2454. || end_elem->type == EQUIV_CLASS || end_elem->type == CHAR_CLASS,
  2455. 0))
  2456. return REG_ERANGE;
  2457. /* We can handle no multi character collating elements without libc
  2458. support. */
  2459. if (BE ((start_elem->type == COLL_SYM
  2460. && strlen ((char *) start_elem->opr.name) > 1)
  2461. || (end_elem->type == COLL_SYM
  2462. && strlen ((char *) end_elem->opr.name) > 1), 0))
  2463. return REG_ECOLLATE;
  2464. # ifdef RE_ENABLE_I18N
  2465. {
  2466. wchar_t wc;
  2467. wint_t start_wc;
  2468. wint_t end_wc;
  2469. start_ch = ((start_elem->type == SB_CHAR) ? start_elem->opr.ch
  2470. : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0]
  2471. : 0));
  2472. end_ch = ((end_elem->type == SB_CHAR) ? end_elem->opr.ch
  2473. : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0]
  2474. : 0));
  2475. start_wc = ((start_elem->type == SB_CHAR || start_elem->type == COLL_SYM)
  2476. ? __btowc (start_ch) : start_elem->opr.wch);
  2477. end_wc = ((end_elem->type == SB_CHAR || end_elem->type == COLL_SYM)
  2478. ? __btowc (end_ch) : end_elem->opr.wch);
  2479. if (start_wc == WEOF || end_wc == WEOF)
  2480. return REG_ECOLLATE;
  2481. else if (BE ((syntax & RE_NO_EMPTY_RANGES) && start_wc > end_wc, 0))
  2482. return REG_ERANGE;
  2483. /* Got valid collation sequence values, add them as a new entry.
  2484. However, for !_LIBC we have no collation elements: if the
  2485. character set is single byte, the single byte character set
  2486. that we build below suffices. parse_bracket_exp passes
  2487. no MBCSET if dfa->mb_cur_max == 1. */
  2488. if (mbcset)
  2489. {
  2490. /* Check the space of the arrays. */
  2491. if (BE (*range_alloc == mbcset->nranges, 0))
  2492. {
  2493. /* There is not enough space, need realloc. */
  2494. wchar_t *new_array_start, *new_array_end;
  2495. Idx new_nranges;
  2496. /* +1 in case of mbcset->nranges is 0. */
  2497. new_nranges = 2 * mbcset->nranges + 1;
  2498. /* Use realloc since mbcset->range_starts and mbcset->range_ends
  2499. are NULL if *range_alloc == 0. */
  2500. new_array_start = re_realloc (mbcset->range_starts, wchar_t,
  2501. new_nranges);
  2502. new_array_end = re_realloc (mbcset->range_ends, wchar_t,
  2503. new_nranges);
  2504. if (BE (new_array_start == NULL || new_array_end == NULL, 0))
  2505. return REG_ESPACE;
  2506. mbcset->range_starts = new_array_start;
  2507. mbcset->range_ends = new_array_end;
  2508. *range_alloc = new_nranges;
  2509. }
  2510. mbcset->range_starts[mbcset->nranges] = start_wc;
  2511. mbcset->range_ends[mbcset->nranges++] = end_wc;
  2512. }
  2513. /* Build the table for single byte characters. */
  2514. for (wc = 0; wc < SBC_MAX; ++wc)
  2515. {
  2516. if (start_wc <= wc && wc <= end_wc)
  2517. bitset_set (sbcset, wc);
  2518. }
  2519. }
  2520. # else /* not RE_ENABLE_I18N */
  2521. {
  2522. unsigned int ch;
  2523. start_ch = ((start_elem->type == SB_CHAR ) ? start_elem->opr.ch
  2524. : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0]
  2525. : 0));
  2526. end_ch = ((end_elem->type == SB_CHAR ) ? end_elem->opr.ch
  2527. : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0]
  2528. : 0));
  2529. if (start_ch > end_ch)
  2530. return REG_ERANGE;
  2531. /* Build the table for single byte characters. */
  2532. for (ch = 0; ch < SBC_MAX; ++ch)
  2533. if (start_ch <= ch && ch <= end_ch)
  2534. bitset_set (sbcset, ch);
  2535. }
  2536. # endif /* not RE_ENABLE_I18N */
  2537. return REG_NOERROR;
  2538. }
  2539. #endif /* not _LIBC */
  2540. #ifndef _LIBC
  2541. /* Helper function for parse_bracket_exp only used in case of NOT _LIBC..
  2542. Build the collating element which is represented by NAME.
  2543. The result are written to MBCSET and SBCSET.
  2544. COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a
  2545. pointer argument since we may update it. */
  2546. static reg_errcode_t
  2547. internal_function
  2548. # ifdef RE_ENABLE_I18N
  2549. build_collating_symbol (bitset_t sbcset, re_charset_t *mbcset,
  2550. Idx *coll_sym_alloc, const unsigned char *name)
  2551. # else /* not RE_ENABLE_I18N */
  2552. build_collating_symbol (bitset_t sbcset, const unsigned char *name)
  2553. # endif /* not RE_ENABLE_I18N */
  2554. {
  2555. size_t name_len = strlen ((const char *) name);
  2556. if (BE (name_len != 1, 0))
  2557. return REG_ECOLLATE;
  2558. else
  2559. {
  2560. bitset_set (sbcset, name[0]);
  2561. return REG_NOERROR;
  2562. }
  2563. }
  2564. #endif /* not _LIBC */
  2565. /* This function parse bracket expression like "[abc]", "[a-c]",
  2566. "[[.a-a.]]" etc. */
  2567. static bin_tree_t *
  2568. parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
  2569. reg_syntax_t syntax, reg_errcode_t *err)
  2570. {
  2571. #ifdef _LIBC
  2572. const unsigned char *collseqmb;
  2573. const char *collseqwc;
  2574. uint32_t nrules;
  2575. int32_t table_size;
  2576. const int32_t *symb_table;
  2577. const unsigned char *extra;
  2578. /* Local function for parse_bracket_exp used in _LIBC environment.
  2579. Seek the collating symbol entry corresponding to NAME.
  2580. Return the index of the symbol in the SYMB_TABLE,
  2581. or -1 if not found. */
  2582. auto inline int32_t
  2583. __attribute__ ((always_inline))
  2584. seek_collating_symbol_entry (const unsigned char *name, size_t name_len)
  2585. {
  2586. int32_t elem;
  2587. for (elem = 0; elem < table_size; elem++)
  2588. if (symb_table[2 * elem] != 0)
  2589. {
  2590. int32_t idx = symb_table[2 * elem + 1];
  2591. /* Skip the name of collating element name. */
  2592. idx += 1 + extra[idx];
  2593. if (/* Compare the length of the name. */
  2594. name_len == extra[idx]
  2595. /* Compare the name. */
  2596. && memcmp (name, &extra[idx + 1], name_len) == 0)
  2597. /* Yep, this is the entry. */
  2598. return elem;
  2599. }
  2600. return -1;
  2601. }
  2602. /* Local function for parse_bracket_exp used in _LIBC environment.
  2603. Look up the collation sequence value of BR_ELEM.
  2604. Return the value if succeeded, UINT_MAX otherwise. */
  2605. auto inline unsigned int
  2606. __attribute__ ((always_inline))
  2607. lookup_collation_sequence_value (bracket_elem_t *br_elem)
  2608. {
  2609. if (br_elem->type == SB_CHAR)
  2610. {
  2611. /*
  2612. if (MB_CUR_MAX == 1)
  2613. */
  2614. if (nrules == 0)
  2615. return collseqmb[br_elem->opr.ch];
  2616. else
  2617. {
  2618. wint_t wc = __btowc (br_elem->opr.ch);
  2619. return __collseq_table_lookup (collseqwc, wc);
  2620. }
  2621. }
  2622. else if (br_elem->type == MB_CHAR)
  2623. {
  2624. if (nrules != 0)
  2625. return __collseq_table_lookup (collseqwc, br_elem->opr.wch);
  2626. }
  2627. else if (br_elem->type == COLL_SYM)
  2628. {
  2629. size_t sym_name_len = strlen ((char *) br_elem->opr.name);
  2630. if (nrules != 0)
  2631. {
  2632. int32_t elem, idx;
  2633. elem = seek_collating_symbol_entry (br_elem->opr.name,
  2634. sym_name_len);
  2635. if (elem != -1)
  2636. {
  2637. /* We found the entry. */
  2638. idx = symb_table[2 * elem + 1];
  2639. /* Skip the name of collating element name. */
  2640. idx += 1 + extra[idx];
  2641. /* Skip the byte sequence of the collating element. */
  2642. idx += 1 + extra[idx];
  2643. /* Adjust for the alignment. */
  2644. idx = (idx + 3) & ~3;
  2645. /* Skip the multibyte collation sequence value. */
  2646. idx += sizeof (unsigned int);
  2647. /* Skip the wide char sequence of the collating element. */
  2648. idx += sizeof (unsigned int) *
  2649. (1 + *(unsigned int *) (extra + idx));
  2650. /* Return the collation sequence value. */
  2651. return *(unsigned int *) (extra + idx);
  2652. }
  2653. else if (sym_name_len == 1)
  2654. {
  2655. /* No valid character. Match it as a single byte
  2656. character. */
  2657. return collseqmb[br_elem->opr.name[0]];
  2658. }
  2659. }
  2660. else if (sym_name_len == 1)
  2661. return collseqmb[br_elem->opr.name[0]];
  2662. }
  2663. return UINT_MAX;
  2664. }
  2665. /* Local function for parse_bracket_exp used in _LIBC environment.
  2666. Build the range expression which starts from START_ELEM, and ends
  2667. at END_ELEM. The result are written to MBCSET and SBCSET.
  2668. RANGE_ALLOC is the allocated size of mbcset->range_starts, and
  2669. mbcset->range_ends, is a pointer argument since we may
  2670. update it. */
  2671. auto inline reg_errcode_t
  2672. __attribute__ ((always_inline))
  2673. build_range_exp (bitset_t sbcset, re_charset_t *mbcset, int *range_alloc,
  2674. bracket_elem_t *start_elem, bracket_elem_t *end_elem)
  2675. {
  2676. unsigned int ch;
  2677. uint32_t start_collseq;
  2678. uint32_t end_collseq;
  2679. /* Equivalence Classes and Character Classes can't be a range
  2680. start/end. */
  2681. if (BE (start_elem->type == EQUIV_CLASS || start_elem->type == CHAR_CLASS
  2682. || end_elem->type == EQUIV_CLASS || end_elem->type == CHAR_CLASS,
  2683. 0))
  2684. return REG_ERANGE;
  2685. /* FIXME: Implement rational ranges here, too. */
  2686. start_collseq = lookup_collation_sequence_value (start_elem);
  2687. end_collseq = lookup_collation_sequence_value (end_elem);
  2688. /* Check start/end collation sequence values. */
  2689. if (BE (start_collseq == UINT_MAX || end_collseq == UINT_MAX, 0))
  2690. return REG_ECOLLATE;
  2691. if (BE ((syntax & RE_NO_EMPTY_RANGES) && start_collseq > end_collseq, 0))
  2692. return REG_ERANGE;
  2693. /* Got valid collation sequence values, add them as a new entry.
  2694. However, if we have no collation elements, and the character set
  2695. is single byte, the single byte character set that we
  2696. build below suffices. */
  2697. if (nrules > 0 || dfa->mb_cur_max > 1)
  2698. {
  2699. /* Check the space of the arrays. */
  2700. if (BE (*range_alloc == mbcset->nranges, 0))
  2701. {
  2702. /* There is not enough space, need realloc. */
  2703. uint32_t *new_array_start;
  2704. uint32_t *new_array_end;
  2705. Idx new_nranges;
  2706. /* +1 in case of mbcset->nranges is 0. */
  2707. new_nranges = 2 * mbcset->nranges + 1;
  2708. new_array_start = re_realloc (mbcset->range_starts, uint32_t,
  2709. new_nranges);
  2710. new_array_end = re_realloc (mbcset->range_ends, uint32_t,
  2711. new_nranges);
  2712. if (BE (new_array_start == NULL || new_array_end == NULL, 0))
  2713. return REG_ESPACE;
  2714. mbcset->range_starts = new_array_start;
  2715. mbcset->range_ends = new_array_end;
  2716. *range_alloc = new_nranges;
  2717. }
  2718. mbcset->range_starts[mbcset->nranges] = start_collseq;
  2719. mbcset->range_ends[mbcset->nranges++] = end_collseq;
  2720. }
  2721. /* Build the table for single byte characters. */
  2722. for (ch = 0; ch < SBC_MAX; ch++)
  2723. {
  2724. uint32_t ch_collseq;
  2725. /*
  2726. if (MB_CUR_MAX == 1)
  2727. */
  2728. if (nrules == 0)
  2729. ch_collseq = collseqmb[ch];
  2730. else
  2731. ch_collseq = __collseq_table_lookup (collseqwc, __btowc (ch));
  2732. if (start_collseq <= ch_collseq && ch_collseq <= end_collseq)
  2733. bitset_set (sbcset, ch);
  2734. }
  2735. return REG_NOERROR;
  2736. }
  2737. /* Local function for parse_bracket_exp used in _LIBC environment.
  2738. Build the collating element which is represented by NAME.
  2739. The result are written to MBCSET and SBCSET.
  2740. COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a
  2741. pointer argument since we may update it. */
  2742. auto inline reg_errcode_t
  2743. __attribute__ ((always_inline))
  2744. build_collating_symbol (bitset_t sbcset, re_charset_t *mbcset,
  2745. Idx *coll_sym_alloc, const unsigned char *name)
  2746. {
  2747. int32_t elem, idx;
  2748. size_t name_len = strlen ((const char *) name);
  2749. if (nrules != 0)
  2750. {
  2751. elem = seek_collating_symbol_entry (name, name_len);
  2752. if (elem != -1)
  2753. {
  2754. /* We found the entry. */
  2755. idx = symb_table[2 * elem + 1];
  2756. /* Skip the name of collating element name. */
  2757. idx += 1 + extra[idx];
  2758. }
  2759. else if (name_len == 1)
  2760. {
  2761. /* No valid character, treat it as a normal
  2762. character. */
  2763. bitset_set (sbcset, name[0]);
  2764. return REG_NOERROR;
  2765. }
  2766. else
  2767. return REG_ECOLLATE;
  2768. /* Got valid collation sequence, add it as a new entry. */
  2769. /* Check the space of the arrays. */
  2770. if (BE (*coll_sym_alloc == mbcset->ncoll_syms, 0))
  2771. {
  2772. /* Not enough, realloc it. */
  2773. /* +1 in case of mbcset->ncoll_syms is 0. */
  2774. Idx new_coll_sym_alloc = 2 * mbcset->ncoll_syms + 1;
  2775. /* Use realloc since mbcset->coll_syms is NULL
  2776. if *alloc == 0. */
  2777. int32_t *new_coll_syms = re_realloc (mbcset->coll_syms, int32_t,
  2778. new_coll_sym_alloc);
  2779. if (BE (new_coll_syms == NULL, 0))
  2780. return REG_ESPACE;
  2781. mbcset->coll_syms = new_coll_syms;
  2782. *coll_sym_alloc = new_coll_sym_alloc;
  2783. }
  2784. mbcset->coll_syms[mbcset->ncoll_syms++] = idx;
  2785. return REG_NOERROR;
  2786. }
  2787. else
  2788. {
  2789. if (BE (name_len != 1, 0))
  2790. return REG_ECOLLATE;
  2791. else
  2792. {
  2793. bitset_set (sbcset, name[0]);
  2794. return REG_NOERROR;
  2795. }
  2796. }
  2797. }
  2798. #endif
  2799. re_token_t br_token;
  2800. re_bitset_ptr_t sbcset;
  2801. #ifdef RE_ENABLE_I18N
  2802. re_charset_t *mbcset;
  2803. Idx coll_sym_alloc = 0, range_alloc = 0, mbchar_alloc = 0;
  2804. Idx equiv_class_alloc = 0, char_class_alloc = 0;
  2805. #endif /* not RE_ENABLE_I18N */
  2806. bool non_match = false;
  2807. bin_tree_t *work_tree;
  2808. int token_len;
  2809. bool first_round = true;
  2810. #ifdef _LIBC
  2811. collseqmb = (const unsigned char *)
  2812. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB);
  2813. nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  2814. if (nrules)
  2815. {
  2816. /*
  2817. if (MB_CUR_MAX > 1)
  2818. */
  2819. collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC);
  2820. table_size = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_SYMB_HASH_SIZEMB);
  2821. symb_table = (const int32_t *) _NL_CURRENT (LC_COLLATE,
  2822. _NL_COLLATE_SYMB_TABLEMB);
  2823. extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  2824. _NL_COLLATE_SYMB_EXTRAMB);
  2825. }
  2826. #endif
  2827. sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  2828. #ifdef RE_ENABLE_I18N
  2829. mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1);
  2830. #endif /* RE_ENABLE_I18N */
  2831. #ifdef RE_ENABLE_I18N
  2832. if (BE (sbcset == NULL || mbcset == NULL, 0))
  2833. #else
  2834. if (BE (sbcset == NULL, 0))
  2835. #endif /* RE_ENABLE_I18N */
  2836. {
  2837. re_free (sbcset);
  2838. #ifdef RE_ENABLE_I18N
  2839. re_free (mbcset);
  2840. #endif
  2841. *err = REG_ESPACE;
  2842. return NULL;
  2843. }
  2844. token_len = peek_token_bracket (token, regexp, syntax);
  2845. if (BE (token->type == END_OF_RE, 0))
  2846. {
  2847. *err = REG_BADPAT;
  2848. goto parse_bracket_exp_free_return;
  2849. }
  2850. if (token->type == OP_NON_MATCH_LIST)
  2851. {
  2852. #ifdef RE_ENABLE_I18N
  2853. mbcset->non_match = 1;
  2854. #endif /* not RE_ENABLE_I18N */
  2855. non_match = true;
  2856. if (syntax & RE_HAT_LISTS_NOT_NEWLINE)
  2857. bitset_set (sbcset, '\n');
  2858. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  2859. token_len = peek_token_bracket (token, regexp, syntax);
  2860. if (BE (token->type == END_OF_RE, 0))
  2861. {
  2862. *err = REG_BADPAT;
  2863. goto parse_bracket_exp_free_return;
  2864. }
  2865. }
  2866. /* We treat the first ']' as a normal character. */
  2867. if (token->type == OP_CLOSE_BRACKET)
  2868. token->type = CHARACTER;
  2869. while (1)
  2870. {
  2871. bracket_elem_t start_elem, end_elem;
  2872. unsigned char start_name_buf[BRACKET_NAME_BUF_SIZE];
  2873. unsigned char end_name_buf[BRACKET_NAME_BUF_SIZE];
  2874. reg_errcode_t ret;
  2875. int token_len2 = 0;
  2876. bool is_range_exp = false;
  2877. re_token_t token2;
  2878. start_elem.opr.name = start_name_buf;
  2879. ret = parse_bracket_element (&start_elem, regexp, token, token_len, dfa,
  2880. syntax, first_round);
  2881. if (BE (ret != REG_NOERROR, 0))
  2882. {
  2883. *err = ret;
  2884. goto parse_bracket_exp_free_return;
  2885. }
  2886. first_round = false;
  2887. /* Get information about the next token. We need it in any case. */
  2888. token_len = peek_token_bracket (token, regexp, syntax);
  2889. /* Do not check for ranges if we know they are not allowed. */
  2890. if (start_elem.type != CHAR_CLASS && start_elem.type != EQUIV_CLASS)
  2891. {
  2892. if (BE (token->type == END_OF_RE, 0))
  2893. {
  2894. *err = REG_EBRACK;
  2895. goto parse_bracket_exp_free_return;
  2896. }
  2897. if (token->type == OP_CHARSET_RANGE)
  2898. {
  2899. re_string_skip_bytes (regexp, token_len); /* Skip '-'. */
  2900. token_len2 = peek_token_bracket (&token2, regexp, syntax);
  2901. if (BE (token2.type == END_OF_RE, 0))
  2902. {
  2903. *err = REG_EBRACK;
  2904. goto parse_bracket_exp_free_return;
  2905. }
  2906. if (token2.type == OP_CLOSE_BRACKET)
  2907. {
  2908. /* We treat the last '-' as a normal character. */
  2909. re_string_skip_bytes (regexp, -token_len);
  2910. token->type = CHARACTER;
  2911. }
  2912. else
  2913. is_range_exp = true;
  2914. }
  2915. }
  2916. if (is_range_exp == true)
  2917. {
  2918. end_elem.opr.name = end_name_buf;
  2919. ret = parse_bracket_element (&end_elem, regexp, &token2, token_len2,
  2920. dfa, syntax, true);
  2921. if (BE (ret != REG_NOERROR, 0))
  2922. {
  2923. *err = ret;
  2924. goto parse_bracket_exp_free_return;
  2925. }
  2926. token_len = peek_token_bracket (token, regexp, syntax);
  2927. #ifdef _LIBC
  2928. *err = build_range_exp (sbcset, mbcset, &range_alloc,
  2929. &start_elem, &end_elem);
  2930. #else
  2931. # ifdef RE_ENABLE_I18N
  2932. *err = build_range_exp (syntax, sbcset,
  2933. dfa->mb_cur_max > 1 ? mbcset : NULL,
  2934. &range_alloc, &start_elem, &end_elem);
  2935. # else
  2936. *err = build_range_exp (syntax, sbcset, &start_elem, &end_elem);
  2937. # endif
  2938. #endif /* RE_ENABLE_I18N */
  2939. if (BE (*err != REG_NOERROR, 0))
  2940. goto parse_bracket_exp_free_return;
  2941. }
  2942. else
  2943. {
  2944. switch (start_elem.type)
  2945. {
  2946. case SB_CHAR:
  2947. bitset_set (sbcset, start_elem.opr.ch);
  2948. break;
  2949. #ifdef RE_ENABLE_I18N
  2950. case MB_CHAR:
  2951. /* Check whether the array has enough space. */
  2952. if (BE (mbchar_alloc == mbcset->nmbchars, 0))
  2953. {
  2954. wchar_t *new_mbchars;
  2955. /* Not enough, realloc it. */
  2956. /* +1 in case of mbcset->nmbchars is 0. */
  2957. mbchar_alloc = 2 * mbcset->nmbchars + 1;
  2958. /* Use realloc since array is NULL if *alloc == 0. */
  2959. new_mbchars = re_realloc (mbcset->mbchars, wchar_t,
  2960. mbchar_alloc);
  2961. if (BE (new_mbchars == NULL, 0))
  2962. goto parse_bracket_exp_espace;
  2963. mbcset->mbchars = new_mbchars;
  2964. }
  2965. mbcset->mbchars[mbcset->nmbchars++] = start_elem.opr.wch;
  2966. break;
  2967. #endif /* RE_ENABLE_I18N */
  2968. case EQUIV_CLASS:
  2969. *err = build_equiv_class (sbcset,
  2970. #ifdef RE_ENABLE_I18N
  2971. mbcset, &equiv_class_alloc,
  2972. #endif /* RE_ENABLE_I18N */
  2973. start_elem.opr.name);
  2974. if (BE (*err != REG_NOERROR, 0))
  2975. goto parse_bracket_exp_free_return;
  2976. break;
  2977. case COLL_SYM:
  2978. *err = build_collating_symbol (sbcset,
  2979. #ifdef RE_ENABLE_I18N
  2980. mbcset, &coll_sym_alloc,
  2981. #endif /* RE_ENABLE_I18N */
  2982. start_elem.opr.name);
  2983. if (BE (*err != REG_NOERROR, 0))
  2984. goto parse_bracket_exp_free_return;
  2985. break;
  2986. case CHAR_CLASS:
  2987. *err = build_charclass (regexp->trans, sbcset,
  2988. #ifdef RE_ENABLE_I18N
  2989. mbcset, &char_class_alloc,
  2990. #endif /* RE_ENABLE_I18N */
  2991. (const char *) start_elem.opr.name,
  2992. syntax);
  2993. if (BE (*err != REG_NOERROR, 0))
  2994. goto parse_bracket_exp_free_return;
  2995. break;
  2996. default:
  2997. assert (0);
  2998. break;
  2999. }
  3000. }
  3001. if (BE (token->type == END_OF_RE, 0))
  3002. {
  3003. *err = REG_EBRACK;
  3004. goto parse_bracket_exp_free_return;
  3005. }
  3006. if (token->type == OP_CLOSE_BRACKET)
  3007. break;
  3008. }
  3009. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  3010. /* If it is non-matching list. */
  3011. if (non_match)
  3012. bitset_not (sbcset);
  3013. #ifdef RE_ENABLE_I18N
  3014. /* Ensure only single byte characters are set. */
  3015. if (dfa->mb_cur_max > 1)
  3016. bitset_mask (sbcset, dfa->sb_char);
  3017. if (mbcset->nmbchars || mbcset->ncoll_syms || mbcset->nequiv_classes
  3018. || mbcset->nranges || (dfa->mb_cur_max > 1 && (mbcset->nchar_classes
  3019. || mbcset->non_match)))
  3020. {
  3021. bin_tree_t *mbc_tree;
  3022. int sbc_idx;
  3023. /* Build a tree for complex bracket. */
  3024. dfa->has_mb_node = 1;
  3025. br_token.type = COMPLEX_BRACKET;
  3026. br_token.opr.mbcset = mbcset;
  3027. mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  3028. if (BE (mbc_tree == NULL, 0))
  3029. goto parse_bracket_exp_espace;
  3030. for (sbc_idx = 0; sbc_idx < BITSET_WORDS; ++sbc_idx)
  3031. if (sbcset[sbc_idx])
  3032. break;
  3033. /* If there are no bits set in sbcset, there is no point
  3034. of having both SIMPLE_BRACKET and COMPLEX_BRACKET. */
  3035. if (sbc_idx < BITSET_WORDS)
  3036. {
  3037. /* Build a tree for simple bracket. */
  3038. br_token.type = SIMPLE_BRACKET;
  3039. br_token.opr.sbcset = sbcset;
  3040. work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  3041. if (BE (work_tree == NULL, 0))
  3042. goto parse_bracket_exp_espace;
  3043. /* Then join them by ALT node. */
  3044. work_tree = create_tree (dfa, work_tree, mbc_tree, OP_ALT);
  3045. if (BE (work_tree == NULL, 0))
  3046. goto parse_bracket_exp_espace;
  3047. }
  3048. else
  3049. {
  3050. re_free (sbcset);
  3051. work_tree = mbc_tree;
  3052. }
  3053. }
  3054. else
  3055. #endif /* not RE_ENABLE_I18N */
  3056. {
  3057. #ifdef RE_ENABLE_I18N
  3058. free_charset (mbcset);
  3059. #endif
  3060. /* Build a tree for simple bracket. */
  3061. br_token.type = SIMPLE_BRACKET;
  3062. br_token.opr.sbcset = sbcset;
  3063. work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  3064. if (BE (work_tree == NULL, 0))
  3065. goto parse_bracket_exp_espace;
  3066. }
  3067. return work_tree;
  3068. parse_bracket_exp_espace:
  3069. *err = REG_ESPACE;
  3070. parse_bracket_exp_free_return:
  3071. re_free (sbcset);
  3072. #ifdef RE_ENABLE_I18N
  3073. free_charset (mbcset);
  3074. #endif /* RE_ENABLE_I18N */
  3075. return NULL;
  3076. }
  3077. /* Parse an element in the bracket expression. */
  3078. static reg_errcode_t
  3079. parse_bracket_element (bracket_elem_t *elem, re_string_t *regexp,
  3080. re_token_t *token, int token_len, re_dfa_t *dfa,
  3081. reg_syntax_t syntax, bool accept_hyphen)
  3082. {
  3083. #ifdef RE_ENABLE_I18N
  3084. int cur_char_size;
  3085. cur_char_size = re_string_char_size_at (regexp, re_string_cur_idx (regexp));
  3086. if (cur_char_size > 1)
  3087. {
  3088. elem->type = MB_CHAR;
  3089. elem->opr.wch = re_string_wchar_at (regexp, re_string_cur_idx (regexp));
  3090. re_string_skip_bytes (regexp, cur_char_size);
  3091. return REG_NOERROR;
  3092. }
  3093. #endif /* RE_ENABLE_I18N */
  3094. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  3095. if (token->type == OP_OPEN_COLL_ELEM || token->type == OP_OPEN_CHAR_CLASS
  3096. || token->type == OP_OPEN_EQUIV_CLASS)
  3097. return parse_bracket_symbol (elem, regexp, token);
  3098. if (BE (token->type == OP_CHARSET_RANGE, 0) && !accept_hyphen)
  3099. {
  3100. /* A '-' must only appear as anything but a range indicator before
  3101. the closing bracket. Everything else is an error. */
  3102. re_token_t token2;
  3103. (void) peek_token_bracket (&token2, regexp, syntax);
  3104. if (token2.type != OP_CLOSE_BRACKET)
  3105. /* The actual error value is not standardized since this whole
  3106. case is undefined. But ERANGE makes good sense. */
  3107. return REG_ERANGE;
  3108. }
  3109. elem->type = SB_CHAR;
  3110. elem->opr.ch = token->opr.c;
  3111. return REG_NOERROR;
  3112. }
  3113. /* Parse a bracket symbol in the bracket expression. Bracket symbols are
  3114. such as [:<character_class>:], [.<collating_element>.], and
  3115. [=<equivalent_class>=]. */
  3116. static reg_errcode_t
  3117. parse_bracket_symbol (bracket_elem_t *elem, re_string_t *regexp,
  3118. re_token_t *token)
  3119. {
  3120. unsigned char ch, delim = token->opr.c;
  3121. int i = 0;
  3122. if (re_string_eoi(regexp))
  3123. return REG_EBRACK;
  3124. for (;; ++i)
  3125. {
  3126. if (i >= BRACKET_NAME_BUF_SIZE)
  3127. return REG_EBRACK;
  3128. if (token->type == OP_OPEN_CHAR_CLASS)
  3129. ch = re_string_fetch_byte_case (regexp);
  3130. else
  3131. ch = re_string_fetch_byte (regexp);
  3132. if (re_string_eoi(regexp))
  3133. return REG_EBRACK;
  3134. if (ch == delim && re_string_peek_byte (regexp, 0) == ']')
  3135. break;
  3136. elem->opr.name[i] = ch;
  3137. }
  3138. re_string_skip_bytes (regexp, 1);
  3139. elem->opr.name[i] = '\0';
  3140. switch (token->type)
  3141. {
  3142. case OP_OPEN_COLL_ELEM:
  3143. elem->type = COLL_SYM;
  3144. break;
  3145. case OP_OPEN_EQUIV_CLASS:
  3146. elem->type = EQUIV_CLASS;
  3147. break;
  3148. case OP_OPEN_CHAR_CLASS:
  3149. elem->type = CHAR_CLASS;
  3150. break;
  3151. default:
  3152. break;
  3153. }
  3154. return REG_NOERROR;
  3155. }
  3156. /* Helper function for parse_bracket_exp.
  3157. Build the equivalence class which is represented by NAME.
  3158. The result are written to MBCSET and SBCSET.
  3159. EQUIV_CLASS_ALLOC is the allocated size of mbcset->equiv_classes,
  3160. is a pointer argument since we may update it. */
  3161. static reg_errcode_t
  3162. #ifdef RE_ENABLE_I18N
  3163. build_equiv_class (bitset_t sbcset, re_charset_t *mbcset,
  3164. Idx *equiv_class_alloc, const unsigned char *name)
  3165. #else /* not RE_ENABLE_I18N */
  3166. build_equiv_class (bitset_t sbcset, const unsigned char *name)
  3167. #endif /* not RE_ENABLE_I18N */
  3168. {
  3169. #ifdef _LIBC
  3170. uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  3171. if (nrules != 0)
  3172. {
  3173. const int32_t *table, *indirect;
  3174. const unsigned char *weights, *extra, *cp;
  3175. unsigned char char_buf[2];
  3176. int32_t idx1, idx2;
  3177. unsigned int ch;
  3178. size_t len;
  3179. /* This #include defines a local function! */
  3180. # include <locale/weight.h>
  3181. /* Calculate the index for equivalence class. */
  3182. cp = name;
  3183. table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  3184. weights = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  3185. _NL_COLLATE_WEIGHTMB);
  3186. extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  3187. _NL_COLLATE_EXTRAMB);
  3188. indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE,
  3189. _NL_COLLATE_INDIRECTMB);
  3190. idx1 = findidx (&cp, -1);
  3191. if (BE (idx1 == 0 || *cp != '\0', 0))
  3192. /* This isn't a valid character. */
  3193. return REG_ECOLLATE;
  3194. /* Build single byte matching table for this equivalence class. */
  3195. len = weights[idx1 & 0xffffff];
  3196. for (ch = 0; ch < SBC_MAX; ++ch)
  3197. {
  3198. char_buf[0] = ch;
  3199. cp = char_buf;
  3200. idx2 = findidx (&cp, 1);
  3201. /*
  3202. idx2 = table[ch];
  3203. */
  3204. if (idx2 == 0)
  3205. /* This isn't a valid character. */
  3206. continue;
  3207. /* Compare only if the length matches and the collation rule
  3208. index is the same. */
  3209. if (len == weights[idx2 & 0xffffff] && (idx1 >> 24) == (idx2 >> 24))
  3210. {
  3211. int cnt = 0;
  3212. while (cnt <= len &&
  3213. weights[(idx1 & 0xffffff) + 1 + cnt]
  3214. == weights[(idx2 & 0xffffff) + 1 + cnt])
  3215. ++cnt;
  3216. if (cnt > len)
  3217. bitset_set (sbcset, ch);
  3218. }
  3219. }
  3220. /* Check whether the array has enough space. */
  3221. if (BE (*equiv_class_alloc == mbcset->nequiv_classes, 0))
  3222. {
  3223. /* Not enough, realloc it. */
  3224. /* +1 in case of mbcset->nequiv_classes is 0. */
  3225. Idx new_equiv_class_alloc = 2 * mbcset->nequiv_classes + 1;
  3226. /* Use realloc since the array is NULL if *alloc == 0. */
  3227. int32_t *new_equiv_classes = re_realloc (mbcset->equiv_classes,
  3228. int32_t,
  3229. new_equiv_class_alloc);
  3230. if (BE (new_equiv_classes == NULL, 0))
  3231. return REG_ESPACE;
  3232. mbcset->equiv_classes = new_equiv_classes;
  3233. *equiv_class_alloc = new_equiv_class_alloc;
  3234. }
  3235. mbcset->equiv_classes[mbcset->nequiv_classes++] = idx1;
  3236. }
  3237. else
  3238. #endif /* _LIBC */
  3239. {
  3240. if (BE (strlen ((const char *) name) != 1, 0))
  3241. return REG_ECOLLATE;
  3242. bitset_set (sbcset, *name);
  3243. }
  3244. return REG_NOERROR;
  3245. }
  3246. /* Helper function for parse_bracket_exp.
  3247. Build the character class which is represented by NAME.
  3248. The result are written to MBCSET and SBCSET.
  3249. CHAR_CLASS_ALLOC is the allocated size of mbcset->char_classes,
  3250. is a pointer argument since we may update it. */
  3251. static reg_errcode_t
  3252. #ifdef RE_ENABLE_I18N
  3253. build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset,
  3254. re_charset_t *mbcset, Idx *char_class_alloc,
  3255. const char *class_name, reg_syntax_t syntax)
  3256. #else /* not RE_ENABLE_I18N */
  3257. build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset,
  3258. const char *class_name, reg_syntax_t syntax)
  3259. #endif /* not RE_ENABLE_I18N */
  3260. {
  3261. int i;
  3262. const char *name = class_name;
  3263. /* In case of REG_ICASE "upper" and "lower" match the both of
  3264. upper and lower cases. */
  3265. if ((syntax & RE_ICASE)
  3266. && (strcmp (name, "upper") == 0 || strcmp (name, "lower") == 0))
  3267. name = "alpha";
  3268. #ifdef RE_ENABLE_I18N
  3269. /* Check the space of the arrays. */
  3270. if (BE (*char_class_alloc == mbcset->nchar_classes, 0))
  3271. {
  3272. /* Not enough, realloc it. */
  3273. /* +1 in case of mbcset->nchar_classes is 0. */
  3274. Idx new_char_class_alloc = 2 * mbcset->nchar_classes + 1;
  3275. /* Use realloc since array is NULL if *alloc == 0. */
  3276. wctype_t *new_char_classes = re_realloc (mbcset->char_classes, wctype_t,
  3277. new_char_class_alloc);
  3278. if (BE (new_char_classes == NULL, 0))
  3279. return REG_ESPACE;
  3280. mbcset->char_classes = new_char_classes;
  3281. *char_class_alloc = new_char_class_alloc;
  3282. }
  3283. mbcset->char_classes[mbcset->nchar_classes++] = __wctype (name);
  3284. #endif /* RE_ENABLE_I18N */
  3285. #define BUILD_CHARCLASS_LOOP(ctype_func) \
  3286. do { \
  3287. if (BE (trans != NULL, 0)) \
  3288. { \
  3289. for (i = 0; i < SBC_MAX; ++i) \
  3290. if (ctype_func (i)) \
  3291. bitset_set (sbcset, trans[i]); \
  3292. } \
  3293. else \
  3294. { \
  3295. for (i = 0; i < SBC_MAX; ++i) \
  3296. if (ctype_func (i)) \
  3297. bitset_set (sbcset, i); \
  3298. } \
  3299. } while (0)
  3300. if (strcmp (name, "alnum") == 0)
  3301. BUILD_CHARCLASS_LOOP (isalnum);
  3302. else if (strcmp (name, "cntrl") == 0)
  3303. BUILD_CHARCLASS_LOOP (iscntrl);
  3304. else if (strcmp (name, "lower") == 0)
  3305. BUILD_CHARCLASS_LOOP (islower);
  3306. else if (strcmp (name, "space") == 0)
  3307. BUILD_CHARCLASS_LOOP (isspace);
  3308. else if (strcmp (name, "alpha") == 0)
  3309. BUILD_CHARCLASS_LOOP (isalpha);
  3310. else if (strcmp (name, "digit") == 0)
  3311. BUILD_CHARCLASS_LOOP (isdigit);
  3312. else if (strcmp (name, "print") == 0)
  3313. BUILD_CHARCLASS_LOOP (isprint);
  3314. else if (strcmp (name, "upper") == 0)
  3315. BUILD_CHARCLASS_LOOP (isupper);
  3316. else if (strcmp (name, "blank") == 0)
  3317. BUILD_CHARCLASS_LOOP (isblank);
  3318. else if (strcmp (name, "graph") == 0)
  3319. BUILD_CHARCLASS_LOOP (isgraph);
  3320. else if (strcmp (name, "punct") == 0)
  3321. BUILD_CHARCLASS_LOOP (ispunct);
  3322. else if (strcmp (name, "xdigit") == 0)
  3323. BUILD_CHARCLASS_LOOP (isxdigit);
  3324. else
  3325. return REG_ECTYPE;
  3326. return REG_NOERROR;
  3327. }
  3328. static bin_tree_t *
  3329. build_charclass_op (re_dfa_t *dfa, RE_TRANSLATE_TYPE trans,
  3330. const char *class_name,
  3331. const char *extra, bool non_match,
  3332. reg_errcode_t *err)
  3333. {
  3334. re_bitset_ptr_t sbcset;
  3335. #ifdef RE_ENABLE_I18N
  3336. re_charset_t *mbcset;
  3337. Idx alloc = 0;
  3338. #endif /* not RE_ENABLE_I18N */
  3339. reg_errcode_t ret;
  3340. re_token_t br_token;
  3341. bin_tree_t *tree;
  3342. sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  3343. #ifdef RE_ENABLE_I18N
  3344. mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1);
  3345. #endif /* RE_ENABLE_I18N */
  3346. #ifdef RE_ENABLE_I18N
  3347. if (BE (sbcset == NULL || mbcset == NULL, 0))
  3348. #else /* not RE_ENABLE_I18N */
  3349. if (BE (sbcset == NULL, 0))
  3350. #endif /* not RE_ENABLE_I18N */
  3351. {
  3352. *err = REG_ESPACE;
  3353. return NULL;
  3354. }
  3355. if (non_match)
  3356. {
  3357. #ifdef RE_ENABLE_I18N
  3358. mbcset->non_match = 1;
  3359. #endif /* not RE_ENABLE_I18N */
  3360. }
  3361. /* We don't care the syntax in this case. */
  3362. ret = build_charclass (trans, sbcset,
  3363. #ifdef RE_ENABLE_I18N
  3364. mbcset, &alloc,
  3365. #endif /* RE_ENABLE_I18N */
  3366. class_name, 0);
  3367. if (BE (ret != REG_NOERROR, 0))
  3368. {
  3369. re_free (sbcset);
  3370. #ifdef RE_ENABLE_I18N
  3371. free_charset (mbcset);
  3372. #endif /* RE_ENABLE_I18N */
  3373. *err = ret;
  3374. return NULL;
  3375. }
  3376. /* \w match '_' also. */
  3377. for (; *extra; extra++)
  3378. bitset_set (sbcset, *extra);
  3379. /* If it is non-matching list. */
  3380. if (non_match)
  3381. bitset_not (sbcset);
  3382. #ifdef RE_ENABLE_I18N
  3383. /* Ensure only single byte characters are set. */
  3384. if (dfa->mb_cur_max > 1)
  3385. bitset_mask (sbcset, dfa->sb_char);
  3386. #endif
  3387. /* Build a tree for simple bracket. */
  3388. br_token.type = SIMPLE_BRACKET;
  3389. br_token.opr.sbcset = sbcset;
  3390. tree = create_token_tree (dfa, NULL, NULL, &br_token);
  3391. if (BE (tree == NULL, 0))
  3392. goto build_word_op_espace;
  3393. #ifdef RE_ENABLE_I18N
  3394. if (dfa->mb_cur_max > 1)
  3395. {
  3396. bin_tree_t *mbc_tree;
  3397. /* Build a tree for complex bracket. */
  3398. br_token.type = COMPLEX_BRACKET;
  3399. br_token.opr.mbcset = mbcset;
  3400. dfa->has_mb_node = 1;
  3401. mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  3402. if (BE (mbc_tree == NULL, 0))
  3403. goto build_word_op_espace;
  3404. /* Then join them by ALT node. */
  3405. tree = create_tree (dfa, tree, mbc_tree, OP_ALT);
  3406. if (BE (mbc_tree != NULL, 1))
  3407. return tree;
  3408. }
  3409. else
  3410. {
  3411. free_charset (mbcset);
  3412. return tree;
  3413. }
  3414. #else /* not RE_ENABLE_I18N */
  3415. return tree;
  3416. #endif /* not RE_ENABLE_I18N */
  3417. build_word_op_espace:
  3418. re_free (sbcset);
  3419. #ifdef RE_ENABLE_I18N
  3420. free_charset (mbcset);
  3421. #endif /* RE_ENABLE_I18N */
  3422. *err = REG_ESPACE;
  3423. return NULL;
  3424. }
  3425. /* This is intended for the expressions like "a{1,3}".
  3426. Fetch a number from 'input', and return the number.
  3427. Return REG_MISSING if the number field is empty like "{,1}".
  3428. Return RE_DUP_MAX + 1 if the number field is too large.
  3429. Return REG_ERROR if an error occurred. */
  3430. static Idx
  3431. fetch_number (re_string_t *input, re_token_t *token, reg_syntax_t syntax)
  3432. {
  3433. Idx num = REG_MISSING;
  3434. unsigned char c;
  3435. while (1)
  3436. {
  3437. fetch_token (token, input, syntax);
  3438. c = token->opr.c;
  3439. if (BE (token->type == END_OF_RE, 0))
  3440. return REG_ERROR;
  3441. if (token->type == OP_CLOSE_DUP_NUM || c == ',')
  3442. break;
  3443. num = ((token->type != CHARACTER || c < '0' || '9' < c
  3444. || num == REG_ERROR)
  3445. ? REG_ERROR
  3446. : num == REG_MISSING
  3447. ? c - '0'
  3448. : MIN (RE_DUP_MAX + 1, num * 10 + c - '0'));
  3449. }
  3450. return num;
  3451. }
  3452. #ifdef RE_ENABLE_I18N
  3453. static void
  3454. free_charset (re_charset_t *cset)
  3455. {
  3456. re_free (cset->mbchars);
  3457. # ifdef _LIBC
  3458. re_free (cset->coll_syms);
  3459. re_free (cset->equiv_classes);
  3460. re_free (cset->range_starts);
  3461. re_free (cset->range_ends);
  3462. # endif
  3463. re_free (cset->char_classes);
  3464. re_free (cset);
  3465. }
  3466. #endif /* RE_ENABLE_I18N */
  3467. /* Functions for binary tree operation. */
  3468. /* Create a tree node. */
  3469. static bin_tree_t *
  3470. create_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right,
  3471. re_token_type_t type)
  3472. {
  3473. re_token_t t;
  3474. t.type = type;
  3475. return create_token_tree (dfa, left, right, &t);
  3476. }
  3477. static bin_tree_t *
  3478. create_token_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right,
  3479. const re_token_t *token)
  3480. {
  3481. bin_tree_t *tree;
  3482. if (BE (dfa->str_tree_storage_idx == BIN_TREE_STORAGE_SIZE, 0))
  3483. {
  3484. bin_tree_storage_t *storage = re_malloc (bin_tree_storage_t, 1);
  3485. if (storage == NULL)
  3486. return NULL;
  3487. storage->next = dfa->str_tree_storage;
  3488. dfa->str_tree_storage = storage;
  3489. dfa->str_tree_storage_idx = 0;
  3490. }
  3491. tree = &dfa->str_tree_storage->data[dfa->str_tree_storage_idx++];
  3492. tree->parent = NULL;
  3493. tree->left = left;
  3494. tree->right = right;
  3495. tree->token = *token;
  3496. tree->token.duplicated = 0;
  3497. tree->token.opt_subexp = 0;
  3498. tree->first = NULL;
  3499. tree->next = NULL;
  3500. tree->node_idx = REG_MISSING;
  3501. if (left != NULL)
  3502. left->parent = tree;
  3503. if (right != NULL)
  3504. right->parent = tree;
  3505. return tree;
  3506. }
  3507. /* Mark the tree SRC as an optional subexpression.
  3508. To be called from preorder or postorder. */
  3509. static reg_errcode_t
  3510. mark_opt_subexp (void *extra, bin_tree_t *node)
  3511. {
  3512. Idx idx = (uintptr_t) extra;
  3513. if (node->token.type == SUBEXP && node->token.opr.idx == idx)
  3514. node->token.opt_subexp = 1;
  3515. return REG_NOERROR;
  3516. }
  3517. /* Free the allocated memory inside NODE. */
  3518. static void
  3519. free_token (re_token_t *node)
  3520. {
  3521. #ifdef RE_ENABLE_I18N
  3522. if (node->type == COMPLEX_BRACKET && node->duplicated == 0)
  3523. free_charset (node->opr.mbcset);
  3524. else
  3525. #endif /* RE_ENABLE_I18N */
  3526. if (node->type == SIMPLE_BRACKET && node->duplicated == 0)
  3527. re_free (node->opr.sbcset);
  3528. }
  3529. /* Worker function for tree walking. Free the allocated memory inside NODE
  3530. and its children. */
  3531. static reg_errcode_t
  3532. free_tree (void *extra, bin_tree_t *node)
  3533. {
  3534. free_token (&node->token);
  3535. return REG_NOERROR;
  3536. }
  3537. /* Duplicate the node SRC, and return new node. This is a preorder
  3538. visit similar to the one implemented by the generic visitor, but
  3539. we need more infrastructure to maintain two parallel trees --- so,
  3540. it's easier to duplicate. */
  3541. static bin_tree_t *
  3542. duplicate_tree (const bin_tree_t *root, re_dfa_t *dfa)
  3543. {
  3544. const bin_tree_t *node;
  3545. bin_tree_t *dup_root;
  3546. bin_tree_t **p_new = &dup_root, *dup_node = root->parent;
  3547. for (node = root; ; )
  3548. {
  3549. /* Create a new tree and link it back to the current parent. */
  3550. *p_new = create_token_tree (dfa, NULL, NULL, &node->token);
  3551. if (*p_new == NULL)
  3552. return NULL;
  3553. (*p_new)->parent = dup_node;
  3554. (*p_new)->token.duplicated = 1;
  3555. dup_node = *p_new;
  3556. /* Go to the left node, or up and to the right. */
  3557. if (node->left)
  3558. {
  3559. node = node->left;
  3560. p_new = &dup_node->left;
  3561. }
  3562. else
  3563. {
  3564. const bin_tree_t *prev = NULL;
  3565. while (node->right == prev || node->right == NULL)
  3566. {
  3567. prev = node;
  3568. node = node->parent;
  3569. dup_node = dup_node->parent;
  3570. if (!node)
  3571. return dup_root;
  3572. }
  3573. node = node->right;
  3574. p_new = &dup_node->right;
  3575. }
  3576. }
  3577. }