_elementtree.c 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458
  1. /*--------------------------------------------------------------------
  2. * Licensed to PSF under a Contributor Agreement.
  3. * See https://www.python.org/psf/license for licensing details.
  4. *
  5. * _elementtree - C accelerator for xml.etree.ElementTree
  6. * Copyright (c) 1999-2009 by Secret Labs AB. All rights reserved.
  7. * Copyright (c) 1999-2009 by Fredrik Lundh.
  8. *
  9. * info@pythonware.com
  10. * http://www.pythonware.com
  11. *--------------------------------------------------------------------
  12. */
  13. #define PY_SSIZE_T_CLEAN
  14. #include "Python.h"
  15. #include "structmember.h" // PyMemberDef
  16. #include "expat.h"
  17. #include "pyexpat.h"
  18. /* -------------------------------------------------------------------- */
  19. /* configuration */
  20. /* An element can hold this many children without extra memory
  21. allocations. */
  22. #define STATIC_CHILDREN 4
  23. /* For best performance, chose a value so that 80-90% of all nodes
  24. have no more than the given number of children. Set this to zero
  25. to minimize the size of the element structure itself (this only
  26. helps if you have lots of leaf nodes with attributes). */
  27. /* Also note that pymalloc always allocates blocks in multiples of
  28. eight bytes. For the current C version of ElementTree, this means
  29. that the number of children should be an even number, at least on
  30. 32-bit platforms. */
  31. /* -------------------------------------------------------------------- */
  32. /* compiler tweaks */
  33. #if defined(_MSC_VER)
  34. #define LOCAL(type) static __inline type __fastcall
  35. #else
  36. #define LOCAL(type) static type
  37. #endif
  38. /* macros used to store 'join' flags in string object pointers. note
  39. that all use of text and tail as object pointers must be wrapped in
  40. JOIN_OBJ. see comments in the ElementObject definition for more
  41. info. */
  42. #define JOIN_GET(p) ((uintptr_t) (p) & 1)
  43. #define JOIN_SET(p, flag) ((void*) ((uintptr_t) (JOIN_OBJ(p)) | (flag)))
  44. #define JOIN_OBJ(p) ((PyObject*) ((uintptr_t) (p) & ~(uintptr_t)1))
  45. /* Py_SETREF for a PyObject* that uses a join flag. */
  46. Py_LOCAL_INLINE(void)
  47. _set_joined_ptr(PyObject **p, PyObject *new_joined_ptr)
  48. {
  49. PyObject *tmp = JOIN_OBJ(*p);
  50. *p = new_joined_ptr;
  51. Py_DECREF(tmp);
  52. }
  53. /* Py_CLEAR for a PyObject* that uses a join flag. Pass the pointer by
  54. * reference since this function sets it to NULL.
  55. */
  56. static void _clear_joined_ptr(PyObject **p)
  57. {
  58. if (*p) {
  59. _set_joined_ptr(p, NULL);
  60. }
  61. }
  62. /* Per-module state; PEP 3121 */
  63. typedef struct {
  64. PyObject *parseerror_obj;
  65. PyObject *deepcopy_obj;
  66. PyObject *elementpath_obj;
  67. PyObject *comment_factory;
  68. PyObject *pi_factory;
  69. /* Interned strings */
  70. PyObject *str_text;
  71. PyObject *str_tail;
  72. PyObject *str_append;
  73. PyObject *str_find;
  74. PyObject *str_findtext;
  75. PyObject *str_findall;
  76. PyObject *str_iterfind;
  77. PyObject *str_doctype;
  78. /* Types defined by this extension */
  79. PyTypeObject *Element_Type;
  80. PyTypeObject *ElementIter_Type;
  81. PyTypeObject *TreeBuilder_Type;
  82. PyTypeObject *XMLParser_Type;
  83. PyObject *expat_capsule;
  84. struct PyExpat_CAPI *expat_capi;
  85. } elementtreestate;
  86. static struct PyModuleDef elementtreemodule;
  87. /* Given a module object (assumed to be _elementtree), get its per-module
  88. * state.
  89. */
  90. static inline elementtreestate*
  91. get_elementtree_state(PyObject *module)
  92. {
  93. void *state = PyModule_GetState(module);
  94. assert(state != NULL);
  95. return (elementtreestate *)state;
  96. }
  97. static inline elementtreestate *
  98. get_elementtree_state_by_cls(PyTypeObject *cls)
  99. {
  100. void *state = PyType_GetModuleState(cls);
  101. assert(state != NULL);
  102. return (elementtreestate *)state;
  103. }
  104. static inline elementtreestate *
  105. get_elementtree_state_by_type(PyTypeObject *tp)
  106. {
  107. PyObject *mod = PyType_GetModuleByDef(tp, &elementtreemodule);
  108. assert(mod != NULL);
  109. return get_elementtree_state(mod);
  110. }
  111. static int
  112. elementtree_clear(PyObject *m)
  113. {
  114. elementtreestate *st = get_elementtree_state(m);
  115. Py_CLEAR(st->parseerror_obj);
  116. Py_CLEAR(st->deepcopy_obj);
  117. Py_CLEAR(st->elementpath_obj);
  118. Py_CLEAR(st->comment_factory);
  119. Py_CLEAR(st->pi_factory);
  120. // Interned strings
  121. Py_CLEAR(st->str_append);
  122. Py_CLEAR(st->str_find);
  123. Py_CLEAR(st->str_findall);
  124. Py_CLEAR(st->str_findtext);
  125. Py_CLEAR(st->str_iterfind);
  126. Py_CLEAR(st->str_tail);
  127. Py_CLEAR(st->str_text);
  128. Py_CLEAR(st->str_doctype);
  129. // Heap types
  130. Py_CLEAR(st->Element_Type);
  131. Py_CLEAR(st->ElementIter_Type);
  132. Py_CLEAR(st->TreeBuilder_Type);
  133. Py_CLEAR(st->XMLParser_Type);
  134. Py_CLEAR(st->expat_capsule);
  135. st->expat_capi = NULL;
  136. return 0;
  137. }
  138. static int
  139. elementtree_traverse(PyObject *m, visitproc visit, void *arg)
  140. {
  141. elementtreestate *st = get_elementtree_state(m);
  142. Py_VISIT(st->parseerror_obj);
  143. Py_VISIT(st->deepcopy_obj);
  144. Py_VISIT(st->elementpath_obj);
  145. Py_VISIT(st->comment_factory);
  146. Py_VISIT(st->pi_factory);
  147. // Heap types
  148. Py_VISIT(st->Element_Type);
  149. Py_VISIT(st->ElementIter_Type);
  150. Py_VISIT(st->TreeBuilder_Type);
  151. Py_VISIT(st->XMLParser_Type);
  152. Py_VISIT(st->expat_capsule);
  153. return 0;
  154. }
  155. static void
  156. elementtree_free(void *m)
  157. {
  158. elementtree_clear((PyObject *)m);
  159. }
  160. /* helpers */
  161. LOCAL(PyObject*)
  162. list_join(PyObject* list)
  163. {
  164. /* join list elements */
  165. PyObject* joiner;
  166. PyObject* result;
  167. joiner = PyUnicode_FromStringAndSize("", 0);
  168. if (!joiner)
  169. return NULL;
  170. result = PyUnicode_Join(joiner, list);
  171. Py_DECREF(joiner);
  172. return result;
  173. }
  174. /* Is the given object an empty dictionary?
  175. */
  176. static int
  177. is_empty_dict(PyObject *obj)
  178. {
  179. return PyDict_CheckExact(obj) && PyDict_GET_SIZE(obj) == 0;
  180. }
  181. /* -------------------------------------------------------------------- */
  182. /* the Element type */
  183. typedef struct {
  184. /* attributes (a dictionary object), or NULL if no attributes */
  185. PyObject* attrib;
  186. /* child elements */
  187. Py_ssize_t length; /* actual number of items */
  188. Py_ssize_t allocated; /* allocated items */
  189. /* this either points to _children or to a malloced buffer */
  190. PyObject* *children;
  191. PyObject* _children[STATIC_CHILDREN];
  192. } ElementObjectExtra;
  193. typedef struct {
  194. PyObject_HEAD
  195. /* element tag (a string). */
  196. PyObject* tag;
  197. /* text before first child. note that this is a tagged pointer;
  198. use JOIN_OBJ to get the object pointer. the join flag is used
  199. to distinguish lists created by the tree builder from lists
  200. assigned to the attribute by application code; the former
  201. should be joined before being returned to the user, the latter
  202. should be left intact. */
  203. PyObject* text;
  204. /* text after this element, in parent. note that this is a tagged
  205. pointer; use JOIN_OBJ to get the object pointer. */
  206. PyObject* tail;
  207. ElementObjectExtra* extra;
  208. PyObject *weakreflist; /* For tp_weaklistoffset */
  209. } ElementObject;
  210. #define Element_CheckExact(st, op) Py_IS_TYPE(op, (st)->Element_Type)
  211. #define Element_Check(st, op) PyObject_TypeCheck(op, (st)->Element_Type)
  212. /* -------------------------------------------------------------------- */
  213. /* Element constructors and destructor */
  214. LOCAL(int)
  215. create_extra(ElementObject* self, PyObject* attrib)
  216. {
  217. self->extra = PyObject_Malloc(sizeof(ElementObjectExtra));
  218. if (!self->extra) {
  219. PyErr_NoMemory();
  220. return -1;
  221. }
  222. self->extra->attrib = Py_XNewRef(attrib);
  223. self->extra->length = 0;
  224. self->extra->allocated = STATIC_CHILDREN;
  225. self->extra->children = self->extra->_children;
  226. return 0;
  227. }
  228. LOCAL(void)
  229. dealloc_extra(ElementObjectExtra *extra)
  230. {
  231. Py_ssize_t i;
  232. if (!extra)
  233. return;
  234. Py_XDECREF(extra->attrib);
  235. for (i = 0; i < extra->length; i++)
  236. Py_DECREF(extra->children[i]);
  237. if (extra->children != extra->_children)
  238. PyObject_Free(extra->children);
  239. PyObject_Free(extra);
  240. }
  241. LOCAL(void)
  242. clear_extra(ElementObject* self)
  243. {
  244. ElementObjectExtra *myextra;
  245. if (!self->extra)
  246. return;
  247. /* Avoid DECREFs calling into this code again (cycles, etc.)
  248. */
  249. myextra = self->extra;
  250. self->extra = NULL;
  251. dealloc_extra(myextra);
  252. }
  253. /* Convenience internal function to create new Element objects with the given
  254. * tag and attributes.
  255. */
  256. LOCAL(PyObject*)
  257. create_new_element(elementtreestate *st, PyObject *tag, PyObject *attrib)
  258. {
  259. ElementObject* self;
  260. self = PyObject_GC_New(ElementObject, st->Element_Type);
  261. if (self == NULL)
  262. return NULL;
  263. self->extra = NULL;
  264. self->tag = Py_NewRef(tag);
  265. self->text = Py_NewRef(Py_None);
  266. self->tail = Py_NewRef(Py_None);
  267. self->weakreflist = NULL;
  268. PyObject_GC_Track(self);
  269. if (attrib != NULL && !is_empty_dict(attrib)) {
  270. if (create_extra(self, attrib) < 0) {
  271. Py_DECREF(self);
  272. return NULL;
  273. }
  274. }
  275. return (PyObject*) self;
  276. }
  277. static PyObject *
  278. element_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  279. {
  280. ElementObject *e = (ElementObject *)type->tp_alloc(type, 0);
  281. if (e != NULL) {
  282. e->tag = Py_NewRef(Py_None);
  283. e->text = Py_NewRef(Py_None);
  284. e->tail = Py_NewRef(Py_None);
  285. e->extra = NULL;
  286. e->weakreflist = NULL;
  287. }
  288. return (PyObject *)e;
  289. }
  290. /* Helper function for extracting the attrib dictionary from a keywords dict.
  291. * This is required by some constructors/functions in this module that can
  292. * either accept attrib as a keyword argument or all attributes splashed
  293. * directly into *kwds.
  294. *
  295. * Return a dictionary with the content of kwds merged into the content of
  296. * attrib. If there is no attrib keyword, return a copy of kwds.
  297. */
  298. static PyObject*
  299. get_attrib_from_keywords(PyObject *kwds)
  300. {
  301. PyObject *attrib_str = PyUnicode_FromString("attrib");
  302. if (attrib_str == NULL) {
  303. return NULL;
  304. }
  305. PyObject *attrib = PyDict_GetItemWithError(kwds, attrib_str);
  306. if (attrib) {
  307. /* If attrib was found in kwds, copy its value and remove it from
  308. * kwds
  309. */
  310. if (!PyDict_Check(attrib)) {
  311. Py_DECREF(attrib_str);
  312. PyErr_Format(PyExc_TypeError, "attrib must be dict, not %.100s",
  313. Py_TYPE(attrib)->tp_name);
  314. return NULL;
  315. }
  316. attrib = PyDict_Copy(attrib);
  317. if (attrib && PyDict_DelItem(kwds, attrib_str) < 0) {
  318. Py_SETREF(attrib, NULL);
  319. }
  320. }
  321. else if (!PyErr_Occurred()) {
  322. attrib = PyDict_New();
  323. }
  324. Py_DECREF(attrib_str);
  325. if (attrib != NULL && PyDict_Update(attrib, kwds) < 0) {
  326. Py_DECREF(attrib);
  327. return NULL;
  328. }
  329. return attrib;
  330. }
  331. /*[clinic input]
  332. module _elementtree
  333. class _elementtree.Element "ElementObject *" "clinic_state()->Element_Type"
  334. class _elementtree.TreeBuilder "TreeBuilderObject *" "clinic_state()->TreeBuilder_Type"
  335. class _elementtree.XMLParser "XMLParserObject *" "clinic_state()->XMLParser_Type"
  336. [clinic start generated code]*/
  337. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=6c83ea832d2b0ef1]*/
  338. static int
  339. element_init(PyObject *self, PyObject *args, PyObject *kwds)
  340. {
  341. PyObject *tag;
  342. PyObject *attrib = NULL;
  343. ElementObject *self_elem;
  344. if (!PyArg_ParseTuple(args, "O|O!:Element", &tag, &PyDict_Type, &attrib))
  345. return -1;
  346. if (attrib) {
  347. /* attrib passed as positional arg */
  348. attrib = PyDict_Copy(attrib);
  349. if (!attrib)
  350. return -1;
  351. if (kwds) {
  352. if (PyDict_Update(attrib, kwds) < 0) {
  353. Py_DECREF(attrib);
  354. return -1;
  355. }
  356. }
  357. } else if (kwds) {
  358. /* have keywords args */
  359. attrib = get_attrib_from_keywords(kwds);
  360. if (!attrib)
  361. return -1;
  362. }
  363. self_elem = (ElementObject *)self;
  364. if (attrib != NULL && !is_empty_dict(attrib)) {
  365. if (create_extra(self_elem, attrib) < 0) {
  366. Py_DECREF(attrib);
  367. return -1;
  368. }
  369. }
  370. /* We own a reference to attrib here and it's no longer needed. */
  371. Py_XDECREF(attrib);
  372. /* Replace the objects already pointed to by tag, text and tail. */
  373. Py_XSETREF(self_elem->tag, Py_NewRef(tag));
  374. _set_joined_ptr(&self_elem->text, Py_NewRef(Py_None));
  375. _set_joined_ptr(&self_elem->tail, Py_NewRef(Py_None));
  376. return 0;
  377. }
  378. LOCAL(int)
  379. element_resize(ElementObject* self, Py_ssize_t extra)
  380. {
  381. Py_ssize_t size;
  382. PyObject* *children;
  383. assert(extra >= 0);
  384. /* make sure self->children can hold the given number of extra
  385. elements. set an exception and return -1 if allocation failed */
  386. if (!self->extra) {
  387. if (create_extra(self, NULL) < 0)
  388. return -1;
  389. }
  390. size = self->extra->length + extra; /* never overflows */
  391. if (size > self->extra->allocated) {
  392. /* use Python 2.4's list growth strategy */
  393. size = (size >> 3) + (size < 9 ? 3 : 6) + size;
  394. /* Coverity CID #182 size_error: Allocating 1 bytes to pointer "children"
  395. * which needs at least 4 bytes.
  396. * Although it's a false alarm always assume at least one child to
  397. * be safe.
  398. */
  399. size = size ? size : 1;
  400. if ((size_t)size > PY_SSIZE_T_MAX/sizeof(PyObject*))
  401. goto nomemory;
  402. if (self->extra->children != self->extra->_children) {
  403. /* Coverity CID #182 size_error: Allocating 1 bytes to pointer
  404. * "children", which needs at least 4 bytes. Although it's a
  405. * false alarm always assume at least one child to be safe.
  406. */
  407. children = PyObject_Realloc(self->extra->children,
  408. size * sizeof(PyObject*));
  409. if (!children)
  410. goto nomemory;
  411. } else {
  412. children = PyObject_Malloc(size * sizeof(PyObject*));
  413. if (!children)
  414. goto nomemory;
  415. /* copy existing children from static area to malloc buffer */
  416. memcpy(children, self->extra->children,
  417. self->extra->length * sizeof(PyObject*));
  418. }
  419. self->extra->children = children;
  420. self->extra->allocated = size;
  421. }
  422. return 0;
  423. nomemory:
  424. PyErr_NoMemory();
  425. return -1;
  426. }
  427. LOCAL(void)
  428. raise_type_error(PyObject *element)
  429. {
  430. PyErr_Format(PyExc_TypeError,
  431. "expected an Element, not \"%.200s\"",
  432. Py_TYPE(element)->tp_name);
  433. }
  434. LOCAL(int)
  435. element_add_subelement(elementtreestate *st, ElementObject *self,
  436. PyObject *element)
  437. {
  438. /* add a child element to a parent */
  439. if (!Element_Check(st, element)) {
  440. raise_type_error(element);
  441. return -1;
  442. }
  443. if (element_resize(self, 1) < 0)
  444. return -1;
  445. self->extra->children[self->extra->length] = Py_NewRef(element);
  446. self->extra->length++;
  447. return 0;
  448. }
  449. LOCAL(PyObject*)
  450. element_get_attrib(ElementObject* self)
  451. {
  452. /* return borrowed reference to attrib dictionary */
  453. /* note: this function assumes that the extra section exists */
  454. PyObject* res = self->extra->attrib;
  455. if (!res) {
  456. /* create missing dictionary */
  457. res = self->extra->attrib = PyDict_New();
  458. }
  459. return res;
  460. }
  461. LOCAL(PyObject*)
  462. element_get_text(ElementObject* self)
  463. {
  464. /* return borrowed reference to text attribute */
  465. PyObject *res = self->text;
  466. if (JOIN_GET(res)) {
  467. res = JOIN_OBJ(res);
  468. if (PyList_CheckExact(res)) {
  469. PyObject *tmp = list_join(res);
  470. if (!tmp)
  471. return NULL;
  472. self->text = tmp;
  473. Py_SETREF(res, tmp);
  474. }
  475. }
  476. return res;
  477. }
  478. LOCAL(PyObject*)
  479. element_get_tail(ElementObject* self)
  480. {
  481. /* return borrowed reference to text attribute */
  482. PyObject *res = self->tail;
  483. if (JOIN_GET(res)) {
  484. res = JOIN_OBJ(res);
  485. if (PyList_CheckExact(res)) {
  486. PyObject *tmp = list_join(res);
  487. if (!tmp)
  488. return NULL;
  489. self->tail = tmp;
  490. Py_SETREF(res, tmp);
  491. }
  492. }
  493. return res;
  494. }
  495. static PyObject*
  496. subelement(PyObject *self, PyObject *args, PyObject *kwds)
  497. {
  498. PyObject* elem;
  499. elementtreestate *st = get_elementtree_state(self);
  500. ElementObject* parent;
  501. PyObject* tag;
  502. PyObject* attrib = NULL;
  503. if (!PyArg_ParseTuple(args, "O!O|O!:SubElement",
  504. st->Element_Type, &parent, &tag,
  505. &PyDict_Type, &attrib)) {
  506. return NULL;
  507. }
  508. if (attrib) {
  509. /* attrib passed as positional arg */
  510. attrib = PyDict_Copy(attrib);
  511. if (!attrib)
  512. return NULL;
  513. if (kwds != NULL && PyDict_Update(attrib, kwds) < 0) {
  514. Py_DECREF(attrib);
  515. return NULL;
  516. }
  517. } else if (kwds) {
  518. /* have keyword args */
  519. attrib = get_attrib_from_keywords(kwds);
  520. if (!attrib)
  521. return NULL;
  522. } else {
  523. /* no attrib arg, no kwds, so no attribute */
  524. }
  525. elem = create_new_element(st, tag, attrib);
  526. Py_XDECREF(attrib);
  527. if (elem == NULL)
  528. return NULL;
  529. if (element_add_subelement(st, parent, elem) < 0) {
  530. Py_DECREF(elem);
  531. return NULL;
  532. }
  533. return elem;
  534. }
  535. static int
  536. element_gc_traverse(ElementObject *self, visitproc visit, void *arg)
  537. {
  538. Py_VISIT(Py_TYPE(self));
  539. Py_VISIT(self->tag);
  540. Py_VISIT(JOIN_OBJ(self->text));
  541. Py_VISIT(JOIN_OBJ(self->tail));
  542. if (self->extra) {
  543. Py_ssize_t i;
  544. Py_VISIT(self->extra->attrib);
  545. for (i = 0; i < self->extra->length; ++i)
  546. Py_VISIT(self->extra->children[i]);
  547. }
  548. return 0;
  549. }
  550. static int
  551. element_gc_clear(ElementObject *self)
  552. {
  553. Py_CLEAR(self->tag);
  554. _clear_joined_ptr(&self->text);
  555. _clear_joined_ptr(&self->tail);
  556. /* After dropping all references from extra, it's no longer valid anyway,
  557. * so fully deallocate it.
  558. */
  559. clear_extra(self);
  560. return 0;
  561. }
  562. static void
  563. element_dealloc(ElementObject* self)
  564. {
  565. PyTypeObject *tp = Py_TYPE(self);
  566. /* bpo-31095: UnTrack is needed before calling any callbacks */
  567. PyObject_GC_UnTrack(self);
  568. Py_TRASHCAN_BEGIN(self, element_dealloc)
  569. if (self->weakreflist != NULL)
  570. PyObject_ClearWeakRefs((PyObject *) self);
  571. /* element_gc_clear clears all references and deallocates extra
  572. */
  573. element_gc_clear(self);
  574. tp->tp_free((PyObject *)self);
  575. Py_DECREF(tp);
  576. Py_TRASHCAN_END
  577. }
  578. /* -------------------------------------------------------------------- */
  579. /*[clinic input]
  580. _elementtree.Element.append
  581. cls: defining_class
  582. subelement: object(subclass_of='clinic_state()->Element_Type')
  583. /
  584. [clinic start generated code]*/
  585. static PyObject *
  586. _elementtree_Element_append_impl(ElementObject *self, PyTypeObject *cls,
  587. PyObject *subelement)
  588. /*[clinic end generated code: output=d00923711ea317fc input=8baf92679f9717b8]*/
  589. {
  590. elementtreestate *st = get_elementtree_state_by_cls(cls);
  591. if (element_add_subelement(st, self, subelement) < 0)
  592. return NULL;
  593. Py_RETURN_NONE;
  594. }
  595. /*[clinic input]
  596. _elementtree.Element.clear
  597. [clinic start generated code]*/
  598. static PyObject *
  599. _elementtree_Element_clear_impl(ElementObject *self)
  600. /*[clinic end generated code: output=8bcd7a51f94cfff6 input=3c719ff94bf45dd6]*/
  601. {
  602. clear_extra(self);
  603. _set_joined_ptr(&self->text, Py_NewRef(Py_None));
  604. _set_joined_ptr(&self->tail, Py_NewRef(Py_None));
  605. Py_RETURN_NONE;
  606. }
  607. /*[clinic input]
  608. _elementtree.Element.__copy__
  609. cls: defining_class
  610. /
  611. [clinic start generated code]*/
  612. static PyObject *
  613. _elementtree_Element___copy___impl(ElementObject *self, PyTypeObject *cls)
  614. /*[clinic end generated code: output=da22894421ff2b36 input=91edb92d9f441213]*/
  615. {
  616. Py_ssize_t i;
  617. ElementObject* element;
  618. elementtreestate *st = get_elementtree_state_by_cls(cls);
  619. element = (ElementObject*) create_new_element(
  620. st, self->tag, self->extra ? self->extra->attrib : NULL);
  621. if (!element)
  622. return NULL;
  623. Py_INCREF(JOIN_OBJ(self->text));
  624. _set_joined_ptr(&element->text, self->text);
  625. Py_INCREF(JOIN_OBJ(self->tail));
  626. _set_joined_ptr(&element->tail, self->tail);
  627. assert(!element->extra || !element->extra->length);
  628. if (self->extra) {
  629. if (element_resize(element, self->extra->length) < 0) {
  630. Py_DECREF(element);
  631. return NULL;
  632. }
  633. for (i = 0; i < self->extra->length; i++) {
  634. element->extra->children[i] = Py_NewRef(self->extra->children[i]);
  635. }
  636. assert(!element->extra->length);
  637. element->extra->length = self->extra->length;
  638. }
  639. return (PyObject*) element;
  640. }
  641. /* Helper for a deep copy. */
  642. LOCAL(PyObject *) deepcopy(elementtreestate *, PyObject *, PyObject *);
  643. /*[clinic input]
  644. _elementtree.Element.__deepcopy__
  645. memo: object(subclass_of="&PyDict_Type")
  646. /
  647. [clinic start generated code]*/
  648. static PyObject *
  649. _elementtree_Element___deepcopy___impl(ElementObject *self, PyObject *memo)
  650. /*[clinic end generated code: output=eefc3df50465b642 input=a2d40348c0aade10]*/
  651. {
  652. Py_ssize_t i;
  653. ElementObject* element;
  654. PyObject* tag;
  655. PyObject* attrib;
  656. PyObject* text;
  657. PyObject* tail;
  658. PyObject* id;
  659. PyTypeObject *tp = Py_TYPE(self);
  660. elementtreestate *st = get_elementtree_state_by_type(tp);
  661. tag = deepcopy(st, self->tag, memo);
  662. if (!tag)
  663. return NULL;
  664. if (self->extra && self->extra->attrib) {
  665. attrib = deepcopy(st, self->extra->attrib, memo);
  666. if (!attrib) {
  667. Py_DECREF(tag);
  668. return NULL;
  669. }
  670. } else {
  671. attrib = NULL;
  672. }
  673. element = (ElementObject*) create_new_element(st, tag, attrib);
  674. Py_DECREF(tag);
  675. Py_XDECREF(attrib);
  676. if (!element)
  677. return NULL;
  678. text = deepcopy(st, JOIN_OBJ(self->text), memo);
  679. if (!text)
  680. goto error;
  681. _set_joined_ptr(&element->text, JOIN_SET(text, JOIN_GET(self->text)));
  682. tail = deepcopy(st, JOIN_OBJ(self->tail), memo);
  683. if (!tail)
  684. goto error;
  685. _set_joined_ptr(&element->tail, JOIN_SET(tail, JOIN_GET(self->tail)));
  686. assert(!element->extra || !element->extra->length);
  687. if (self->extra) {
  688. if (element_resize(element, self->extra->length) < 0)
  689. goto error;
  690. for (i = 0; i < self->extra->length; i++) {
  691. PyObject* child = deepcopy(st, self->extra->children[i], memo);
  692. if (!child || !Element_Check(st, child)) {
  693. if (child) {
  694. raise_type_error(child);
  695. Py_DECREF(child);
  696. }
  697. element->extra->length = i;
  698. goto error;
  699. }
  700. element->extra->children[i] = child;
  701. }
  702. assert(!element->extra->length);
  703. element->extra->length = self->extra->length;
  704. }
  705. /* add object to memo dictionary (so deepcopy won't visit it again) */
  706. id = PyLong_FromSsize_t((uintptr_t) self);
  707. if (!id)
  708. goto error;
  709. i = PyDict_SetItem(memo, id, (PyObject*) element);
  710. Py_DECREF(id);
  711. if (i < 0)
  712. goto error;
  713. return (PyObject*) element;
  714. error:
  715. Py_DECREF(element);
  716. return NULL;
  717. }
  718. LOCAL(PyObject *)
  719. deepcopy(elementtreestate *st, PyObject *object, PyObject *memo)
  720. {
  721. /* do a deep copy of the given object */
  722. PyObject *stack[2];
  723. /* Fast paths */
  724. if (object == Py_None || PyUnicode_CheckExact(object)) {
  725. return Py_NewRef(object);
  726. }
  727. if (Py_REFCNT(object) == 1) {
  728. if (PyDict_CheckExact(object)) {
  729. PyObject *key, *value;
  730. Py_ssize_t pos = 0;
  731. int simple = 1;
  732. while (PyDict_Next(object, &pos, &key, &value)) {
  733. if (!PyUnicode_CheckExact(key) || !PyUnicode_CheckExact(value)) {
  734. simple = 0;
  735. break;
  736. }
  737. }
  738. if (simple)
  739. return PyDict_Copy(object);
  740. /* Fall through to general case */
  741. }
  742. else if (Element_CheckExact(st, object)) {
  743. return _elementtree_Element___deepcopy___impl(
  744. (ElementObject *)object, memo);
  745. }
  746. }
  747. /* General case */
  748. if (!st->deepcopy_obj) {
  749. PyErr_SetString(PyExc_RuntimeError,
  750. "deepcopy helper not found");
  751. return NULL;
  752. }
  753. stack[0] = object;
  754. stack[1] = memo;
  755. return _PyObject_FastCall(st->deepcopy_obj, stack, 2);
  756. }
  757. /*[clinic input]
  758. _elementtree.Element.__sizeof__ -> size_t
  759. [clinic start generated code]*/
  760. static size_t
  761. _elementtree_Element___sizeof___impl(ElementObject *self)
  762. /*[clinic end generated code: output=baae4e7ae9fe04ec input=54e298c501f3e0d0]*/
  763. {
  764. size_t result = _PyObject_SIZE(Py_TYPE(self));
  765. if (self->extra) {
  766. result += sizeof(ElementObjectExtra);
  767. if (self->extra->children != self->extra->_children) {
  768. result += (size_t)self->extra->allocated * sizeof(PyObject*);
  769. }
  770. }
  771. return result;
  772. }
  773. /* dict keys for getstate/setstate. */
  774. #define PICKLED_TAG "tag"
  775. #define PICKLED_CHILDREN "_children"
  776. #define PICKLED_ATTRIB "attrib"
  777. #define PICKLED_TAIL "tail"
  778. #define PICKLED_TEXT "text"
  779. /* __getstate__ returns a fabricated instance dict as in the pure-Python
  780. * Element implementation, for interoperability/interchangeability. This
  781. * makes the pure-Python implementation details an API, but (a) there aren't
  782. * any unnecessary structures there; and (b) it buys compatibility with 3.2
  783. * pickles. See issue #16076.
  784. */
  785. /*[clinic input]
  786. _elementtree.Element.__getstate__
  787. [clinic start generated code]*/
  788. static PyObject *
  789. _elementtree_Element___getstate___impl(ElementObject *self)
  790. /*[clinic end generated code: output=37279aeeb6bb5b04 input=f0d16d7ec2f7adc1]*/
  791. {
  792. Py_ssize_t i;
  793. PyObject *children, *attrib;
  794. /* Build a list of children. */
  795. children = PyList_New(self->extra ? self->extra->length : 0);
  796. if (!children)
  797. return NULL;
  798. for (i = 0; i < PyList_GET_SIZE(children); i++) {
  799. PyObject *child = Py_NewRef(self->extra->children[i]);
  800. PyList_SET_ITEM(children, i, child);
  801. }
  802. if (self->extra && self->extra->attrib) {
  803. attrib = Py_NewRef(self->extra->attrib);
  804. }
  805. else {
  806. attrib = PyDict_New();
  807. if (!attrib) {
  808. Py_DECREF(children);
  809. return NULL;
  810. }
  811. }
  812. return Py_BuildValue("{sOsNsNsOsO}",
  813. PICKLED_TAG, self->tag,
  814. PICKLED_CHILDREN, children,
  815. PICKLED_ATTRIB, attrib,
  816. PICKLED_TEXT, JOIN_OBJ(self->text),
  817. PICKLED_TAIL, JOIN_OBJ(self->tail));
  818. }
  819. static PyObject *
  820. element_setstate_from_attributes(elementtreestate *st,
  821. ElementObject *self,
  822. PyObject *tag,
  823. PyObject *attrib,
  824. PyObject *text,
  825. PyObject *tail,
  826. PyObject *children)
  827. {
  828. Py_ssize_t i, nchildren;
  829. ElementObjectExtra *oldextra = NULL;
  830. if (!tag) {
  831. PyErr_SetString(PyExc_TypeError, "tag may not be NULL");
  832. return NULL;
  833. }
  834. Py_XSETREF(self->tag, Py_NewRef(tag));
  835. text = text ? JOIN_SET(text, PyList_CheckExact(text)) : Py_None;
  836. Py_INCREF(JOIN_OBJ(text));
  837. _set_joined_ptr(&self->text, text);
  838. tail = tail ? JOIN_SET(tail, PyList_CheckExact(tail)) : Py_None;
  839. Py_INCREF(JOIN_OBJ(tail));
  840. _set_joined_ptr(&self->tail, tail);
  841. /* Handle ATTRIB and CHILDREN. */
  842. if (!children && !attrib) {
  843. Py_RETURN_NONE;
  844. }
  845. /* Compute 'nchildren'. */
  846. if (children) {
  847. if (!PyList_Check(children)) {
  848. PyErr_SetString(PyExc_TypeError, "'_children' is not a list");
  849. return NULL;
  850. }
  851. nchildren = PyList_GET_SIZE(children);
  852. /* (Re-)allocate 'extra'.
  853. Avoid DECREFs calling into this code again (cycles, etc.)
  854. */
  855. oldextra = self->extra;
  856. self->extra = NULL;
  857. if (element_resize(self, nchildren)) {
  858. assert(!self->extra || !self->extra->length);
  859. clear_extra(self);
  860. self->extra = oldextra;
  861. return NULL;
  862. }
  863. assert(self->extra);
  864. assert(self->extra->allocated >= nchildren);
  865. if (oldextra) {
  866. assert(self->extra->attrib == NULL);
  867. self->extra->attrib = oldextra->attrib;
  868. oldextra->attrib = NULL;
  869. }
  870. /* Copy children */
  871. for (i = 0; i < nchildren; i++) {
  872. PyObject *child = PyList_GET_ITEM(children, i);
  873. if (!Element_Check(st, child)) {
  874. raise_type_error(child);
  875. self->extra->length = i;
  876. dealloc_extra(oldextra);
  877. return NULL;
  878. }
  879. self->extra->children[i] = Py_NewRef(child);
  880. }
  881. assert(!self->extra->length);
  882. self->extra->length = nchildren;
  883. }
  884. else {
  885. if (element_resize(self, 0)) {
  886. return NULL;
  887. }
  888. }
  889. /* Stash attrib. */
  890. Py_XSETREF(self->extra->attrib, Py_XNewRef(attrib));
  891. dealloc_extra(oldextra);
  892. Py_RETURN_NONE;
  893. }
  894. /* __setstate__ for Element instance from the Python implementation.
  895. * 'state' should be the instance dict.
  896. */
  897. static PyObject *
  898. element_setstate_from_Python(elementtreestate *st, ElementObject *self,
  899. PyObject *state)
  900. {
  901. static char *kwlist[] = {PICKLED_TAG, PICKLED_ATTRIB, PICKLED_TEXT,
  902. PICKLED_TAIL, PICKLED_CHILDREN, 0};
  903. PyObject *args;
  904. PyObject *tag, *attrib, *text, *tail, *children;
  905. PyObject *retval;
  906. tag = attrib = text = tail = children = NULL;
  907. args = PyTuple_New(0);
  908. if (!args)
  909. return NULL;
  910. if (PyArg_ParseTupleAndKeywords(args, state, "|$OOOOO", kwlist, &tag,
  911. &attrib, &text, &tail, &children))
  912. retval = element_setstate_from_attributes(st, self, tag, attrib, text,
  913. tail, children);
  914. else
  915. retval = NULL;
  916. Py_DECREF(args);
  917. return retval;
  918. }
  919. /*[clinic input]
  920. _elementtree.Element.__setstate__
  921. cls: defining_class
  922. state: object
  923. /
  924. [clinic start generated code]*/
  925. static PyObject *
  926. _elementtree_Element___setstate___impl(ElementObject *self,
  927. PyTypeObject *cls, PyObject *state)
  928. /*[clinic end generated code: output=598bfb5730f71509 input=13830488d35d51f7]*/
  929. {
  930. if (!PyDict_CheckExact(state)) {
  931. PyErr_Format(PyExc_TypeError,
  932. "Don't know how to unpickle \"%.200R\" as an Element",
  933. state);
  934. return NULL;
  935. }
  936. else {
  937. elementtreestate *st = get_elementtree_state_by_cls(cls);
  938. return element_setstate_from_Python(st, self, state);
  939. }
  940. }
  941. LOCAL(int)
  942. checkpath(PyObject* tag)
  943. {
  944. Py_ssize_t i;
  945. int check = 1;
  946. /* check if a tag contains an xpath character */
  947. #define PATHCHAR(ch) \
  948. (ch == '/' || ch == '*' || ch == '[' || ch == '@' || ch == '.')
  949. if (PyUnicode_Check(tag)) {
  950. const Py_ssize_t len = PyUnicode_GET_LENGTH(tag);
  951. const void *data = PyUnicode_DATA(tag);
  952. int kind = PyUnicode_KIND(tag);
  953. if (len >= 3 && PyUnicode_READ(kind, data, 0) == '{' && (
  954. PyUnicode_READ(kind, data, 1) == '}' || (
  955. PyUnicode_READ(kind, data, 1) == '*' &&
  956. PyUnicode_READ(kind, data, 2) == '}'))) {
  957. /* wildcard: '{}tag' or '{*}tag' */
  958. return 1;
  959. }
  960. for (i = 0; i < len; i++) {
  961. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  962. if (ch == '{')
  963. check = 0;
  964. else if (ch == '}')
  965. check = 1;
  966. else if (check && PATHCHAR(ch))
  967. return 1;
  968. }
  969. return 0;
  970. }
  971. if (PyBytes_Check(tag)) {
  972. const char *p = PyBytes_AS_STRING(tag);
  973. const Py_ssize_t len = PyBytes_GET_SIZE(tag);
  974. if (len >= 3 && p[0] == '{' && (
  975. p[1] == '}' || (p[1] == '*' && p[2] == '}'))) {
  976. /* wildcard: '{}tag' or '{*}tag' */
  977. return 1;
  978. }
  979. for (i = 0; i < len; i++) {
  980. if (p[i] == '{')
  981. check = 0;
  982. else if (p[i] == '}')
  983. check = 1;
  984. else if (check && PATHCHAR(p[i]))
  985. return 1;
  986. }
  987. return 0;
  988. }
  989. return 1; /* unknown type; might be path expression */
  990. }
  991. /*[clinic input]
  992. _elementtree.Element.extend
  993. cls: defining_class
  994. elements: object
  995. /
  996. [clinic start generated code]*/
  997. static PyObject *
  998. _elementtree_Element_extend_impl(ElementObject *self, PyTypeObject *cls,
  999. PyObject *elements)
  1000. /*[clinic end generated code: output=3e86d37fac542216 input=6479b1b5379d09ae]*/
  1001. {
  1002. PyObject* seq;
  1003. Py_ssize_t i;
  1004. seq = PySequence_Fast(elements, "");
  1005. if (!seq) {
  1006. PyErr_Format(
  1007. PyExc_TypeError,
  1008. "expected sequence, not \"%.200s\"", Py_TYPE(elements)->tp_name
  1009. );
  1010. return NULL;
  1011. }
  1012. elementtreestate *st = get_elementtree_state_by_cls(cls);
  1013. for (i = 0; i < PySequence_Fast_GET_SIZE(seq); i++) {
  1014. PyObject* element = Py_NewRef(PySequence_Fast_GET_ITEM(seq, i));
  1015. if (element_add_subelement(st, self, element) < 0) {
  1016. Py_DECREF(seq);
  1017. Py_DECREF(element);
  1018. return NULL;
  1019. }
  1020. Py_DECREF(element);
  1021. }
  1022. Py_DECREF(seq);
  1023. Py_RETURN_NONE;
  1024. }
  1025. /*[clinic input]
  1026. _elementtree.Element.find
  1027. cls: defining_class
  1028. /
  1029. path: object
  1030. namespaces: object = None
  1031. [clinic start generated code]*/
  1032. static PyObject *
  1033. _elementtree_Element_find_impl(ElementObject *self, PyTypeObject *cls,
  1034. PyObject *path, PyObject *namespaces)
  1035. /*[clinic end generated code: output=18f77d393c9fef1b input=94df8a83f956acc6]*/
  1036. {
  1037. Py_ssize_t i;
  1038. elementtreestate *st = get_elementtree_state_by_cls(cls);
  1039. if (checkpath(path) || namespaces != Py_None) {
  1040. return PyObject_CallMethodObjArgs(
  1041. st->elementpath_obj, st->str_find, self, path, namespaces, NULL
  1042. );
  1043. }
  1044. if (!self->extra)
  1045. Py_RETURN_NONE;
  1046. for (i = 0; i < self->extra->length; i++) {
  1047. PyObject* item = self->extra->children[i];
  1048. int rc;
  1049. assert(Element_Check(st, item));
  1050. Py_INCREF(item);
  1051. rc = PyObject_RichCompareBool(((ElementObject*)item)->tag, path, Py_EQ);
  1052. if (rc > 0)
  1053. return item;
  1054. Py_DECREF(item);
  1055. if (rc < 0)
  1056. return NULL;
  1057. }
  1058. Py_RETURN_NONE;
  1059. }
  1060. /*[clinic input]
  1061. _elementtree.Element.findtext
  1062. cls: defining_class
  1063. /
  1064. path: object
  1065. default: object = None
  1066. namespaces: object = None
  1067. [clinic start generated code]*/
  1068. static PyObject *
  1069. _elementtree_Element_findtext_impl(ElementObject *self, PyTypeObject *cls,
  1070. PyObject *path, PyObject *default_value,
  1071. PyObject *namespaces)
  1072. /*[clinic end generated code: output=6af7a2d96aac32cb input=32f252099f62a3d2]*/
  1073. {
  1074. Py_ssize_t i;
  1075. elementtreestate *st = get_elementtree_state_by_cls(cls);
  1076. if (checkpath(path) || namespaces != Py_None)
  1077. return PyObject_CallMethodObjArgs(
  1078. st->elementpath_obj, st->str_findtext,
  1079. self, path, default_value, namespaces, NULL
  1080. );
  1081. if (!self->extra) {
  1082. return Py_NewRef(default_value);
  1083. }
  1084. for (i = 0; i < self->extra->length; i++) {
  1085. PyObject *item = self->extra->children[i];
  1086. int rc;
  1087. assert(Element_Check(st, item));
  1088. Py_INCREF(item);
  1089. rc = PyObject_RichCompareBool(((ElementObject*)item)->tag, path, Py_EQ);
  1090. if (rc > 0) {
  1091. PyObject* text = element_get_text((ElementObject*)item);
  1092. if (text == Py_None) {
  1093. Py_DECREF(item);
  1094. return PyUnicode_New(0, 0);
  1095. }
  1096. Py_XINCREF(text);
  1097. Py_DECREF(item);
  1098. return text;
  1099. }
  1100. Py_DECREF(item);
  1101. if (rc < 0)
  1102. return NULL;
  1103. }
  1104. return Py_NewRef(default_value);
  1105. }
  1106. /*[clinic input]
  1107. _elementtree.Element.findall
  1108. cls: defining_class
  1109. /
  1110. path: object
  1111. namespaces: object = None
  1112. [clinic start generated code]*/
  1113. static PyObject *
  1114. _elementtree_Element_findall_impl(ElementObject *self, PyTypeObject *cls,
  1115. PyObject *path, PyObject *namespaces)
  1116. /*[clinic end generated code: output=65e39a1208f3b59e input=7aa0db45673fc9a5]*/
  1117. {
  1118. Py_ssize_t i;
  1119. PyObject* out;
  1120. elementtreestate *st = get_elementtree_state_by_cls(cls);
  1121. if (checkpath(path) || namespaces != Py_None) {
  1122. return PyObject_CallMethodObjArgs(
  1123. st->elementpath_obj, st->str_findall, self, path, namespaces, NULL
  1124. );
  1125. }
  1126. out = PyList_New(0);
  1127. if (!out)
  1128. return NULL;
  1129. if (!self->extra)
  1130. return out;
  1131. for (i = 0; i < self->extra->length; i++) {
  1132. PyObject* item = self->extra->children[i];
  1133. int rc;
  1134. assert(Element_Check(st, item));
  1135. Py_INCREF(item);
  1136. rc = PyObject_RichCompareBool(((ElementObject*)item)->tag, path, Py_EQ);
  1137. if (rc != 0 && (rc < 0 || PyList_Append(out, item) < 0)) {
  1138. Py_DECREF(item);
  1139. Py_DECREF(out);
  1140. return NULL;
  1141. }
  1142. Py_DECREF(item);
  1143. }
  1144. return out;
  1145. }
  1146. /*[clinic input]
  1147. _elementtree.Element.iterfind
  1148. cls: defining_class
  1149. /
  1150. path: object
  1151. namespaces: object = None
  1152. [clinic start generated code]*/
  1153. static PyObject *
  1154. _elementtree_Element_iterfind_impl(ElementObject *self, PyTypeObject *cls,
  1155. PyObject *path, PyObject *namespaces)
  1156. /*[clinic end generated code: output=be5c3f697a14e676 input=88766875a5c9a88b]*/
  1157. {
  1158. PyObject* tag = path;
  1159. elementtreestate *st = get_elementtree_state_by_cls(cls);
  1160. return PyObject_CallMethodObjArgs(
  1161. st->elementpath_obj, st->str_iterfind, self, tag, namespaces, NULL);
  1162. }
  1163. /*[clinic input]
  1164. _elementtree.Element.get
  1165. key: object
  1166. default: object = None
  1167. [clinic start generated code]*/
  1168. static PyObject *
  1169. _elementtree_Element_get_impl(ElementObject *self, PyObject *key,
  1170. PyObject *default_value)
  1171. /*[clinic end generated code: output=523c614142595d75 input=ee153bbf8cdb246e]*/
  1172. {
  1173. if (self->extra && self->extra->attrib) {
  1174. PyObject *attrib = Py_NewRef(self->extra->attrib);
  1175. PyObject *value = Py_XNewRef(PyDict_GetItemWithError(attrib, key));
  1176. Py_DECREF(attrib);
  1177. if (value != NULL || PyErr_Occurred()) {
  1178. return value;
  1179. }
  1180. }
  1181. return Py_NewRef(default_value);
  1182. }
  1183. static PyObject *
  1184. create_elementiter(elementtreestate *st, ElementObject *self, PyObject *tag,
  1185. int gettext);
  1186. /*[clinic input]
  1187. _elementtree.Element.iter
  1188. cls: defining_class
  1189. /
  1190. tag: object = None
  1191. [clinic start generated code]*/
  1192. static PyObject *
  1193. _elementtree_Element_iter_impl(ElementObject *self, PyTypeObject *cls,
  1194. PyObject *tag)
  1195. /*[clinic end generated code: output=bff29dc5d4566c68 input=f6944c48d3f84c58]*/
  1196. {
  1197. if (PyUnicode_Check(tag)) {
  1198. if (PyUnicode_READY(tag) < 0)
  1199. return NULL;
  1200. if (PyUnicode_GET_LENGTH(tag) == 1 && PyUnicode_READ_CHAR(tag, 0) == '*')
  1201. tag = Py_None;
  1202. }
  1203. else if (PyBytes_Check(tag)) {
  1204. if (PyBytes_GET_SIZE(tag) == 1 && *PyBytes_AS_STRING(tag) == '*')
  1205. tag = Py_None;
  1206. }
  1207. elementtreestate *st = get_elementtree_state_by_cls(cls);
  1208. return create_elementiter(st, self, tag, 0);
  1209. }
  1210. /*[clinic input]
  1211. _elementtree.Element.itertext
  1212. cls: defining_class
  1213. /
  1214. [clinic start generated code]*/
  1215. static PyObject *
  1216. _elementtree_Element_itertext_impl(ElementObject *self, PyTypeObject *cls)
  1217. /*[clinic end generated code: output=fdeb2a3bca0ae063 input=a1ef1f0fc872a586]*/
  1218. {
  1219. elementtreestate *st = get_elementtree_state_by_cls(cls);
  1220. return create_elementiter(st, self, Py_None, 1);
  1221. }
  1222. static PyObject*
  1223. element_getitem(PyObject* self_, Py_ssize_t index)
  1224. {
  1225. ElementObject* self = (ElementObject*) self_;
  1226. if (!self->extra || index < 0 || index >= self->extra->length) {
  1227. PyErr_SetString(
  1228. PyExc_IndexError,
  1229. "child index out of range"
  1230. );
  1231. return NULL;
  1232. }
  1233. return Py_NewRef(self->extra->children[index]);
  1234. }
  1235. static int
  1236. element_bool(PyObject* self_)
  1237. {
  1238. ElementObject* self = (ElementObject*) self_;
  1239. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  1240. "Testing an element's truth value will raise an exception "
  1241. "in future versions. Use specific 'len(elem)' or "
  1242. "'elem is not None' test instead.",
  1243. 1) < 0) {
  1244. return -1;
  1245. };
  1246. if (self->extra ? self->extra->length : 0) {
  1247. return 1;
  1248. }
  1249. return 0;
  1250. }
  1251. /*[clinic input]
  1252. _elementtree.Element.insert
  1253. index: Py_ssize_t
  1254. subelement: object(subclass_of='clinic_state()->Element_Type')
  1255. /
  1256. [clinic start generated code]*/
  1257. static PyObject *
  1258. _elementtree_Element_insert_impl(ElementObject *self, Py_ssize_t index,
  1259. PyObject *subelement)
  1260. /*[clinic end generated code: output=990adfef4d424c0b input=9530f4905aa401ca]*/
  1261. {
  1262. Py_ssize_t i;
  1263. if (!self->extra) {
  1264. if (create_extra(self, NULL) < 0)
  1265. return NULL;
  1266. }
  1267. if (index < 0) {
  1268. index += self->extra->length;
  1269. if (index < 0)
  1270. index = 0;
  1271. }
  1272. if (index > self->extra->length)
  1273. index = self->extra->length;
  1274. if (element_resize(self, 1) < 0)
  1275. return NULL;
  1276. for (i = self->extra->length; i > index; i--)
  1277. self->extra->children[i] = self->extra->children[i-1];
  1278. self->extra->children[index] = Py_NewRef(subelement);
  1279. self->extra->length++;
  1280. Py_RETURN_NONE;
  1281. }
  1282. /*[clinic input]
  1283. _elementtree.Element.items
  1284. [clinic start generated code]*/
  1285. static PyObject *
  1286. _elementtree_Element_items_impl(ElementObject *self)
  1287. /*[clinic end generated code: output=6db2c778ce3f5a4d input=adbe09aaea474447]*/
  1288. {
  1289. if (!self->extra || !self->extra->attrib)
  1290. return PyList_New(0);
  1291. return PyDict_Items(self->extra->attrib);
  1292. }
  1293. /*[clinic input]
  1294. _elementtree.Element.keys
  1295. [clinic start generated code]*/
  1296. static PyObject *
  1297. _elementtree_Element_keys_impl(ElementObject *self)
  1298. /*[clinic end generated code: output=bc5bfabbf20eeb3c input=f02caf5b496b5b0b]*/
  1299. {
  1300. if (!self->extra || !self->extra->attrib)
  1301. return PyList_New(0);
  1302. return PyDict_Keys(self->extra->attrib);
  1303. }
  1304. static Py_ssize_t
  1305. element_length(ElementObject* self)
  1306. {
  1307. if (!self->extra)
  1308. return 0;
  1309. return self->extra->length;
  1310. }
  1311. /*[clinic input]
  1312. _elementtree.Element.makeelement
  1313. cls: defining_class
  1314. tag: object
  1315. attrib: object(subclass_of='&PyDict_Type')
  1316. /
  1317. [clinic start generated code]*/
  1318. static PyObject *
  1319. _elementtree_Element_makeelement_impl(ElementObject *self, PyTypeObject *cls,
  1320. PyObject *tag, PyObject *attrib)
  1321. /*[clinic end generated code: output=d50bb17a47077d47 input=589829dab92f26e8]*/
  1322. {
  1323. PyObject* elem;
  1324. attrib = PyDict_Copy(attrib);
  1325. if (!attrib)
  1326. return NULL;
  1327. elementtreestate *st = get_elementtree_state_by_cls(cls);
  1328. elem = create_new_element(st, tag, attrib);
  1329. Py_DECREF(attrib);
  1330. return elem;
  1331. }
  1332. /*[clinic input]
  1333. _elementtree.Element.remove
  1334. subelement: object(subclass_of='clinic_state()->Element_Type')
  1335. /
  1336. [clinic start generated code]*/
  1337. static PyObject *
  1338. _elementtree_Element_remove_impl(ElementObject *self, PyObject *subelement)
  1339. /*[clinic end generated code: output=38fe6c07d6d87d1f input=6133e1d05597d5ee]*/
  1340. {
  1341. Py_ssize_t i;
  1342. int rc;
  1343. PyObject *found;
  1344. if (!self->extra) {
  1345. /* element has no children, so raise exception */
  1346. PyErr_SetString(
  1347. PyExc_ValueError,
  1348. "list.remove(x): x not in list"
  1349. );
  1350. return NULL;
  1351. }
  1352. for (i = 0; i < self->extra->length; i++) {
  1353. if (self->extra->children[i] == subelement)
  1354. break;
  1355. rc = PyObject_RichCompareBool(self->extra->children[i], subelement, Py_EQ);
  1356. if (rc > 0)
  1357. break;
  1358. if (rc < 0)
  1359. return NULL;
  1360. }
  1361. if (i >= self->extra->length) {
  1362. /* subelement is not in children, so raise exception */
  1363. PyErr_SetString(
  1364. PyExc_ValueError,
  1365. "list.remove(x): x not in list"
  1366. );
  1367. return NULL;
  1368. }
  1369. found = self->extra->children[i];
  1370. self->extra->length--;
  1371. for (; i < self->extra->length; i++)
  1372. self->extra->children[i] = self->extra->children[i+1];
  1373. Py_DECREF(found);
  1374. Py_RETURN_NONE;
  1375. }
  1376. static PyObject*
  1377. element_repr(ElementObject* self)
  1378. {
  1379. int status;
  1380. if (self->tag == NULL)
  1381. return PyUnicode_FromFormat("<Element at %p>", self);
  1382. status = Py_ReprEnter((PyObject *)self);
  1383. if (status == 0) {
  1384. PyObject *res;
  1385. res = PyUnicode_FromFormat("<Element %R at %p>", self->tag, self);
  1386. Py_ReprLeave((PyObject *)self);
  1387. return res;
  1388. }
  1389. if (status > 0)
  1390. PyErr_Format(PyExc_RuntimeError,
  1391. "reentrant call inside %s.__repr__",
  1392. Py_TYPE(self)->tp_name);
  1393. return NULL;
  1394. }
  1395. /*[clinic input]
  1396. _elementtree.Element.set
  1397. key: object
  1398. value: object
  1399. /
  1400. [clinic start generated code]*/
  1401. static PyObject *
  1402. _elementtree_Element_set_impl(ElementObject *self, PyObject *key,
  1403. PyObject *value)
  1404. /*[clinic end generated code: output=fb938806be3c5656 input=1efe90f7d82b3fe9]*/
  1405. {
  1406. PyObject* attrib;
  1407. if (!self->extra) {
  1408. if (create_extra(self, NULL) < 0)
  1409. return NULL;
  1410. }
  1411. attrib = element_get_attrib(self);
  1412. if (!attrib)
  1413. return NULL;
  1414. if (PyDict_SetItem(attrib, key, value) < 0)
  1415. return NULL;
  1416. Py_RETURN_NONE;
  1417. }
  1418. static int
  1419. element_setitem(PyObject* self_, Py_ssize_t index, PyObject* item)
  1420. {
  1421. ElementObject* self = (ElementObject*) self_;
  1422. Py_ssize_t i;
  1423. PyObject* old;
  1424. if (!self->extra || index < 0 || index >= self->extra->length) {
  1425. PyErr_SetString(
  1426. PyExc_IndexError,
  1427. "child assignment index out of range");
  1428. return -1;
  1429. }
  1430. old = self->extra->children[index];
  1431. if (item) {
  1432. PyTypeObject *tp = Py_TYPE(self);
  1433. elementtreestate *st = get_elementtree_state_by_type(tp);
  1434. if (!Element_Check(st, item)) {
  1435. raise_type_error(item);
  1436. return -1;
  1437. }
  1438. self->extra->children[index] = Py_NewRef(item);
  1439. } else {
  1440. self->extra->length--;
  1441. for (i = index; i < self->extra->length; i++)
  1442. self->extra->children[i] = self->extra->children[i+1];
  1443. }
  1444. Py_DECREF(old);
  1445. return 0;
  1446. }
  1447. static PyObject*
  1448. element_subscr(PyObject* self_, PyObject* item)
  1449. {
  1450. ElementObject* self = (ElementObject*) self_;
  1451. if (PyIndex_Check(item)) {
  1452. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  1453. if (i == -1 && PyErr_Occurred()) {
  1454. return NULL;
  1455. }
  1456. if (i < 0 && self->extra)
  1457. i += self->extra->length;
  1458. return element_getitem(self_, i);
  1459. }
  1460. else if (PySlice_Check(item)) {
  1461. Py_ssize_t start, stop, step, slicelen, i;
  1462. size_t cur;
  1463. PyObject* list;
  1464. if (!self->extra)
  1465. return PyList_New(0);
  1466. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  1467. return NULL;
  1468. }
  1469. slicelen = PySlice_AdjustIndices(self->extra->length, &start, &stop,
  1470. step);
  1471. if (slicelen <= 0)
  1472. return PyList_New(0);
  1473. else {
  1474. list = PyList_New(slicelen);
  1475. if (!list)
  1476. return NULL;
  1477. for (cur = start, i = 0; i < slicelen;
  1478. cur += step, i++) {
  1479. PyObject* item = Py_NewRef(self->extra->children[cur]);
  1480. PyList_SET_ITEM(list, i, item);
  1481. }
  1482. return list;
  1483. }
  1484. }
  1485. else {
  1486. PyErr_SetString(PyExc_TypeError,
  1487. "element indices must be integers");
  1488. return NULL;
  1489. }
  1490. }
  1491. static int
  1492. element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value)
  1493. {
  1494. ElementObject* self = (ElementObject*) self_;
  1495. if (PyIndex_Check(item)) {
  1496. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  1497. if (i == -1 && PyErr_Occurred()) {
  1498. return -1;
  1499. }
  1500. if (i < 0 && self->extra)
  1501. i += self->extra->length;
  1502. return element_setitem(self_, i, value);
  1503. }
  1504. else if (PySlice_Check(item)) {
  1505. Py_ssize_t start, stop, step, slicelen, newlen, i;
  1506. size_t cur;
  1507. PyObject* recycle = NULL;
  1508. PyObject* seq;
  1509. if (!self->extra) {
  1510. if (create_extra(self, NULL) < 0)
  1511. return -1;
  1512. }
  1513. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  1514. return -1;
  1515. }
  1516. slicelen = PySlice_AdjustIndices(self->extra->length, &start, &stop,
  1517. step);
  1518. if (value == NULL) {
  1519. /* Delete slice */
  1520. size_t cur;
  1521. Py_ssize_t i;
  1522. if (slicelen <= 0)
  1523. return 0;
  1524. /* Since we're deleting, the direction of the range doesn't matter,
  1525. * so for simplicity make it always ascending.
  1526. */
  1527. if (step < 0) {
  1528. stop = start + 1;
  1529. start = stop + step * (slicelen - 1) - 1;
  1530. step = -step;
  1531. }
  1532. assert((size_t)slicelen <= SIZE_MAX / sizeof(PyObject *));
  1533. /* recycle is a list that will contain all the children
  1534. * scheduled for removal.
  1535. */
  1536. if (!(recycle = PyList_New(slicelen))) {
  1537. return -1;
  1538. }
  1539. /* This loop walks over all the children that have to be deleted,
  1540. * with cur pointing at them. num_moved is the amount of children
  1541. * until the next deleted child that have to be "shifted down" to
  1542. * occupy the deleted's places.
  1543. * Note that in the ith iteration, shifting is done i+i places down
  1544. * because i children were already removed.
  1545. */
  1546. for (cur = start, i = 0; cur < (size_t)stop; cur += step, ++i) {
  1547. /* Compute how many children have to be moved, clipping at the
  1548. * list end.
  1549. */
  1550. Py_ssize_t num_moved = step - 1;
  1551. if (cur + step >= (size_t)self->extra->length) {
  1552. num_moved = self->extra->length - cur - 1;
  1553. }
  1554. PyList_SET_ITEM(recycle, i, self->extra->children[cur]);
  1555. memmove(
  1556. self->extra->children + cur - i,
  1557. self->extra->children + cur + 1,
  1558. num_moved * sizeof(PyObject *));
  1559. }
  1560. /* Leftover "tail" after the last removed child */
  1561. cur = start + (size_t)slicelen * step;
  1562. if (cur < (size_t)self->extra->length) {
  1563. memmove(
  1564. self->extra->children + cur - slicelen,
  1565. self->extra->children + cur,
  1566. (self->extra->length - cur) * sizeof(PyObject *));
  1567. }
  1568. self->extra->length -= slicelen;
  1569. /* Discard the recycle list with all the deleted sub-elements */
  1570. Py_DECREF(recycle);
  1571. return 0;
  1572. }
  1573. /* A new slice is actually being assigned */
  1574. seq = PySequence_Fast(value, "");
  1575. if (!seq) {
  1576. PyErr_Format(
  1577. PyExc_TypeError,
  1578. "expected sequence, not \"%.200s\"", Py_TYPE(value)->tp_name
  1579. );
  1580. return -1;
  1581. }
  1582. newlen = PySequence_Fast_GET_SIZE(seq);
  1583. if (step != 1 && newlen != slicelen)
  1584. {
  1585. Py_DECREF(seq);
  1586. PyErr_Format(PyExc_ValueError,
  1587. "attempt to assign sequence of size %zd "
  1588. "to extended slice of size %zd",
  1589. newlen, slicelen
  1590. );
  1591. return -1;
  1592. }
  1593. /* Resize before creating the recycle bin, to prevent refleaks. */
  1594. if (newlen > slicelen) {
  1595. if (element_resize(self, newlen - slicelen) < 0) {
  1596. Py_DECREF(seq);
  1597. return -1;
  1598. }
  1599. }
  1600. PyTypeObject *tp = Py_TYPE(self);
  1601. elementtreestate *st = get_elementtree_state_by_type(tp);
  1602. for (i = 0; i < newlen; i++) {
  1603. PyObject *element = PySequence_Fast_GET_ITEM(seq, i);
  1604. if (!Element_Check(st, element)) {
  1605. raise_type_error(element);
  1606. Py_DECREF(seq);
  1607. return -1;
  1608. }
  1609. }
  1610. if (slicelen > 0) {
  1611. /* to avoid recursive calls to this method (via decref), move
  1612. old items to the recycle bin here, and get rid of them when
  1613. we're done modifying the element */
  1614. recycle = PyList_New(slicelen);
  1615. if (!recycle) {
  1616. Py_DECREF(seq);
  1617. return -1;
  1618. }
  1619. for (cur = start, i = 0; i < slicelen;
  1620. cur += step, i++)
  1621. PyList_SET_ITEM(recycle, i, self->extra->children[cur]);
  1622. }
  1623. if (newlen < slicelen) {
  1624. /* delete slice */
  1625. for (i = stop; i < self->extra->length; i++)
  1626. self->extra->children[i + newlen - slicelen] = self->extra->children[i];
  1627. } else if (newlen > slicelen) {
  1628. /* insert slice */
  1629. for (i = self->extra->length-1; i >= stop; i--)
  1630. self->extra->children[i + newlen - slicelen] = self->extra->children[i];
  1631. }
  1632. /* replace the slice */
  1633. for (cur = start, i = 0; i < newlen;
  1634. cur += step, i++) {
  1635. PyObject* element = PySequence_Fast_GET_ITEM(seq, i);
  1636. self->extra->children[cur] = Py_NewRef(element);
  1637. }
  1638. self->extra->length += newlen - slicelen;
  1639. Py_DECREF(seq);
  1640. /* discard the recycle bin, and everything in it */
  1641. Py_XDECREF(recycle);
  1642. return 0;
  1643. }
  1644. else {
  1645. PyErr_SetString(PyExc_TypeError,
  1646. "element indices must be integers");
  1647. return -1;
  1648. }
  1649. }
  1650. static PyObject*
  1651. element_tag_getter(ElementObject *self, void *closure)
  1652. {
  1653. PyObject *res = self->tag;
  1654. return Py_NewRef(res);
  1655. }
  1656. static PyObject*
  1657. element_text_getter(ElementObject *self, void *closure)
  1658. {
  1659. PyObject *res = element_get_text(self);
  1660. return Py_XNewRef(res);
  1661. }
  1662. static PyObject*
  1663. element_tail_getter(ElementObject *self, void *closure)
  1664. {
  1665. PyObject *res = element_get_tail(self);
  1666. return Py_XNewRef(res);
  1667. }
  1668. static PyObject*
  1669. element_attrib_getter(ElementObject *self, void *closure)
  1670. {
  1671. PyObject *res;
  1672. if (!self->extra) {
  1673. if (create_extra(self, NULL) < 0)
  1674. return NULL;
  1675. }
  1676. res = element_get_attrib(self);
  1677. return Py_XNewRef(res);
  1678. }
  1679. /* macro for setter validation */
  1680. #define _VALIDATE_ATTR_VALUE(V) \
  1681. if ((V) == NULL) { \
  1682. PyErr_SetString( \
  1683. PyExc_AttributeError, \
  1684. "can't delete element attribute"); \
  1685. return -1; \
  1686. }
  1687. static int
  1688. element_tag_setter(ElementObject *self, PyObject *value, void *closure)
  1689. {
  1690. _VALIDATE_ATTR_VALUE(value);
  1691. Py_SETREF(self->tag, Py_NewRef(value));
  1692. return 0;
  1693. }
  1694. static int
  1695. element_text_setter(ElementObject *self, PyObject *value, void *closure)
  1696. {
  1697. _VALIDATE_ATTR_VALUE(value);
  1698. _set_joined_ptr(&self->text, Py_NewRef(value));
  1699. return 0;
  1700. }
  1701. static int
  1702. element_tail_setter(ElementObject *self, PyObject *value, void *closure)
  1703. {
  1704. _VALIDATE_ATTR_VALUE(value);
  1705. _set_joined_ptr(&self->tail, Py_NewRef(value));
  1706. return 0;
  1707. }
  1708. static int
  1709. element_attrib_setter(ElementObject *self, PyObject *value, void *closure)
  1710. {
  1711. _VALIDATE_ATTR_VALUE(value);
  1712. if (!PyDict_Check(value)) {
  1713. PyErr_Format(PyExc_TypeError,
  1714. "attrib must be dict, not %.200s",
  1715. Py_TYPE(value)->tp_name);
  1716. return -1;
  1717. }
  1718. if (!self->extra) {
  1719. if (create_extra(self, NULL) < 0)
  1720. return -1;
  1721. }
  1722. Py_XSETREF(self->extra->attrib, Py_NewRef(value));
  1723. return 0;
  1724. }
  1725. /******************************* Element iterator ****************************/
  1726. /* ElementIterObject represents the iteration state over an XML element in
  1727. * pre-order traversal. To keep track of which sub-element should be returned
  1728. * next, a stack of parents is maintained. This is a standard stack-based
  1729. * iterative pre-order traversal of a tree.
  1730. * The stack is managed using a continuous array.
  1731. * Each stack item contains the saved parent to which we should return after
  1732. * the current one is exhausted, and the next child to examine in that parent.
  1733. */
  1734. typedef struct ParentLocator_t {
  1735. ElementObject *parent;
  1736. Py_ssize_t child_index;
  1737. } ParentLocator;
  1738. typedef struct {
  1739. PyObject_HEAD
  1740. ParentLocator *parent_stack;
  1741. Py_ssize_t parent_stack_used;
  1742. Py_ssize_t parent_stack_size;
  1743. ElementObject *root_element;
  1744. PyObject *sought_tag;
  1745. int gettext;
  1746. } ElementIterObject;
  1747. static void
  1748. elementiter_dealloc(ElementIterObject *it)
  1749. {
  1750. PyTypeObject *tp = Py_TYPE(it);
  1751. Py_ssize_t i = it->parent_stack_used;
  1752. it->parent_stack_used = 0;
  1753. /* bpo-31095: UnTrack is needed before calling any callbacks */
  1754. PyObject_GC_UnTrack(it);
  1755. while (i--)
  1756. Py_XDECREF(it->parent_stack[i].parent);
  1757. PyMem_Free(it->parent_stack);
  1758. Py_XDECREF(it->sought_tag);
  1759. Py_XDECREF(it->root_element);
  1760. tp->tp_free(it);
  1761. Py_DECREF(tp);
  1762. }
  1763. static int
  1764. elementiter_traverse(ElementIterObject *it, visitproc visit, void *arg)
  1765. {
  1766. Py_ssize_t i = it->parent_stack_used;
  1767. while (i--)
  1768. Py_VISIT(it->parent_stack[i].parent);
  1769. Py_VISIT(it->root_element);
  1770. Py_VISIT(it->sought_tag);
  1771. Py_VISIT(Py_TYPE(it));
  1772. return 0;
  1773. }
  1774. /* Helper function for elementiter_next. Add a new parent to the parent stack.
  1775. */
  1776. static int
  1777. parent_stack_push_new(ElementIterObject *it, ElementObject *parent)
  1778. {
  1779. ParentLocator *item;
  1780. if (it->parent_stack_used >= it->parent_stack_size) {
  1781. Py_ssize_t new_size = it->parent_stack_size * 2; /* never overflow */
  1782. ParentLocator *parent_stack = it->parent_stack;
  1783. PyMem_Resize(parent_stack, ParentLocator, new_size);
  1784. if (parent_stack == NULL)
  1785. return -1;
  1786. it->parent_stack = parent_stack;
  1787. it->parent_stack_size = new_size;
  1788. }
  1789. item = it->parent_stack + it->parent_stack_used++;
  1790. item->parent = (ElementObject*)Py_NewRef(parent);
  1791. item->child_index = 0;
  1792. return 0;
  1793. }
  1794. static PyObject *
  1795. elementiter_next(ElementIterObject *it)
  1796. {
  1797. /* Sub-element iterator.
  1798. *
  1799. * A short note on gettext: this function serves both the iter() and
  1800. * itertext() methods to avoid code duplication. However, there are a few
  1801. * small differences in the way these iterations work. Namely:
  1802. * - itertext() only yields text from nodes that have it, and continues
  1803. * iterating when a node doesn't have text (so it doesn't return any
  1804. * node like iter())
  1805. * - itertext() also has to handle tail, after finishing with all the
  1806. * children of a node.
  1807. */
  1808. int rc;
  1809. ElementObject *elem;
  1810. PyObject *text;
  1811. while (1) {
  1812. /* Handle the case reached in the beginning and end of iteration, where
  1813. * the parent stack is empty. If root_element is NULL and we're here, the
  1814. * iterator is exhausted.
  1815. */
  1816. if (!it->parent_stack_used) {
  1817. if (!it->root_element) {
  1818. PyErr_SetNone(PyExc_StopIteration);
  1819. return NULL;
  1820. }
  1821. elem = it->root_element; /* steals a reference */
  1822. it->root_element = NULL;
  1823. }
  1824. else {
  1825. /* See if there are children left to traverse in the current parent. If
  1826. * yes, visit the next child. If not, pop the stack and try again.
  1827. */
  1828. ParentLocator *item = &it->parent_stack[it->parent_stack_used - 1];
  1829. Py_ssize_t child_index = item->child_index;
  1830. ElementObjectExtra *extra;
  1831. elem = item->parent;
  1832. extra = elem->extra;
  1833. if (!extra || child_index >= extra->length) {
  1834. it->parent_stack_used--;
  1835. /* Note that extra condition on it->parent_stack_used here;
  1836. * this is because itertext() is supposed to only return *inner*
  1837. * text, not text following the element it began iteration with.
  1838. */
  1839. if (it->gettext && it->parent_stack_used) {
  1840. text = element_get_tail(elem);
  1841. goto gettext;
  1842. }
  1843. Py_DECREF(elem);
  1844. continue;
  1845. }
  1846. #ifndef NDEBUG
  1847. PyTypeObject *tp = Py_TYPE(it);
  1848. elementtreestate *st = get_elementtree_state_by_type(tp);
  1849. assert(Element_Check(st, extra->children[child_index]));
  1850. #endif
  1851. elem = (ElementObject *)Py_NewRef(extra->children[child_index]);
  1852. item->child_index++;
  1853. }
  1854. if (parent_stack_push_new(it, elem) < 0) {
  1855. Py_DECREF(elem);
  1856. PyErr_NoMemory();
  1857. return NULL;
  1858. }
  1859. if (it->gettext) {
  1860. text = element_get_text(elem);
  1861. goto gettext;
  1862. }
  1863. if (it->sought_tag == Py_None)
  1864. return (PyObject *)elem;
  1865. rc = PyObject_RichCompareBool(elem->tag, it->sought_tag, Py_EQ);
  1866. if (rc > 0)
  1867. return (PyObject *)elem;
  1868. Py_DECREF(elem);
  1869. if (rc < 0)
  1870. return NULL;
  1871. continue;
  1872. gettext:
  1873. if (!text) {
  1874. Py_DECREF(elem);
  1875. return NULL;
  1876. }
  1877. if (text == Py_None) {
  1878. Py_DECREF(elem);
  1879. }
  1880. else {
  1881. Py_INCREF(text);
  1882. Py_DECREF(elem);
  1883. rc = PyObject_IsTrue(text);
  1884. if (rc > 0)
  1885. return text;
  1886. Py_DECREF(text);
  1887. if (rc < 0)
  1888. return NULL;
  1889. }
  1890. }
  1891. return NULL;
  1892. }
  1893. static PyType_Slot elementiter_slots[] = {
  1894. {Py_tp_dealloc, elementiter_dealloc},
  1895. {Py_tp_traverse, elementiter_traverse},
  1896. {Py_tp_iter, PyObject_SelfIter},
  1897. {Py_tp_iternext, elementiter_next},
  1898. {0, NULL},
  1899. };
  1900. static PyType_Spec elementiter_spec = {
  1901. /* Using the module's name since the pure-Python implementation does not
  1902. have such a type. */
  1903. .name = "_elementtree._element_iterator",
  1904. .basicsize = sizeof(ElementIterObject),
  1905. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1906. Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  1907. .slots = elementiter_slots,
  1908. };
  1909. #define INIT_PARENT_STACK_SIZE 8
  1910. static PyObject *
  1911. create_elementiter(elementtreestate *st, ElementObject *self, PyObject *tag,
  1912. int gettext)
  1913. {
  1914. ElementIterObject *it;
  1915. it = PyObject_GC_New(ElementIterObject, st->ElementIter_Type);
  1916. if (!it)
  1917. return NULL;
  1918. it->sought_tag = Py_NewRef(tag);
  1919. it->gettext = gettext;
  1920. it->root_element = (ElementObject*)Py_NewRef(self);
  1921. it->parent_stack = PyMem_New(ParentLocator, INIT_PARENT_STACK_SIZE);
  1922. if (it->parent_stack == NULL) {
  1923. Py_DECREF(it);
  1924. PyErr_NoMemory();
  1925. return NULL;
  1926. }
  1927. it->parent_stack_used = 0;
  1928. it->parent_stack_size = INIT_PARENT_STACK_SIZE;
  1929. PyObject_GC_Track(it);
  1930. return (PyObject *)it;
  1931. }
  1932. /* ==================================================================== */
  1933. /* the tree builder type */
  1934. typedef struct {
  1935. PyObject_HEAD
  1936. PyObject *root; /* root node (first created node) */
  1937. PyObject *this; /* current node */
  1938. PyObject *last; /* most recently created node */
  1939. PyObject *last_for_tail; /* most recently created node that takes a tail */
  1940. PyObject *data; /* data collector (string or list), or NULL */
  1941. PyObject *stack; /* element stack */
  1942. Py_ssize_t index; /* current stack size (0 means empty) */
  1943. PyObject *element_factory;
  1944. PyObject *comment_factory;
  1945. PyObject *pi_factory;
  1946. /* element tracing */
  1947. PyObject *events_append; /* the append method of the list of events, or NULL */
  1948. PyObject *start_event_obj; /* event objects (NULL to ignore) */
  1949. PyObject *end_event_obj;
  1950. PyObject *start_ns_event_obj;
  1951. PyObject *end_ns_event_obj;
  1952. PyObject *comment_event_obj;
  1953. PyObject *pi_event_obj;
  1954. char insert_comments;
  1955. char insert_pis;
  1956. elementtreestate *state;
  1957. } TreeBuilderObject;
  1958. #define TreeBuilder_CheckExact(st, op) Py_IS_TYPE((op), (st)->TreeBuilder_Type)
  1959. /* -------------------------------------------------------------------- */
  1960. /* constructor and destructor */
  1961. static PyObject *
  1962. treebuilder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1963. {
  1964. TreeBuilderObject *t = (TreeBuilderObject *)type->tp_alloc(type, 0);
  1965. if (t != NULL) {
  1966. t->root = NULL;
  1967. t->this = Py_NewRef(Py_None);
  1968. t->last = Py_NewRef(Py_None);
  1969. t->data = NULL;
  1970. t->element_factory = NULL;
  1971. t->comment_factory = NULL;
  1972. t->pi_factory = NULL;
  1973. t->stack = PyList_New(20);
  1974. if (!t->stack) {
  1975. Py_DECREF(t->this);
  1976. Py_DECREF(t->last);
  1977. Py_DECREF((PyObject *) t);
  1978. return NULL;
  1979. }
  1980. t->index = 0;
  1981. t->events_append = NULL;
  1982. t->start_event_obj = t->end_event_obj = NULL;
  1983. t->start_ns_event_obj = t->end_ns_event_obj = NULL;
  1984. t->comment_event_obj = t->pi_event_obj = NULL;
  1985. t->insert_comments = t->insert_pis = 0;
  1986. t->state = get_elementtree_state_by_type(type);
  1987. }
  1988. return (PyObject *)t;
  1989. }
  1990. /*[clinic input]
  1991. _elementtree.TreeBuilder.__init__
  1992. element_factory: object = None
  1993. *
  1994. comment_factory: object = None
  1995. pi_factory: object = None
  1996. insert_comments: bool = False
  1997. insert_pis: bool = False
  1998. [clinic start generated code]*/
  1999. static int
  2000. _elementtree_TreeBuilder___init___impl(TreeBuilderObject *self,
  2001. PyObject *element_factory,
  2002. PyObject *comment_factory,
  2003. PyObject *pi_factory,
  2004. int insert_comments, int insert_pis)
  2005. /*[clinic end generated code: output=8571d4dcadfdf952 input=ae98a94df20b5cc3]*/
  2006. {
  2007. if (element_factory != Py_None) {
  2008. Py_XSETREF(self->element_factory, Py_NewRef(element_factory));
  2009. } else {
  2010. Py_CLEAR(self->element_factory);
  2011. }
  2012. if (comment_factory == Py_None) {
  2013. elementtreestate *st = self->state;
  2014. comment_factory = st->comment_factory;
  2015. }
  2016. if (comment_factory) {
  2017. Py_XSETREF(self->comment_factory, Py_NewRef(comment_factory));
  2018. self->insert_comments = insert_comments;
  2019. } else {
  2020. Py_CLEAR(self->comment_factory);
  2021. self->insert_comments = 0;
  2022. }
  2023. if (pi_factory == Py_None) {
  2024. elementtreestate *st = self->state;
  2025. pi_factory = st->pi_factory;
  2026. }
  2027. if (pi_factory) {
  2028. Py_XSETREF(self->pi_factory, Py_NewRef(pi_factory));
  2029. self->insert_pis = insert_pis;
  2030. } else {
  2031. Py_CLEAR(self->pi_factory);
  2032. self->insert_pis = 0;
  2033. }
  2034. return 0;
  2035. }
  2036. static int
  2037. treebuilder_gc_traverse(TreeBuilderObject *self, visitproc visit, void *arg)
  2038. {
  2039. Py_VISIT(Py_TYPE(self));
  2040. Py_VISIT(self->pi_event_obj);
  2041. Py_VISIT(self->comment_event_obj);
  2042. Py_VISIT(self->end_ns_event_obj);
  2043. Py_VISIT(self->start_ns_event_obj);
  2044. Py_VISIT(self->end_event_obj);
  2045. Py_VISIT(self->start_event_obj);
  2046. Py_VISIT(self->events_append);
  2047. Py_VISIT(self->root);
  2048. Py_VISIT(self->this);
  2049. Py_VISIT(self->last);
  2050. Py_VISIT(self->last_for_tail);
  2051. Py_VISIT(self->data);
  2052. Py_VISIT(self->stack);
  2053. Py_VISIT(self->pi_factory);
  2054. Py_VISIT(self->comment_factory);
  2055. Py_VISIT(self->element_factory);
  2056. return 0;
  2057. }
  2058. static int
  2059. treebuilder_gc_clear(TreeBuilderObject *self)
  2060. {
  2061. Py_CLEAR(self->pi_event_obj);
  2062. Py_CLEAR(self->comment_event_obj);
  2063. Py_CLEAR(self->end_ns_event_obj);
  2064. Py_CLEAR(self->start_ns_event_obj);
  2065. Py_CLEAR(self->end_event_obj);
  2066. Py_CLEAR(self->start_event_obj);
  2067. Py_CLEAR(self->events_append);
  2068. Py_CLEAR(self->stack);
  2069. Py_CLEAR(self->data);
  2070. Py_CLEAR(self->last);
  2071. Py_CLEAR(self->last_for_tail);
  2072. Py_CLEAR(self->this);
  2073. Py_CLEAR(self->pi_factory);
  2074. Py_CLEAR(self->comment_factory);
  2075. Py_CLEAR(self->element_factory);
  2076. Py_CLEAR(self->root);
  2077. return 0;
  2078. }
  2079. static void
  2080. treebuilder_dealloc(TreeBuilderObject *self)
  2081. {
  2082. PyTypeObject *tp = Py_TYPE(self);
  2083. PyObject_GC_UnTrack(self);
  2084. treebuilder_gc_clear(self);
  2085. tp->tp_free(self);
  2086. Py_DECREF(tp);
  2087. }
  2088. /* -------------------------------------------------------------------- */
  2089. /* helpers for handling of arbitrary element-like objects */
  2090. /*[clinic input]
  2091. _elementtree._set_factories
  2092. comment_factory: object
  2093. pi_factory: object
  2094. /
  2095. Change the factories used to create comments and processing instructions.
  2096. For internal use only.
  2097. [clinic start generated code]*/
  2098. static PyObject *
  2099. _elementtree__set_factories_impl(PyObject *module, PyObject *comment_factory,
  2100. PyObject *pi_factory)
  2101. /*[clinic end generated code: output=813b408adee26535 input=99d17627aea7fb3b]*/
  2102. {
  2103. elementtreestate *st = get_elementtree_state(module);
  2104. PyObject *old;
  2105. if (!PyCallable_Check(comment_factory) && comment_factory != Py_None) {
  2106. PyErr_Format(PyExc_TypeError, "Comment factory must be callable, not %.100s",
  2107. Py_TYPE(comment_factory)->tp_name);
  2108. return NULL;
  2109. }
  2110. if (!PyCallable_Check(pi_factory) && pi_factory != Py_None) {
  2111. PyErr_Format(PyExc_TypeError, "PI factory must be callable, not %.100s",
  2112. Py_TYPE(pi_factory)->tp_name);
  2113. return NULL;
  2114. }
  2115. old = PyTuple_Pack(2,
  2116. st->comment_factory ? st->comment_factory : Py_None,
  2117. st->pi_factory ? st->pi_factory : Py_None);
  2118. if (comment_factory == Py_None) {
  2119. Py_CLEAR(st->comment_factory);
  2120. } else {
  2121. Py_XSETREF(st->comment_factory, Py_NewRef(comment_factory));
  2122. }
  2123. if (pi_factory == Py_None) {
  2124. Py_CLEAR(st->pi_factory);
  2125. } else {
  2126. Py_XSETREF(st->pi_factory, Py_NewRef(pi_factory));
  2127. }
  2128. return old;
  2129. }
  2130. static int
  2131. treebuilder_extend_element_text_or_tail(elementtreestate *st, PyObject *element,
  2132. PyObject **data, PyObject **dest,
  2133. PyObject *name)
  2134. {
  2135. /* Fast paths for the "almost always" cases. */
  2136. if (Element_CheckExact(st, element)) {
  2137. PyObject *dest_obj = JOIN_OBJ(*dest);
  2138. if (dest_obj == Py_None) {
  2139. *dest = JOIN_SET(*data, PyList_CheckExact(*data));
  2140. *data = NULL;
  2141. Py_DECREF(dest_obj);
  2142. return 0;
  2143. }
  2144. else if (JOIN_GET(*dest)) {
  2145. if (PyList_SetSlice(dest_obj, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, *data) < 0) {
  2146. return -1;
  2147. }
  2148. Py_CLEAR(*data);
  2149. return 0;
  2150. }
  2151. }
  2152. /* Fallback for the non-Element / non-trivial cases. */
  2153. {
  2154. int r;
  2155. PyObject* joined;
  2156. PyObject* previous = PyObject_GetAttr(element, name);
  2157. if (!previous)
  2158. return -1;
  2159. joined = list_join(*data);
  2160. if (!joined) {
  2161. Py_DECREF(previous);
  2162. return -1;
  2163. }
  2164. if (previous != Py_None) {
  2165. PyObject *tmp = PyNumber_Add(previous, joined);
  2166. Py_DECREF(joined);
  2167. Py_DECREF(previous);
  2168. if (!tmp)
  2169. return -1;
  2170. joined = tmp;
  2171. } else {
  2172. Py_DECREF(previous);
  2173. }
  2174. r = PyObject_SetAttr(element, name, joined);
  2175. Py_DECREF(joined);
  2176. if (r < 0)
  2177. return -1;
  2178. Py_CLEAR(*data);
  2179. return 0;
  2180. }
  2181. }
  2182. LOCAL(int)
  2183. treebuilder_flush_data(TreeBuilderObject* self)
  2184. {
  2185. if (!self->data) {
  2186. return 0;
  2187. }
  2188. elementtreestate *st = self->state;
  2189. if (!self->last_for_tail) {
  2190. PyObject *element = self->last;
  2191. return treebuilder_extend_element_text_or_tail(
  2192. st, element, &self->data,
  2193. &((ElementObject *) element)->text, st->str_text);
  2194. }
  2195. else {
  2196. PyObject *element = self->last_for_tail;
  2197. return treebuilder_extend_element_text_or_tail(
  2198. st, element, &self->data,
  2199. &((ElementObject *) element)->tail, st->str_tail);
  2200. }
  2201. }
  2202. static int
  2203. treebuilder_add_subelement(elementtreestate *st, PyObject *element,
  2204. PyObject *child)
  2205. {
  2206. if (Element_CheckExact(st, element)) {
  2207. ElementObject *elem = (ElementObject *) element;
  2208. return element_add_subelement(st, elem, child);
  2209. }
  2210. else {
  2211. PyObject *res;
  2212. res = PyObject_CallMethodOneArg(element, st->str_append, child);
  2213. if (res == NULL)
  2214. return -1;
  2215. Py_DECREF(res);
  2216. return 0;
  2217. }
  2218. }
  2219. LOCAL(int)
  2220. treebuilder_append_event(TreeBuilderObject *self, PyObject *action,
  2221. PyObject *node)
  2222. {
  2223. if (action != NULL) {
  2224. PyObject *res;
  2225. PyObject *event = PyTuple_Pack(2, action, node);
  2226. if (event == NULL)
  2227. return -1;
  2228. res = PyObject_CallOneArg(self->events_append, event);
  2229. Py_DECREF(event);
  2230. if (res == NULL)
  2231. return -1;
  2232. Py_DECREF(res);
  2233. }
  2234. return 0;
  2235. }
  2236. /* -------------------------------------------------------------------- */
  2237. /* handlers */
  2238. LOCAL(PyObject*)
  2239. treebuilder_handle_start(TreeBuilderObject* self, PyObject* tag,
  2240. PyObject* attrib)
  2241. {
  2242. PyObject* node;
  2243. PyObject* this;
  2244. elementtreestate *st = self->state;
  2245. if (treebuilder_flush_data(self) < 0) {
  2246. return NULL;
  2247. }
  2248. if (!self->element_factory) {
  2249. node = create_new_element(st, tag, attrib);
  2250. }
  2251. else if (attrib == NULL) {
  2252. attrib = PyDict_New();
  2253. if (!attrib)
  2254. return NULL;
  2255. node = PyObject_CallFunctionObjArgs(self->element_factory,
  2256. tag, attrib, NULL);
  2257. Py_DECREF(attrib);
  2258. }
  2259. else {
  2260. node = PyObject_CallFunctionObjArgs(self->element_factory,
  2261. tag, attrib, NULL);
  2262. }
  2263. if (!node) {
  2264. return NULL;
  2265. }
  2266. this = self->this;
  2267. Py_CLEAR(self->last_for_tail);
  2268. if (this != Py_None) {
  2269. if (treebuilder_add_subelement(st, this, node) < 0) {
  2270. goto error;
  2271. }
  2272. } else {
  2273. if (self->root) {
  2274. PyErr_SetString(
  2275. st->parseerror_obj,
  2276. "multiple elements on top level"
  2277. );
  2278. goto error;
  2279. }
  2280. self->root = Py_NewRef(node);
  2281. }
  2282. if (self->index < PyList_GET_SIZE(self->stack)) {
  2283. if (PyList_SetItem(self->stack, self->index, this) < 0)
  2284. goto error;
  2285. Py_INCREF(this);
  2286. } else {
  2287. if (PyList_Append(self->stack, this) < 0)
  2288. goto error;
  2289. }
  2290. self->index++;
  2291. Py_SETREF(self->this, Py_NewRef(node));
  2292. Py_SETREF(self->last, Py_NewRef(node));
  2293. if (treebuilder_append_event(self, self->start_event_obj, node) < 0)
  2294. goto error;
  2295. return node;
  2296. error:
  2297. Py_DECREF(node);
  2298. return NULL;
  2299. }
  2300. LOCAL(PyObject*)
  2301. treebuilder_handle_data(TreeBuilderObject* self, PyObject* data)
  2302. {
  2303. if (!self->data) {
  2304. if (self->last == Py_None) {
  2305. /* ignore calls to data before the first call to start */
  2306. Py_RETURN_NONE;
  2307. }
  2308. /* store the first item as is */
  2309. self->data = Py_NewRef(data);
  2310. } else {
  2311. /* more than one item; use a list to collect items */
  2312. if (PyBytes_CheckExact(self->data) && Py_REFCNT(self->data) == 1 &&
  2313. PyBytes_CheckExact(data) && PyBytes_GET_SIZE(data) == 1) {
  2314. /* XXX this code path unused in Python 3? */
  2315. /* expat often generates single character data sections; handle
  2316. the most common case by resizing the existing string... */
  2317. Py_ssize_t size = PyBytes_GET_SIZE(self->data);
  2318. if (_PyBytes_Resize(&self->data, size + 1) < 0)
  2319. return NULL;
  2320. PyBytes_AS_STRING(self->data)[size] = PyBytes_AS_STRING(data)[0];
  2321. } else if (PyList_CheckExact(self->data)) {
  2322. if (PyList_Append(self->data, data) < 0)
  2323. return NULL;
  2324. } else {
  2325. PyObject* list = PyList_New(2);
  2326. if (!list)
  2327. return NULL;
  2328. PyList_SET_ITEM(list, 0, Py_NewRef(self->data));
  2329. PyList_SET_ITEM(list, 1, Py_NewRef(data));
  2330. Py_SETREF(self->data, list);
  2331. }
  2332. }
  2333. Py_RETURN_NONE;
  2334. }
  2335. LOCAL(PyObject*)
  2336. treebuilder_handle_end(TreeBuilderObject* self, PyObject* tag)
  2337. {
  2338. PyObject* item;
  2339. if (treebuilder_flush_data(self) < 0) {
  2340. return NULL;
  2341. }
  2342. if (self->index == 0) {
  2343. PyErr_SetString(
  2344. PyExc_IndexError,
  2345. "pop from empty stack"
  2346. );
  2347. return NULL;
  2348. }
  2349. item = self->last;
  2350. self->last = Py_NewRef(self->this);
  2351. Py_XSETREF(self->last_for_tail, self->last);
  2352. self->index--;
  2353. self->this = Py_NewRef(PyList_GET_ITEM(self->stack, self->index));
  2354. Py_DECREF(item);
  2355. if (treebuilder_append_event(self, self->end_event_obj, self->last) < 0)
  2356. return NULL;
  2357. return Py_NewRef(self->last);
  2358. }
  2359. LOCAL(PyObject*)
  2360. treebuilder_handle_comment(TreeBuilderObject* self, PyObject* text)
  2361. {
  2362. PyObject* comment;
  2363. PyObject* this;
  2364. if (treebuilder_flush_data(self) < 0) {
  2365. return NULL;
  2366. }
  2367. if (self->comment_factory) {
  2368. comment = PyObject_CallOneArg(self->comment_factory, text);
  2369. if (!comment)
  2370. return NULL;
  2371. this = self->this;
  2372. if (self->insert_comments && this != Py_None) {
  2373. if (treebuilder_add_subelement(self->state, this, comment) < 0) {
  2374. goto error;
  2375. }
  2376. Py_XSETREF(self->last_for_tail, Py_NewRef(comment));
  2377. }
  2378. } else {
  2379. comment = Py_NewRef(text);
  2380. }
  2381. if (self->events_append && self->comment_event_obj) {
  2382. if (treebuilder_append_event(self, self->comment_event_obj, comment) < 0)
  2383. goto error;
  2384. }
  2385. return comment;
  2386. error:
  2387. Py_DECREF(comment);
  2388. return NULL;
  2389. }
  2390. LOCAL(PyObject*)
  2391. treebuilder_handle_pi(TreeBuilderObject* self, PyObject* target, PyObject* text)
  2392. {
  2393. PyObject* pi;
  2394. PyObject* this;
  2395. PyObject* stack[2] = {target, text};
  2396. if (treebuilder_flush_data(self) < 0) {
  2397. return NULL;
  2398. }
  2399. if (self->pi_factory) {
  2400. pi = _PyObject_FastCall(self->pi_factory, stack, 2);
  2401. if (!pi) {
  2402. return NULL;
  2403. }
  2404. this = self->this;
  2405. if (self->insert_pis && this != Py_None) {
  2406. if (treebuilder_add_subelement(self->state, this, pi) < 0) {
  2407. goto error;
  2408. }
  2409. Py_XSETREF(self->last_for_tail, Py_NewRef(pi));
  2410. }
  2411. } else {
  2412. pi = PyTuple_Pack(2, target, text);
  2413. if (!pi) {
  2414. return NULL;
  2415. }
  2416. }
  2417. if (self->events_append && self->pi_event_obj) {
  2418. if (treebuilder_append_event(self, self->pi_event_obj, pi) < 0)
  2419. goto error;
  2420. }
  2421. return pi;
  2422. error:
  2423. Py_DECREF(pi);
  2424. return NULL;
  2425. }
  2426. LOCAL(PyObject*)
  2427. treebuilder_handle_start_ns(TreeBuilderObject* self, PyObject* prefix, PyObject* uri)
  2428. {
  2429. PyObject* parcel;
  2430. if (self->events_append && self->start_ns_event_obj) {
  2431. parcel = PyTuple_Pack(2, prefix, uri);
  2432. if (!parcel) {
  2433. return NULL;
  2434. }
  2435. if (treebuilder_append_event(self, self->start_ns_event_obj, parcel) < 0) {
  2436. Py_DECREF(parcel);
  2437. return NULL;
  2438. }
  2439. Py_DECREF(parcel);
  2440. }
  2441. Py_RETURN_NONE;
  2442. }
  2443. LOCAL(PyObject*)
  2444. treebuilder_handle_end_ns(TreeBuilderObject* self, PyObject* prefix)
  2445. {
  2446. if (self->events_append && self->end_ns_event_obj) {
  2447. if (treebuilder_append_event(self, self->end_ns_event_obj, prefix) < 0) {
  2448. return NULL;
  2449. }
  2450. }
  2451. Py_RETURN_NONE;
  2452. }
  2453. /* -------------------------------------------------------------------- */
  2454. /* methods (in alphabetical order) */
  2455. /*[clinic input]
  2456. _elementtree.TreeBuilder.data
  2457. data: object
  2458. /
  2459. [clinic start generated code]*/
  2460. static PyObject *
  2461. _elementtree_TreeBuilder_data(TreeBuilderObject *self, PyObject *data)
  2462. /*[clinic end generated code: output=69144c7100795bb2 input=a0540c532b284d29]*/
  2463. {
  2464. return treebuilder_handle_data(self, data);
  2465. }
  2466. /*[clinic input]
  2467. _elementtree.TreeBuilder.end
  2468. tag: object
  2469. /
  2470. [clinic start generated code]*/
  2471. static PyObject *
  2472. _elementtree_TreeBuilder_end(TreeBuilderObject *self, PyObject *tag)
  2473. /*[clinic end generated code: output=9a98727cc691cd9d input=22dc3674236f5745]*/
  2474. {
  2475. return treebuilder_handle_end(self, tag);
  2476. }
  2477. /*[clinic input]
  2478. _elementtree.TreeBuilder.comment
  2479. text: object
  2480. /
  2481. [clinic start generated code]*/
  2482. static PyObject *
  2483. _elementtree_TreeBuilder_comment(TreeBuilderObject *self, PyObject *text)
  2484. /*[clinic end generated code: output=22835be41deeaa27 input=47e7ebc48ed01dfa]*/
  2485. {
  2486. return treebuilder_handle_comment(self, text);
  2487. }
  2488. /*[clinic input]
  2489. _elementtree.TreeBuilder.pi
  2490. target: object
  2491. text: object = None
  2492. /
  2493. [clinic start generated code]*/
  2494. static PyObject *
  2495. _elementtree_TreeBuilder_pi_impl(TreeBuilderObject *self, PyObject *target,
  2496. PyObject *text)
  2497. /*[clinic end generated code: output=21eb95ec9d04d1d9 input=349342bd79c35570]*/
  2498. {
  2499. return treebuilder_handle_pi(self, target, text);
  2500. }
  2501. LOCAL(PyObject*)
  2502. treebuilder_done(TreeBuilderObject* self)
  2503. {
  2504. PyObject* res;
  2505. /* FIXME: check stack size? */
  2506. if (self->root)
  2507. res = self->root;
  2508. else
  2509. res = Py_None;
  2510. return Py_NewRef(res);
  2511. }
  2512. /*[clinic input]
  2513. _elementtree.TreeBuilder.close
  2514. [clinic start generated code]*/
  2515. static PyObject *
  2516. _elementtree_TreeBuilder_close_impl(TreeBuilderObject *self)
  2517. /*[clinic end generated code: output=b441fee3202f61ee input=f7c9c65dc718de14]*/
  2518. {
  2519. return treebuilder_done(self);
  2520. }
  2521. /*[clinic input]
  2522. _elementtree.TreeBuilder.start
  2523. tag: object
  2524. attrs: object(subclass_of='&PyDict_Type')
  2525. /
  2526. [clinic start generated code]*/
  2527. static PyObject *
  2528. _elementtree_TreeBuilder_start_impl(TreeBuilderObject *self, PyObject *tag,
  2529. PyObject *attrs)
  2530. /*[clinic end generated code: output=e7e9dc2861349411 input=7288e9e38e63b2b6]*/
  2531. {
  2532. return treebuilder_handle_start(self, tag, attrs);
  2533. }
  2534. /* ==================================================================== */
  2535. /* the expat interface */
  2536. #define EXPAT(st, func) ((st)->expat_capi->func)
  2537. static XML_Memory_Handling_Suite ExpatMemoryHandler = {
  2538. PyObject_Malloc, PyObject_Realloc, PyObject_Free};
  2539. typedef struct {
  2540. PyObject_HEAD
  2541. XML_Parser parser;
  2542. PyObject *target;
  2543. PyObject *entity;
  2544. PyObject *names;
  2545. PyObject *handle_start_ns;
  2546. PyObject *handle_end_ns;
  2547. PyObject *handle_start;
  2548. PyObject *handle_data;
  2549. PyObject *handle_end;
  2550. PyObject *handle_comment;
  2551. PyObject *handle_pi;
  2552. PyObject *handle_doctype;
  2553. PyObject *handle_close;
  2554. elementtreestate *state;
  2555. PyObject *elementtree_module;
  2556. } XMLParserObject;
  2557. /* helpers */
  2558. LOCAL(PyObject*)
  2559. makeuniversal(XMLParserObject* self, const char* string)
  2560. {
  2561. /* convert a UTF-8 tag/attribute name from the expat parser
  2562. to a universal name string */
  2563. Py_ssize_t size = (Py_ssize_t) strlen(string);
  2564. PyObject* key;
  2565. PyObject* value;
  2566. /* look the 'raw' name up in the names dictionary */
  2567. key = PyBytes_FromStringAndSize(string, size);
  2568. if (!key)
  2569. return NULL;
  2570. value = Py_XNewRef(PyDict_GetItemWithError(self->names, key));
  2571. if (value == NULL && !PyErr_Occurred()) {
  2572. /* new name. convert to universal name, and decode as
  2573. necessary */
  2574. PyObject* tag;
  2575. char* p;
  2576. Py_ssize_t i;
  2577. /* look for namespace separator */
  2578. for (i = 0; i < size; i++)
  2579. if (string[i] == '}')
  2580. break;
  2581. if (i != size) {
  2582. /* convert to universal name */
  2583. tag = PyBytes_FromStringAndSize(NULL, size+1);
  2584. if (tag == NULL) {
  2585. Py_DECREF(key);
  2586. return NULL;
  2587. }
  2588. p = PyBytes_AS_STRING(tag);
  2589. p[0] = '{';
  2590. memcpy(p+1, string, size);
  2591. size++;
  2592. } else {
  2593. /* plain name; use key as tag */
  2594. tag = Py_NewRef(key);
  2595. }
  2596. /* decode universal name */
  2597. p = PyBytes_AS_STRING(tag);
  2598. value = PyUnicode_DecodeUTF8(p, size, "strict");
  2599. Py_DECREF(tag);
  2600. if (!value) {
  2601. Py_DECREF(key);
  2602. return NULL;
  2603. }
  2604. /* add to names dictionary */
  2605. if (PyDict_SetItem(self->names, key, value) < 0) {
  2606. Py_DECREF(key);
  2607. Py_DECREF(value);
  2608. return NULL;
  2609. }
  2610. }
  2611. Py_DECREF(key);
  2612. return value;
  2613. }
  2614. /* Set the ParseError exception with the given parameters.
  2615. * If message is not NULL, it's used as the error string. Otherwise, the
  2616. * message string is the default for the given error_code.
  2617. */
  2618. static void
  2619. expat_set_error(elementtreestate *st, enum XML_Error error_code,
  2620. Py_ssize_t line, Py_ssize_t column, const char *message)
  2621. {
  2622. PyObject *errmsg, *error, *position, *code;
  2623. errmsg = PyUnicode_FromFormat("%s: line %zd, column %zd",
  2624. message ? message : EXPAT(st, ErrorString)(error_code),
  2625. line, column);
  2626. if (errmsg == NULL)
  2627. return;
  2628. error = PyObject_CallOneArg(st->parseerror_obj, errmsg);
  2629. Py_DECREF(errmsg);
  2630. if (!error)
  2631. return;
  2632. /* Add code and position attributes */
  2633. code = PyLong_FromLong((long)error_code);
  2634. if (!code) {
  2635. Py_DECREF(error);
  2636. return;
  2637. }
  2638. if (PyObject_SetAttrString(error, "code", code) == -1) {
  2639. Py_DECREF(error);
  2640. Py_DECREF(code);
  2641. return;
  2642. }
  2643. Py_DECREF(code);
  2644. position = Py_BuildValue("(nn)", line, column);
  2645. if (!position) {
  2646. Py_DECREF(error);
  2647. return;
  2648. }
  2649. if (PyObject_SetAttrString(error, "position", position) == -1) {
  2650. Py_DECREF(error);
  2651. Py_DECREF(position);
  2652. return;
  2653. }
  2654. Py_DECREF(position);
  2655. PyErr_SetObject(st->parseerror_obj, error);
  2656. Py_DECREF(error);
  2657. }
  2658. /* -------------------------------------------------------------------- */
  2659. /* handlers */
  2660. static void
  2661. expat_default_handler(XMLParserObject* self, const XML_Char* data_in,
  2662. int data_len)
  2663. {
  2664. PyObject* key;
  2665. PyObject* value;
  2666. PyObject* res;
  2667. if (data_len < 2 || data_in[0] != '&')
  2668. return;
  2669. if (PyErr_Occurred())
  2670. return;
  2671. key = PyUnicode_DecodeUTF8(data_in + 1, data_len - 2, "strict");
  2672. if (!key)
  2673. return;
  2674. value = PyDict_GetItemWithError(self->entity, key);
  2675. elementtreestate *st = self->state;
  2676. if (value) {
  2677. if (TreeBuilder_CheckExact(st, self->target))
  2678. res = treebuilder_handle_data(
  2679. (TreeBuilderObject*) self->target, value
  2680. );
  2681. else if (self->handle_data)
  2682. res = PyObject_CallOneArg(self->handle_data, value);
  2683. else
  2684. res = NULL;
  2685. Py_XDECREF(res);
  2686. } else if (!PyErr_Occurred()) {
  2687. /* Report the first error, not the last */
  2688. char message[128] = "undefined entity ";
  2689. strncat(message, data_in, data_len < 100?data_len:100);
  2690. expat_set_error(
  2691. st,
  2692. XML_ERROR_UNDEFINED_ENTITY,
  2693. EXPAT(st, GetErrorLineNumber)(self->parser),
  2694. EXPAT(st, GetErrorColumnNumber)(self->parser),
  2695. message
  2696. );
  2697. }
  2698. Py_DECREF(key);
  2699. }
  2700. static void
  2701. expat_start_handler(XMLParserObject* self, const XML_Char* tag_in,
  2702. const XML_Char **attrib_in)
  2703. {
  2704. PyObject* res;
  2705. PyObject* tag;
  2706. PyObject* attrib;
  2707. int ok;
  2708. if (PyErr_Occurred())
  2709. return;
  2710. /* tag name */
  2711. tag = makeuniversal(self, tag_in);
  2712. if (!tag)
  2713. return; /* parser will look for errors */
  2714. /* attributes */
  2715. if (attrib_in[0]) {
  2716. attrib = PyDict_New();
  2717. if (!attrib) {
  2718. Py_DECREF(tag);
  2719. return;
  2720. }
  2721. while (attrib_in[0] && attrib_in[1]) {
  2722. PyObject* key = makeuniversal(self, attrib_in[0]);
  2723. if (key == NULL) {
  2724. Py_DECREF(attrib);
  2725. Py_DECREF(tag);
  2726. return;
  2727. }
  2728. PyObject* value = PyUnicode_DecodeUTF8(attrib_in[1], strlen(attrib_in[1]), "strict");
  2729. if (value == NULL) {
  2730. Py_DECREF(key);
  2731. Py_DECREF(attrib);
  2732. Py_DECREF(tag);
  2733. return;
  2734. }
  2735. ok = PyDict_SetItem(attrib, key, value);
  2736. Py_DECREF(value);
  2737. Py_DECREF(key);
  2738. if (ok < 0) {
  2739. Py_DECREF(attrib);
  2740. Py_DECREF(tag);
  2741. return;
  2742. }
  2743. attrib_in += 2;
  2744. }
  2745. } else {
  2746. attrib = NULL;
  2747. }
  2748. elementtreestate *st = self->state;
  2749. if (TreeBuilder_CheckExact(st, self->target)) {
  2750. /* shortcut */
  2751. res = treebuilder_handle_start((TreeBuilderObject*) self->target,
  2752. tag, attrib);
  2753. }
  2754. else if (self->handle_start) {
  2755. if (attrib == NULL) {
  2756. attrib = PyDict_New();
  2757. if (!attrib) {
  2758. Py_DECREF(tag);
  2759. return;
  2760. }
  2761. }
  2762. res = PyObject_CallFunctionObjArgs(self->handle_start,
  2763. tag, attrib, NULL);
  2764. } else
  2765. res = NULL;
  2766. Py_DECREF(tag);
  2767. Py_XDECREF(attrib);
  2768. Py_XDECREF(res);
  2769. }
  2770. static void
  2771. expat_data_handler(XMLParserObject* self, const XML_Char* data_in,
  2772. int data_len)
  2773. {
  2774. PyObject* data;
  2775. PyObject* res;
  2776. if (PyErr_Occurred())
  2777. return;
  2778. data = PyUnicode_DecodeUTF8(data_in, data_len, "strict");
  2779. if (!data)
  2780. return; /* parser will look for errors */
  2781. elementtreestate *st = self->state;
  2782. if (TreeBuilder_CheckExact(st, self->target))
  2783. /* shortcut */
  2784. res = treebuilder_handle_data((TreeBuilderObject*) self->target, data);
  2785. else if (self->handle_data)
  2786. res = PyObject_CallOneArg(self->handle_data, data);
  2787. else
  2788. res = NULL;
  2789. Py_DECREF(data);
  2790. Py_XDECREF(res);
  2791. }
  2792. static void
  2793. expat_end_handler(XMLParserObject* self, const XML_Char* tag_in)
  2794. {
  2795. PyObject* tag;
  2796. PyObject* res = NULL;
  2797. if (PyErr_Occurred())
  2798. return;
  2799. elementtreestate *st = self->state;
  2800. if (TreeBuilder_CheckExact(st, self->target))
  2801. /* shortcut */
  2802. /* the standard tree builder doesn't look at the end tag */
  2803. res = treebuilder_handle_end(
  2804. (TreeBuilderObject*) self->target, Py_None
  2805. );
  2806. else if (self->handle_end) {
  2807. tag = makeuniversal(self, tag_in);
  2808. if (tag) {
  2809. res = PyObject_CallOneArg(self->handle_end, tag);
  2810. Py_DECREF(tag);
  2811. }
  2812. }
  2813. Py_XDECREF(res);
  2814. }
  2815. static void
  2816. expat_start_ns_handler(XMLParserObject* self, const XML_Char* prefix_in,
  2817. const XML_Char *uri_in)
  2818. {
  2819. PyObject* res = NULL;
  2820. PyObject* uri;
  2821. PyObject* prefix;
  2822. PyObject* stack[2];
  2823. if (PyErr_Occurred())
  2824. return;
  2825. if (!uri_in)
  2826. uri_in = "";
  2827. if (!prefix_in)
  2828. prefix_in = "";
  2829. elementtreestate *st = self->state;
  2830. if (TreeBuilder_CheckExact(st, self->target)) {
  2831. /* shortcut - TreeBuilder does not actually implement .start_ns() */
  2832. TreeBuilderObject *target = (TreeBuilderObject*) self->target;
  2833. if (target->events_append && target->start_ns_event_obj) {
  2834. prefix = PyUnicode_DecodeUTF8(prefix_in, strlen(prefix_in), "strict");
  2835. if (!prefix)
  2836. return;
  2837. uri = PyUnicode_DecodeUTF8(uri_in, strlen(uri_in), "strict");
  2838. if (!uri) {
  2839. Py_DECREF(prefix);
  2840. return;
  2841. }
  2842. res = treebuilder_handle_start_ns(target, prefix, uri);
  2843. Py_DECREF(uri);
  2844. Py_DECREF(prefix);
  2845. }
  2846. } else if (self->handle_start_ns) {
  2847. prefix = PyUnicode_DecodeUTF8(prefix_in, strlen(prefix_in), "strict");
  2848. if (!prefix)
  2849. return;
  2850. uri = PyUnicode_DecodeUTF8(uri_in, strlen(uri_in), "strict");
  2851. if (!uri) {
  2852. Py_DECREF(prefix);
  2853. return;
  2854. }
  2855. stack[0] = prefix;
  2856. stack[1] = uri;
  2857. res = _PyObject_FastCall(self->handle_start_ns, stack, 2);
  2858. Py_DECREF(uri);
  2859. Py_DECREF(prefix);
  2860. }
  2861. Py_XDECREF(res);
  2862. }
  2863. static void
  2864. expat_end_ns_handler(XMLParserObject* self, const XML_Char* prefix_in)
  2865. {
  2866. PyObject *res = NULL;
  2867. PyObject* prefix;
  2868. if (PyErr_Occurred())
  2869. return;
  2870. if (!prefix_in)
  2871. prefix_in = "";
  2872. elementtreestate *st = self->state;
  2873. if (TreeBuilder_CheckExact(st, self->target)) {
  2874. /* shortcut - TreeBuilder does not actually implement .end_ns() */
  2875. TreeBuilderObject *target = (TreeBuilderObject*) self->target;
  2876. if (target->events_append && target->end_ns_event_obj) {
  2877. res = treebuilder_handle_end_ns(target, Py_None);
  2878. }
  2879. } else if (self->handle_end_ns) {
  2880. prefix = PyUnicode_DecodeUTF8(prefix_in, strlen(prefix_in), "strict");
  2881. if (!prefix)
  2882. return;
  2883. res = PyObject_CallOneArg(self->handle_end_ns, prefix);
  2884. Py_DECREF(prefix);
  2885. }
  2886. Py_XDECREF(res);
  2887. }
  2888. static void
  2889. expat_comment_handler(XMLParserObject* self, const XML_Char* comment_in)
  2890. {
  2891. PyObject* comment;
  2892. PyObject* res;
  2893. if (PyErr_Occurred())
  2894. return;
  2895. elementtreestate *st = self->state;
  2896. if (TreeBuilder_CheckExact(st, self->target)) {
  2897. /* shortcut */
  2898. TreeBuilderObject *target = (TreeBuilderObject*) self->target;
  2899. comment = PyUnicode_DecodeUTF8(comment_in, strlen(comment_in), "strict");
  2900. if (!comment)
  2901. return; /* parser will look for errors */
  2902. res = treebuilder_handle_comment(target, comment);
  2903. Py_XDECREF(res);
  2904. Py_DECREF(comment);
  2905. } else if (self->handle_comment) {
  2906. comment = PyUnicode_DecodeUTF8(comment_in, strlen(comment_in), "strict");
  2907. if (!comment)
  2908. return;
  2909. res = PyObject_CallOneArg(self->handle_comment, comment);
  2910. Py_XDECREF(res);
  2911. Py_DECREF(comment);
  2912. }
  2913. }
  2914. static void
  2915. expat_start_doctype_handler(XMLParserObject *self,
  2916. const XML_Char *doctype_name,
  2917. const XML_Char *sysid,
  2918. const XML_Char *pubid,
  2919. int has_internal_subset)
  2920. {
  2921. PyObject *doctype_name_obj, *sysid_obj, *pubid_obj;
  2922. PyObject *res;
  2923. if (PyErr_Occurred())
  2924. return;
  2925. doctype_name_obj = makeuniversal(self, doctype_name);
  2926. if (!doctype_name_obj)
  2927. return;
  2928. if (sysid) {
  2929. sysid_obj = makeuniversal(self, sysid);
  2930. if (!sysid_obj) {
  2931. Py_DECREF(doctype_name_obj);
  2932. return;
  2933. }
  2934. } else {
  2935. sysid_obj = Py_NewRef(Py_None);
  2936. }
  2937. if (pubid) {
  2938. pubid_obj = makeuniversal(self, pubid);
  2939. if (!pubid_obj) {
  2940. Py_DECREF(doctype_name_obj);
  2941. Py_DECREF(sysid_obj);
  2942. return;
  2943. }
  2944. } else {
  2945. pubid_obj = Py_NewRef(Py_None);
  2946. }
  2947. elementtreestate *st = self->state;
  2948. /* If the target has a handler for doctype, call it. */
  2949. if (self->handle_doctype) {
  2950. res = PyObject_CallFunctionObjArgs(self->handle_doctype,
  2951. doctype_name_obj, pubid_obj,
  2952. sysid_obj, NULL);
  2953. Py_XDECREF(res);
  2954. }
  2955. else if (_PyObject_LookupAttr((PyObject *)self, st->str_doctype, &res) > 0) {
  2956. (void)PyErr_WarnEx(PyExc_RuntimeWarning,
  2957. "The doctype() method of XMLParser is ignored. "
  2958. "Define doctype() method on the TreeBuilder target.",
  2959. 1);
  2960. Py_DECREF(res);
  2961. }
  2962. Py_DECREF(doctype_name_obj);
  2963. Py_DECREF(pubid_obj);
  2964. Py_DECREF(sysid_obj);
  2965. }
  2966. static void
  2967. expat_pi_handler(XMLParserObject* self, const XML_Char* target_in,
  2968. const XML_Char* data_in)
  2969. {
  2970. PyObject* pi_target;
  2971. PyObject* data;
  2972. PyObject* res;
  2973. PyObject* stack[2];
  2974. if (PyErr_Occurred())
  2975. return;
  2976. elementtreestate *st = self->state;
  2977. if (TreeBuilder_CheckExact(st, self->target)) {
  2978. /* shortcut */
  2979. TreeBuilderObject *target = (TreeBuilderObject*) self->target;
  2980. if ((target->events_append && target->pi_event_obj) || target->insert_pis) {
  2981. pi_target = PyUnicode_DecodeUTF8(target_in, strlen(target_in), "strict");
  2982. if (!pi_target)
  2983. goto error;
  2984. data = PyUnicode_DecodeUTF8(data_in, strlen(data_in), "strict");
  2985. if (!data)
  2986. goto error;
  2987. res = treebuilder_handle_pi(target, pi_target, data);
  2988. Py_XDECREF(res);
  2989. Py_DECREF(data);
  2990. Py_DECREF(pi_target);
  2991. }
  2992. } else if (self->handle_pi) {
  2993. pi_target = PyUnicode_DecodeUTF8(target_in, strlen(target_in), "strict");
  2994. if (!pi_target)
  2995. goto error;
  2996. data = PyUnicode_DecodeUTF8(data_in, strlen(data_in), "strict");
  2997. if (!data)
  2998. goto error;
  2999. stack[0] = pi_target;
  3000. stack[1] = data;
  3001. res = _PyObject_FastCall(self->handle_pi, stack, 2);
  3002. Py_XDECREF(res);
  3003. Py_DECREF(data);
  3004. Py_DECREF(pi_target);
  3005. }
  3006. return;
  3007. error:
  3008. Py_XDECREF(pi_target);
  3009. return;
  3010. }
  3011. /* -------------------------------------------------------------------- */
  3012. static PyObject *
  3013. xmlparser_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3014. {
  3015. XMLParserObject *self = (XMLParserObject *)type->tp_alloc(type, 0);
  3016. if (self) {
  3017. self->parser = NULL;
  3018. self->target = self->entity = self->names = NULL;
  3019. self->handle_start_ns = self->handle_end_ns = NULL;
  3020. self->handle_start = self->handle_data = self->handle_end = NULL;
  3021. self->handle_comment = self->handle_pi = self->handle_close = NULL;
  3022. self->handle_doctype = NULL;
  3023. self->elementtree_module = PyType_GetModuleByDef(type, &elementtreemodule);
  3024. assert(self->elementtree_module != NULL);
  3025. Py_INCREF(self->elementtree_module);
  3026. // See gh-111784 for explanation why is reference to module needed here.
  3027. self->state = get_elementtree_state(self->elementtree_module);
  3028. }
  3029. return (PyObject *)self;
  3030. }
  3031. static int
  3032. ignore_attribute_error(PyObject *value)
  3033. {
  3034. if (value == NULL) {
  3035. if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
  3036. return -1;
  3037. }
  3038. PyErr_Clear();
  3039. }
  3040. return 0;
  3041. }
  3042. /*[clinic input]
  3043. _elementtree.XMLParser.__init__
  3044. *
  3045. target: object = None
  3046. encoding: str(accept={str, NoneType}) = None
  3047. [clinic start generated code]*/
  3048. static int
  3049. _elementtree_XMLParser___init___impl(XMLParserObject *self, PyObject *target,
  3050. const char *encoding)
  3051. /*[clinic end generated code: output=3ae45ec6cdf344e4 input=7e716dd6e4f3e439]*/
  3052. {
  3053. self->entity = PyDict_New();
  3054. if (!self->entity)
  3055. return -1;
  3056. self->names = PyDict_New();
  3057. if (!self->names) {
  3058. Py_CLEAR(self->entity);
  3059. return -1;
  3060. }
  3061. elementtreestate *st = self->state;
  3062. self->parser = EXPAT(st, ParserCreate_MM)(encoding, &ExpatMemoryHandler, "}");
  3063. if (!self->parser) {
  3064. Py_CLEAR(self->entity);
  3065. Py_CLEAR(self->names);
  3066. PyErr_NoMemory();
  3067. return -1;
  3068. }
  3069. /* expat < 2.1.0 has no XML_SetHashSalt() */
  3070. if (EXPAT(st, SetHashSalt) != NULL) {
  3071. EXPAT(st, SetHashSalt)(self->parser,
  3072. (unsigned long)_Py_HashSecret.expat.hashsalt);
  3073. }
  3074. if (target != Py_None) {
  3075. Py_INCREF(target);
  3076. } else {
  3077. target = treebuilder_new(st->TreeBuilder_Type, NULL, NULL);
  3078. if (!target) {
  3079. Py_CLEAR(self->entity);
  3080. Py_CLEAR(self->names);
  3081. return -1;
  3082. }
  3083. }
  3084. self->target = target;
  3085. self->handle_start_ns = PyObject_GetAttrString(target, "start_ns");
  3086. if (ignore_attribute_error(self->handle_start_ns)) {
  3087. return -1;
  3088. }
  3089. self->handle_end_ns = PyObject_GetAttrString(target, "end_ns");
  3090. if (ignore_attribute_error(self->handle_end_ns)) {
  3091. return -1;
  3092. }
  3093. self->handle_start = PyObject_GetAttrString(target, "start");
  3094. if (ignore_attribute_error(self->handle_start)) {
  3095. return -1;
  3096. }
  3097. self->handle_data = PyObject_GetAttrString(target, "data");
  3098. if (ignore_attribute_error(self->handle_data)) {
  3099. return -1;
  3100. }
  3101. self->handle_end = PyObject_GetAttrString(target, "end");
  3102. if (ignore_attribute_error(self->handle_end)) {
  3103. return -1;
  3104. }
  3105. self->handle_comment = PyObject_GetAttrString(target, "comment");
  3106. if (ignore_attribute_error(self->handle_comment)) {
  3107. return -1;
  3108. }
  3109. self->handle_pi = PyObject_GetAttrString(target, "pi");
  3110. if (ignore_attribute_error(self->handle_pi)) {
  3111. return -1;
  3112. }
  3113. self->handle_close = PyObject_GetAttrString(target, "close");
  3114. if (ignore_attribute_error(self->handle_close)) {
  3115. return -1;
  3116. }
  3117. self->handle_doctype = PyObject_GetAttrString(target, "doctype");
  3118. if (ignore_attribute_error(self->handle_doctype)) {
  3119. return -1;
  3120. }
  3121. /* configure parser */
  3122. EXPAT(st, SetUserData)(self->parser, self);
  3123. if (self->handle_start_ns || self->handle_end_ns)
  3124. EXPAT(st, SetNamespaceDeclHandler)(
  3125. self->parser,
  3126. (XML_StartNamespaceDeclHandler) expat_start_ns_handler,
  3127. (XML_EndNamespaceDeclHandler) expat_end_ns_handler
  3128. );
  3129. EXPAT(st, SetElementHandler)(
  3130. self->parser,
  3131. (XML_StartElementHandler) expat_start_handler,
  3132. (XML_EndElementHandler) expat_end_handler
  3133. );
  3134. EXPAT(st, SetDefaultHandlerExpand)(
  3135. self->parser,
  3136. (XML_DefaultHandler) expat_default_handler
  3137. );
  3138. EXPAT(st, SetCharacterDataHandler)(
  3139. self->parser,
  3140. (XML_CharacterDataHandler) expat_data_handler
  3141. );
  3142. if (self->handle_comment)
  3143. EXPAT(st, SetCommentHandler)(
  3144. self->parser,
  3145. (XML_CommentHandler) expat_comment_handler
  3146. );
  3147. if (self->handle_pi)
  3148. EXPAT(st, SetProcessingInstructionHandler)(
  3149. self->parser,
  3150. (XML_ProcessingInstructionHandler) expat_pi_handler
  3151. );
  3152. EXPAT(st, SetStartDoctypeDeclHandler)(
  3153. self->parser,
  3154. (XML_StartDoctypeDeclHandler) expat_start_doctype_handler
  3155. );
  3156. EXPAT(st, SetUnknownEncodingHandler)(
  3157. self->parser,
  3158. EXPAT(st, DefaultUnknownEncodingHandler), NULL
  3159. );
  3160. return 0;
  3161. }
  3162. static int
  3163. xmlparser_gc_traverse(XMLParserObject *self, visitproc visit, void *arg)
  3164. {
  3165. Py_VISIT(Py_TYPE(self));
  3166. Py_VISIT(self->handle_close);
  3167. Py_VISIT(self->handle_pi);
  3168. Py_VISIT(self->handle_comment);
  3169. Py_VISIT(self->handle_end);
  3170. Py_VISIT(self->handle_data);
  3171. Py_VISIT(self->handle_start);
  3172. Py_VISIT(self->handle_start_ns);
  3173. Py_VISIT(self->handle_end_ns);
  3174. Py_VISIT(self->handle_doctype);
  3175. Py_VISIT(self->target);
  3176. Py_VISIT(self->entity);
  3177. Py_VISIT(self->names);
  3178. return 0;
  3179. }
  3180. static int
  3181. xmlparser_gc_clear(XMLParserObject *self)
  3182. {
  3183. elementtreestate *st = self->state;
  3184. if (self->parser != NULL) {
  3185. XML_Parser parser = self->parser;
  3186. self->parser = NULL;
  3187. EXPAT(st, ParserFree)(parser);
  3188. }
  3189. Py_CLEAR(self->elementtree_module);
  3190. Py_CLEAR(self->handle_close);
  3191. Py_CLEAR(self->handle_pi);
  3192. Py_CLEAR(self->handle_comment);
  3193. Py_CLEAR(self->handle_end);
  3194. Py_CLEAR(self->handle_data);
  3195. Py_CLEAR(self->handle_start);
  3196. Py_CLEAR(self->handle_start_ns);
  3197. Py_CLEAR(self->handle_end_ns);
  3198. Py_CLEAR(self->handle_doctype);
  3199. Py_CLEAR(self->target);
  3200. Py_CLEAR(self->entity);
  3201. Py_CLEAR(self->names);
  3202. return 0;
  3203. }
  3204. static void
  3205. xmlparser_dealloc(XMLParserObject* self)
  3206. {
  3207. PyTypeObject *tp = Py_TYPE(self);
  3208. PyObject_GC_UnTrack(self);
  3209. xmlparser_gc_clear(self);
  3210. tp->tp_free(self);
  3211. Py_DECREF(tp);
  3212. }
  3213. Py_LOCAL_INLINE(int)
  3214. _check_xmlparser(XMLParserObject* self)
  3215. {
  3216. if (self->target == NULL) {
  3217. PyErr_SetString(PyExc_ValueError,
  3218. "XMLParser.__init__() wasn't called");
  3219. return 0;
  3220. }
  3221. return 1;
  3222. }
  3223. LOCAL(PyObject*)
  3224. expat_parse(elementtreestate *st, XMLParserObject *self, const char *data,
  3225. int data_len, int final)
  3226. {
  3227. int ok;
  3228. assert(!PyErr_Occurred());
  3229. ok = EXPAT(st, Parse)(self->parser, data, data_len, final);
  3230. if (PyErr_Occurred())
  3231. return NULL;
  3232. if (!ok) {
  3233. expat_set_error(
  3234. st,
  3235. EXPAT(st, GetErrorCode)(self->parser),
  3236. EXPAT(st, GetErrorLineNumber)(self->parser),
  3237. EXPAT(st, GetErrorColumnNumber)(self->parser),
  3238. NULL
  3239. );
  3240. return NULL;
  3241. }
  3242. Py_RETURN_NONE;
  3243. }
  3244. /*[clinic input]
  3245. _elementtree.XMLParser.close
  3246. [clinic start generated code]*/
  3247. static PyObject *
  3248. _elementtree_XMLParser_close_impl(XMLParserObject *self)
  3249. /*[clinic end generated code: output=d68d375dd23bc7fb input=ca7909ca78c3abfe]*/
  3250. {
  3251. /* end feeding data to parser */
  3252. PyObject* res;
  3253. if (!_check_xmlparser(self)) {
  3254. return NULL;
  3255. }
  3256. elementtreestate *st = self->state;
  3257. res = expat_parse(st, self, "", 0, 1);
  3258. if (!res)
  3259. return NULL;
  3260. if (TreeBuilder_CheckExact(st, self->target)) {
  3261. Py_DECREF(res);
  3262. return treebuilder_done((TreeBuilderObject*) self->target);
  3263. }
  3264. else if (self->handle_close) {
  3265. Py_DECREF(res);
  3266. return PyObject_CallNoArgs(self->handle_close);
  3267. }
  3268. else {
  3269. return res;
  3270. }
  3271. }
  3272. /*[clinic input]
  3273. _elementtree.XMLParser.feed
  3274. data: object
  3275. /
  3276. [clinic start generated code]*/
  3277. static PyObject *
  3278. _elementtree_XMLParser_feed(XMLParserObject *self, PyObject *data)
  3279. /*[clinic end generated code: output=e42b6a78eec7446d input=fe231b6b8de3ce1f]*/
  3280. {
  3281. /* feed data to parser */
  3282. if (!_check_xmlparser(self)) {
  3283. return NULL;
  3284. }
  3285. elementtreestate *st = self->state;
  3286. if (PyUnicode_Check(data)) {
  3287. Py_ssize_t data_len;
  3288. const char *data_ptr = PyUnicode_AsUTF8AndSize(data, &data_len);
  3289. if (data_ptr == NULL)
  3290. return NULL;
  3291. if (data_len > INT_MAX) {
  3292. PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
  3293. return NULL;
  3294. }
  3295. /* Explicitly set UTF-8 encoding. Return code ignored. */
  3296. (void)EXPAT(st, SetEncoding)(self->parser, "utf-8");
  3297. return expat_parse(st, self, data_ptr, (int)data_len, 0);
  3298. }
  3299. else {
  3300. Py_buffer view;
  3301. PyObject *res;
  3302. if (PyObject_GetBuffer(data, &view, PyBUF_SIMPLE) < 0)
  3303. return NULL;
  3304. if (view.len > INT_MAX) {
  3305. PyBuffer_Release(&view);
  3306. PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
  3307. return NULL;
  3308. }
  3309. res = expat_parse(st, self, view.buf, (int)view.len, 0);
  3310. PyBuffer_Release(&view);
  3311. return res;
  3312. }
  3313. }
  3314. /*[clinic input]
  3315. _elementtree.XMLParser._parse_whole
  3316. file: object
  3317. /
  3318. [clinic start generated code]*/
  3319. static PyObject *
  3320. _elementtree_XMLParser__parse_whole(XMLParserObject *self, PyObject *file)
  3321. /*[clinic end generated code: output=f797197bb818dda3 input=19ecc893b6f3e752]*/
  3322. {
  3323. /* (internal) parse the whole input, until end of stream */
  3324. PyObject* reader;
  3325. PyObject* buffer;
  3326. PyObject* temp;
  3327. PyObject* res;
  3328. if (!_check_xmlparser(self)) {
  3329. return NULL;
  3330. }
  3331. reader = PyObject_GetAttrString(file, "read");
  3332. if (!reader)
  3333. return NULL;
  3334. /* read from open file object */
  3335. elementtreestate *st = self->state;
  3336. for (;;) {
  3337. buffer = PyObject_CallFunction(reader, "i", 64*1024);
  3338. if (!buffer) {
  3339. /* read failed (e.g. due to KeyboardInterrupt) */
  3340. Py_DECREF(reader);
  3341. return NULL;
  3342. }
  3343. if (PyUnicode_CheckExact(buffer)) {
  3344. /* A unicode object is encoded into bytes using UTF-8 */
  3345. if (PyUnicode_GET_LENGTH(buffer) == 0) {
  3346. Py_DECREF(buffer);
  3347. break;
  3348. }
  3349. temp = PyUnicode_AsEncodedString(buffer, "utf-8", "surrogatepass");
  3350. Py_DECREF(buffer);
  3351. if (!temp) {
  3352. /* Propagate exception from PyUnicode_AsEncodedString */
  3353. Py_DECREF(reader);
  3354. return NULL;
  3355. }
  3356. buffer = temp;
  3357. }
  3358. else if (!PyBytes_CheckExact(buffer) || PyBytes_GET_SIZE(buffer) == 0) {
  3359. Py_DECREF(buffer);
  3360. break;
  3361. }
  3362. if (PyBytes_GET_SIZE(buffer) > INT_MAX) {
  3363. Py_DECREF(buffer);
  3364. Py_DECREF(reader);
  3365. PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
  3366. return NULL;
  3367. }
  3368. res = expat_parse(
  3369. st, self, PyBytes_AS_STRING(buffer), (int)PyBytes_GET_SIZE(buffer),
  3370. 0);
  3371. Py_DECREF(buffer);
  3372. if (!res) {
  3373. Py_DECREF(reader);
  3374. return NULL;
  3375. }
  3376. Py_DECREF(res);
  3377. }
  3378. Py_DECREF(reader);
  3379. res = expat_parse(st, self, "", 0, 1);
  3380. if (res && TreeBuilder_CheckExact(st, self->target)) {
  3381. Py_DECREF(res);
  3382. return treebuilder_done((TreeBuilderObject*) self->target);
  3383. }
  3384. return res;
  3385. }
  3386. /*[clinic input]
  3387. _elementtree.XMLParser._setevents
  3388. events_queue: object
  3389. events_to_report: object = None
  3390. /
  3391. [clinic start generated code]*/
  3392. static PyObject *
  3393. _elementtree_XMLParser__setevents_impl(XMLParserObject *self,
  3394. PyObject *events_queue,
  3395. PyObject *events_to_report)
  3396. /*[clinic end generated code: output=1440092922b13ed1 input=abf90830a1c3b0fc]*/
  3397. {
  3398. /* activate element event reporting */
  3399. Py_ssize_t i;
  3400. TreeBuilderObject *target;
  3401. PyObject *events_append, *events_seq;
  3402. if (!_check_xmlparser(self)) {
  3403. return NULL;
  3404. }
  3405. elementtreestate *st = self->state;
  3406. if (!TreeBuilder_CheckExact(st, self->target)) {
  3407. PyErr_SetString(
  3408. PyExc_TypeError,
  3409. "event handling only supported for ElementTree.TreeBuilder "
  3410. "targets"
  3411. );
  3412. return NULL;
  3413. }
  3414. target = (TreeBuilderObject*) self->target;
  3415. events_append = PyObject_GetAttrString(events_queue, "append");
  3416. if (events_append == NULL)
  3417. return NULL;
  3418. Py_XSETREF(target->events_append, events_append);
  3419. /* clear out existing events */
  3420. Py_CLEAR(target->start_event_obj);
  3421. Py_CLEAR(target->end_event_obj);
  3422. Py_CLEAR(target->start_ns_event_obj);
  3423. Py_CLEAR(target->end_ns_event_obj);
  3424. Py_CLEAR(target->comment_event_obj);
  3425. Py_CLEAR(target->pi_event_obj);
  3426. if (events_to_report == Py_None) {
  3427. /* default is "end" only */
  3428. target->end_event_obj = PyUnicode_FromString("end");
  3429. Py_RETURN_NONE;
  3430. }
  3431. if (!(events_seq = PySequence_Fast(events_to_report,
  3432. "events must be a sequence"))) {
  3433. return NULL;
  3434. }
  3435. for (i = 0; i < PySequence_Fast_GET_SIZE(events_seq); ++i) {
  3436. PyObject *event_name_obj = PySequence_Fast_GET_ITEM(events_seq, i);
  3437. const char *event_name = NULL;
  3438. if (PyUnicode_Check(event_name_obj)) {
  3439. event_name = PyUnicode_AsUTF8(event_name_obj);
  3440. } else if (PyBytes_Check(event_name_obj)) {
  3441. event_name = PyBytes_AS_STRING(event_name_obj);
  3442. }
  3443. if (event_name == NULL) {
  3444. Py_DECREF(events_seq);
  3445. PyErr_Format(PyExc_ValueError, "invalid events sequence");
  3446. return NULL;
  3447. }
  3448. if (strcmp(event_name, "start") == 0) {
  3449. Py_XSETREF(target->start_event_obj, Py_NewRef(event_name_obj));
  3450. } else if (strcmp(event_name, "end") == 0) {
  3451. Py_XSETREF(target->end_event_obj, Py_NewRef(event_name_obj));
  3452. } else if (strcmp(event_name, "start-ns") == 0) {
  3453. Py_XSETREF(target->start_ns_event_obj, Py_NewRef(event_name_obj));
  3454. EXPAT(st, SetNamespaceDeclHandler)(
  3455. self->parser,
  3456. (XML_StartNamespaceDeclHandler) expat_start_ns_handler,
  3457. (XML_EndNamespaceDeclHandler) expat_end_ns_handler
  3458. );
  3459. } else if (strcmp(event_name, "end-ns") == 0) {
  3460. Py_XSETREF(target->end_ns_event_obj, Py_NewRef(event_name_obj));
  3461. EXPAT(st, SetNamespaceDeclHandler)(
  3462. self->parser,
  3463. (XML_StartNamespaceDeclHandler) expat_start_ns_handler,
  3464. (XML_EndNamespaceDeclHandler) expat_end_ns_handler
  3465. );
  3466. } else if (strcmp(event_name, "comment") == 0) {
  3467. Py_XSETREF(target->comment_event_obj, Py_NewRef(event_name_obj));
  3468. EXPAT(st, SetCommentHandler)(
  3469. self->parser,
  3470. (XML_CommentHandler) expat_comment_handler
  3471. );
  3472. } else if (strcmp(event_name, "pi") == 0) {
  3473. Py_XSETREF(target->pi_event_obj, Py_NewRef(event_name_obj));
  3474. EXPAT(st, SetProcessingInstructionHandler)(
  3475. self->parser,
  3476. (XML_ProcessingInstructionHandler) expat_pi_handler
  3477. );
  3478. } else {
  3479. Py_DECREF(events_seq);
  3480. PyErr_Format(PyExc_ValueError, "unknown event '%s'", event_name);
  3481. return NULL;
  3482. }
  3483. }
  3484. Py_DECREF(events_seq);
  3485. Py_RETURN_NONE;
  3486. }
  3487. static PyMemberDef xmlparser_members[] = {
  3488. {"entity", T_OBJECT, offsetof(XMLParserObject, entity), READONLY, NULL},
  3489. {"target", T_OBJECT, offsetof(XMLParserObject, target), READONLY, NULL},
  3490. {NULL}
  3491. };
  3492. static PyObject*
  3493. xmlparser_version_getter(XMLParserObject *self, void *closure)
  3494. {
  3495. return PyUnicode_FromFormat(
  3496. "Expat %d.%d.%d", XML_MAJOR_VERSION,
  3497. XML_MINOR_VERSION, XML_MICRO_VERSION);
  3498. }
  3499. static PyGetSetDef xmlparser_getsetlist[] = {
  3500. {"version", (getter)xmlparser_version_getter, NULL, NULL},
  3501. {NULL},
  3502. };
  3503. #define clinic_state() (get_elementtree_state_by_type(Py_TYPE(self)))
  3504. #include "clinic/_elementtree.c.h"
  3505. #undef clinic_state
  3506. static PyMethodDef element_methods[] = {
  3507. _ELEMENTTREE_ELEMENT_CLEAR_METHODDEF
  3508. _ELEMENTTREE_ELEMENT_GET_METHODDEF
  3509. _ELEMENTTREE_ELEMENT_SET_METHODDEF
  3510. _ELEMENTTREE_ELEMENT_FIND_METHODDEF
  3511. _ELEMENTTREE_ELEMENT_FINDTEXT_METHODDEF
  3512. _ELEMENTTREE_ELEMENT_FINDALL_METHODDEF
  3513. _ELEMENTTREE_ELEMENT_APPEND_METHODDEF
  3514. _ELEMENTTREE_ELEMENT_EXTEND_METHODDEF
  3515. _ELEMENTTREE_ELEMENT_INSERT_METHODDEF
  3516. _ELEMENTTREE_ELEMENT_REMOVE_METHODDEF
  3517. _ELEMENTTREE_ELEMENT_ITER_METHODDEF
  3518. _ELEMENTTREE_ELEMENT_ITERTEXT_METHODDEF
  3519. _ELEMENTTREE_ELEMENT_ITERFIND_METHODDEF
  3520. _ELEMENTTREE_ELEMENT_ITEMS_METHODDEF
  3521. _ELEMENTTREE_ELEMENT_KEYS_METHODDEF
  3522. _ELEMENTTREE_ELEMENT_MAKEELEMENT_METHODDEF
  3523. _ELEMENTTREE_ELEMENT___COPY___METHODDEF
  3524. _ELEMENTTREE_ELEMENT___DEEPCOPY___METHODDEF
  3525. _ELEMENTTREE_ELEMENT___SIZEOF___METHODDEF
  3526. _ELEMENTTREE_ELEMENT___GETSTATE___METHODDEF
  3527. _ELEMENTTREE_ELEMENT___SETSTATE___METHODDEF
  3528. {NULL, NULL}
  3529. };
  3530. static struct PyMemberDef element_members[] = {
  3531. {"__weaklistoffset__", T_PYSSIZET, offsetof(ElementObject, weakreflist), READONLY},
  3532. {NULL},
  3533. };
  3534. static PyGetSetDef element_getsetlist[] = {
  3535. {"tag",
  3536. (getter)element_tag_getter,
  3537. (setter)element_tag_setter,
  3538. "A string identifying what kind of data this element represents"},
  3539. {"text",
  3540. (getter)element_text_getter,
  3541. (setter)element_text_setter,
  3542. "A string of text directly after the start tag, or None"},
  3543. {"tail",
  3544. (getter)element_tail_getter,
  3545. (setter)element_tail_setter,
  3546. "A string of text directly after the end tag, or None"},
  3547. {"attrib",
  3548. (getter)element_attrib_getter,
  3549. (setter)element_attrib_setter,
  3550. "A dictionary containing the element's attributes"},
  3551. {NULL},
  3552. };
  3553. static PyType_Slot element_slots[] = {
  3554. {Py_tp_dealloc, element_dealloc},
  3555. {Py_tp_repr, element_repr},
  3556. {Py_tp_getattro, PyObject_GenericGetAttr},
  3557. {Py_tp_traverse, element_gc_traverse},
  3558. {Py_tp_clear, element_gc_clear},
  3559. {Py_tp_methods, element_methods},
  3560. {Py_tp_members, element_members},
  3561. {Py_tp_getset, element_getsetlist},
  3562. {Py_tp_init, element_init},
  3563. {Py_tp_alloc, PyType_GenericAlloc},
  3564. {Py_tp_new, element_new},
  3565. {Py_sq_length, element_length},
  3566. {Py_sq_item, element_getitem},
  3567. {Py_sq_ass_item, element_setitem},
  3568. {Py_nb_bool, element_bool},
  3569. {Py_mp_length, element_length},
  3570. {Py_mp_subscript, element_subscr},
  3571. {Py_mp_ass_subscript, element_ass_subscr},
  3572. {0, NULL},
  3573. };
  3574. static PyType_Spec element_spec = {
  3575. .name = "xml.etree.ElementTree.Element",
  3576. .basicsize = sizeof(ElementObject),
  3577. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  3578. Py_TPFLAGS_IMMUTABLETYPE),
  3579. .slots = element_slots,
  3580. };
  3581. static PyMethodDef treebuilder_methods[] = {
  3582. _ELEMENTTREE_TREEBUILDER_DATA_METHODDEF
  3583. _ELEMENTTREE_TREEBUILDER_START_METHODDEF
  3584. _ELEMENTTREE_TREEBUILDER_END_METHODDEF
  3585. _ELEMENTTREE_TREEBUILDER_COMMENT_METHODDEF
  3586. _ELEMENTTREE_TREEBUILDER_PI_METHODDEF
  3587. _ELEMENTTREE_TREEBUILDER_CLOSE_METHODDEF
  3588. {NULL, NULL}
  3589. };
  3590. static PyType_Slot treebuilder_slots[] = {
  3591. {Py_tp_dealloc, treebuilder_dealloc},
  3592. {Py_tp_traverse, treebuilder_gc_traverse},
  3593. {Py_tp_clear, treebuilder_gc_clear},
  3594. {Py_tp_methods, treebuilder_methods},
  3595. {Py_tp_init, _elementtree_TreeBuilder___init__},
  3596. {Py_tp_alloc, PyType_GenericAlloc},
  3597. {Py_tp_new, treebuilder_new},
  3598. {0, NULL},
  3599. };
  3600. static PyType_Spec treebuilder_spec = {
  3601. .name = "xml.etree.ElementTree.TreeBuilder",
  3602. .basicsize = sizeof(TreeBuilderObject),
  3603. .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE,
  3604. .slots = treebuilder_slots,
  3605. };
  3606. static PyMethodDef xmlparser_methods[] = {
  3607. _ELEMENTTREE_XMLPARSER_FEED_METHODDEF
  3608. _ELEMENTTREE_XMLPARSER_CLOSE_METHODDEF
  3609. _ELEMENTTREE_XMLPARSER__PARSE_WHOLE_METHODDEF
  3610. _ELEMENTTREE_XMLPARSER__SETEVENTS_METHODDEF
  3611. {NULL, NULL}
  3612. };
  3613. static PyType_Slot xmlparser_slots[] = {
  3614. {Py_tp_dealloc, xmlparser_dealloc},
  3615. {Py_tp_traverse, xmlparser_gc_traverse},
  3616. {Py_tp_clear, xmlparser_gc_clear},
  3617. {Py_tp_methods, xmlparser_methods},
  3618. {Py_tp_members, xmlparser_members},
  3619. {Py_tp_getset, xmlparser_getsetlist},
  3620. {Py_tp_init, _elementtree_XMLParser___init__},
  3621. {Py_tp_alloc, PyType_GenericAlloc},
  3622. {Py_tp_new, xmlparser_new},
  3623. {0, NULL},
  3624. };
  3625. static PyType_Spec xmlparser_spec = {
  3626. .name = "xml.etree.ElementTree.XMLParser",
  3627. .basicsize = sizeof(XMLParserObject),
  3628. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  3629. Py_TPFLAGS_IMMUTABLETYPE),
  3630. .slots = xmlparser_slots,
  3631. };
  3632. /* ==================================================================== */
  3633. /* python module interface */
  3634. static PyMethodDef _functions[] = {
  3635. {"SubElement", _PyCFunction_CAST(subelement), METH_VARARGS | METH_KEYWORDS},
  3636. _ELEMENTTREE__SET_FACTORIES_METHODDEF
  3637. {NULL, NULL}
  3638. };
  3639. #define CREATE_TYPE(module, type, spec) \
  3640. do { \
  3641. if (type != NULL) { \
  3642. break; \
  3643. } \
  3644. type = (PyTypeObject *)PyType_FromModuleAndSpec(module, spec, NULL); \
  3645. if (type == NULL) { \
  3646. goto error; \
  3647. } \
  3648. } while (0)
  3649. static int
  3650. module_exec(PyObject *m)
  3651. {
  3652. elementtreestate *st = get_elementtree_state(m);
  3653. /* Initialize object types */
  3654. CREATE_TYPE(m, st->ElementIter_Type, &elementiter_spec);
  3655. CREATE_TYPE(m, st->TreeBuilder_Type, &treebuilder_spec);
  3656. CREATE_TYPE(m, st->Element_Type, &element_spec);
  3657. CREATE_TYPE(m, st->XMLParser_Type, &xmlparser_spec);
  3658. st->deepcopy_obj = _PyImport_GetModuleAttrString("copy", "deepcopy");
  3659. if (st->deepcopy_obj == NULL) {
  3660. goto error;
  3661. }
  3662. assert(!PyErr_Occurred());
  3663. if (!(st->elementpath_obj = PyImport_ImportModule("xml.etree.ElementPath")))
  3664. goto error;
  3665. /* link against pyexpat */
  3666. if (!(st->expat_capsule = _PyImport_GetModuleAttrString("pyexpat", "expat_CAPI")))
  3667. goto error;
  3668. if (!(st->expat_capi = PyCapsule_GetPointer(st->expat_capsule, PyExpat_CAPSULE_NAME)))
  3669. goto error;
  3670. if (st->expat_capi) {
  3671. /* check that it's usable */
  3672. if (strcmp(st->expat_capi->magic, PyExpat_CAPI_MAGIC) != 0 ||
  3673. (size_t)st->expat_capi->size < sizeof(struct PyExpat_CAPI) ||
  3674. st->expat_capi->MAJOR_VERSION != XML_MAJOR_VERSION ||
  3675. st->expat_capi->MINOR_VERSION != XML_MINOR_VERSION ||
  3676. st->expat_capi->MICRO_VERSION != XML_MICRO_VERSION) {
  3677. PyErr_SetString(PyExc_ImportError,
  3678. "pyexpat version is incompatible");
  3679. goto error;
  3680. }
  3681. } else {
  3682. goto error;
  3683. }
  3684. st->str_append = PyUnicode_InternFromString("append");
  3685. if (st->str_append == NULL) {
  3686. goto error;
  3687. }
  3688. st->str_find = PyUnicode_InternFromString("find");
  3689. if (st->str_find == NULL) {
  3690. goto error;
  3691. }
  3692. st->str_findall = PyUnicode_InternFromString("findall");
  3693. if (st->str_findall == NULL) {
  3694. goto error;
  3695. }
  3696. st->str_findtext = PyUnicode_InternFromString("findtext");
  3697. if (st->str_findtext == NULL) {
  3698. goto error;
  3699. }
  3700. st->str_iterfind = PyUnicode_InternFromString("iterfind");
  3701. if (st->str_iterfind == NULL) {
  3702. goto error;
  3703. }
  3704. st->str_tail = PyUnicode_InternFromString("tail");
  3705. if (st->str_tail == NULL) {
  3706. goto error;
  3707. }
  3708. st->str_text = PyUnicode_InternFromString("text");
  3709. if (st->str_text == NULL) {
  3710. goto error;
  3711. }
  3712. st->str_doctype = PyUnicode_InternFromString("doctype");
  3713. if (st->str_doctype == NULL) {
  3714. goto error;
  3715. }
  3716. st->parseerror_obj = PyErr_NewException(
  3717. "xml.etree.ElementTree.ParseError", PyExc_SyntaxError, NULL
  3718. );
  3719. if (PyModule_AddObjectRef(m, "ParseError", st->parseerror_obj) < 0) {
  3720. goto error;
  3721. }
  3722. PyTypeObject *types[] = {
  3723. st->Element_Type,
  3724. st->TreeBuilder_Type,
  3725. st->XMLParser_Type
  3726. };
  3727. for (size_t i = 0; i < Py_ARRAY_LENGTH(types); i++) {
  3728. if (PyModule_AddType(m, types[i]) < 0) {
  3729. goto error;
  3730. }
  3731. }
  3732. return 0;
  3733. error:
  3734. return -1;
  3735. }
  3736. static struct PyModuleDef_Slot elementtree_slots[] = {
  3737. {Py_mod_exec, module_exec},
  3738. // XXX gh-103092: fix isolation.
  3739. {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},
  3740. //{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  3741. {0, NULL},
  3742. };
  3743. static struct PyModuleDef elementtreemodule = {
  3744. .m_base = PyModuleDef_HEAD_INIT,
  3745. .m_name = "_elementtree",
  3746. .m_size = sizeof(elementtreestate),
  3747. .m_methods = _functions,
  3748. .m_slots = elementtree_slots,
  3749. .m_traverse = elementtree_traverse,
  3750. .m_clear = elementtree_clear,
  3751. .m_free = elementtree_free,
  3752. };
  3753. PyMODINIT_FUNC
  3754. PyInit__elementtree(void)
  3755. {
  3756. return PyModuleDef_Init(&elementtreemodule);
  3757. }