PikaVM.c 160 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011
  1. /*
  2. * This file is part of the PikaPython project.
  3. * http://github.com/pikastech/pikapython
  4. *
  5. * MIT License
  6. *
  7. * Copyright (c) 2021 lyon liang6516@outlook.com
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a
  10. * copy of this software and associated documentation files (the "Software"),
  11. * to deal in the Software without restriction, including without limitation
  12. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  13. * and/or sell copies of the Software, and to permit persons to whom the
  14. * Software is furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  22. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  24. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  25. * DEALINGS IN THE SOFTWARE.
  26. */
  27. #include "PikaVM.h"
  28. #include "BaseObj.h"
  29. #include "PikaCompiler.h"
  30. #include "PikaObj.h"
  31. #include "PikaParser.h"
  32. #include "PikaPlatform.h"
  33. #include "dataArg.h"
  34. #include "dataStrs.h"
  35. #if PIKA_MATH_ENABLE
  36. #include <math.h>
  37. #endif
  38. static pika_thread_recursive_mutex_t g_pikaGIL = {0};
  39. volatile VMState g_PikaVMState = {
  40. .signal_ctrl = VM_SIGNAL_CTRL_NONE,
  41. .vm_cnt = 0,
  42. #if PIKA_EVENT_ENABLE
  43. .cq =
  44. {
  45. .head = 0,
  46. .tail = 0,
  47. .res = {0},
  48. },
  49. .sq =
  50. {
  51. .head = 0,
  52. .tail = 0,
  53. .res = {0},
  54. },
  55. .event_pickup_cnt = 0,
  56. .event_thread = NULL,
  57. .event_thread_exit = pika_false,
  58. #endif
  59. #if PIKA_DEBUG_BREAK_POINT_MAX > 0
  60. .break_module_hash = {0},
  61. .break_point_pc = {0},
  62. .break_point_cnt = 0,
  63. #endif
  64. };
  65. extern volatile PikaObjState g_PikaObjState;
  66. /* private */
  67. static pika_bool _checkLReg(char* data);
  68. static uint8_t _getLRegIndex(char* data);
  69. static PikaObj* New_Locals(Args* args);
  70. char* string_slice(Args* outBuffs, char* str, int start, int end);
  71. pika_bool pika_GIL_isInit(void) {
  72. return g_pikaGIL.mutex.is_init;
  73. }
  74. int pika_GIL_ENTER(void) {
  75. if (!g_pikaGIL.mutex.is_init) {
  76. if (g_pikaGIL.mutex.bare_lock > 0) {
  77. return -1;
  78. }
  79. g_pikaGIL.mutex.bare_lock = 1;
  80. return 0;
  81. }
  82. int ret = pika_thread_recursive_mutex_lock(&g_pikaGIL);
  83. // pika_debug("pika_GIL_ENTER");
  84. if (!g_pikaGIL.mutex.is_first_lock) {
  85. g_pikaGIL.mutex.is_first_lock = 1;
  86. }
  87. return ret;
  88. }
  89. int pika_GIL_getBareLock(void) {
  90. return g_pikaGIL.mutex.bare_lock;
  91. }
  92. int pika_GIL_EXIT(void) {
  93. if (!g_pikaGIL.mutex.is_first_lock || !g_pikaGIL.mutex.is_init) {
  94. g_pikaGIL.mutex.bare_lock = 0;
  95. return 0;
  96. }
  97. return pika_thread_recursive_mutex_unlock(&g_pikaGIL);
  98. }
  99. int pika_GIL_deinit(void) {
  100. pika_platform_memset(&g_pikaGIL, 0, sizeof(g_pikaGIL));
  101. return 0;
  102. }
  103. int _VM_lock_init(void) {
  104. if (g_pikaGIL.mutex.is_init) {
  105. return 0;
  106. }
  107. int ret = pika_thread_recursive_mutex_init(&g_pikaGIL);
  108. if (0 == ret) {
  109. g_pikaGIL.mutex.is_init = 1;
  110. }
  111. return ret;
  112. }
  113. int _VM_is_first_lock(void) {
  114. return g_pikaGIL.mutex.is_first_lock;
  115. }
  116. int _VMEvent_getVMCnt(void) {
  117. return g_PikaVMState.vm_cnt;
  118. }
  119. int _VMEvent_getEventPickupCnt(void) {
  120. #if !PIKA_EVENT_ENABLE
  121. return -1;
  122. #else
  123. return g_PikaVMState.event_pickup_cnt;
  124. #endif
  125. }
  126. #if PIKA_EVENT_ENABLE
  127. static pika_bool _ecq_isEmpty(volatile PikaEventQueue* cq) {
  128. return (pika_bool)(cq->head == cq->tail);
  129. }
  130. static pika_bool _ecq_isFull(volatile PikaEventQueue* cq) {
  131. return (pika_bool)((cq->tail + 1) % PIKA_EVENT_LIST_SIZE == cq->head);
  132. }
  133. #endif
  134. #if PIKA_SETJMP_ENABLE
  135. static pika_bool _jcq_isEmpty(volatile JmpBufCQ* cq) {
  136. return (pika_bool)(cq->head == cq->tail);
  137. }
  138. static pika_bool _jcq_isFull(volatile JmpBufCQ* cq) {
  139. return (pika_bool)((cq->tail + 1) % PIKA_JMP_BUF_LIST_SIZE == cq->head);
  140. }
  141. static jmp_buf* _jcq_pop(volatile JmpBufCQ* cq) {
  142. if (_jcq_isEmpty(cq)) {
  143. return NULL;
  144. }
  145. jmp_buf* buf = cq->buf[cq->head];
  146. cq->head = (cq->head + 1) % PIKA_JMP_BUF_LIST_SIZE;
  147. return buf;
  148. }
  149. static jmp_buf* _jcq_check_pop(volatile JmpBufCQ* cq) {
  150. if (_jcq_isEmpty(cq)) {
  151. return NULL;
  152. }
  153. return cq->buf[cq->head];
  154. }
  155. static PIKA_RES _jcq_push(volatile JmpBufCQ* cq, jmp_buf* pos) {
  156. if (_jcq_isFull(cq)) {
  157. return -1;
  158. }
  159. cq->buf[cq->tail] = pos;
  160. cq->tail = (cq->tail + 1) % PIKA_JMP_BUF_LIST_SIZE;
  161. return PIKA_RES_OK;
  162. }
  163. static PIKA_RES _jcq_remove(volatile JmpBufCQ* cq, jmp_buf* pos) {
  164. if (_jcq_isEmpty(cq)) {
  165. return -1;
  166. }
  167. for (int i = cq->head; i != cq->tail;
  168. i = (i + 1) % PIKA_JMP_BUF_LIST_SIZE) {
  169. if (cq->buf[i] == pos) {
  170. /* move */
  171. for (int j = i; j != cq->tail;
  172. j = (j + 1) % PIKA_JMP_BUF_LIST_SIZE) {
  173. cq->buf[j] = cq->buf[(j + 1) % PIKA_JMP_BUF_LIST_SIZE];
  174. }
  175. cq->tail = (cq->tail - 1) % PIKA_JMP_BUF_LIST_SIZE;
  176. return PIKA_RES_OK;
  177. }
  178. }
  179. return -1;
  180. }
  181. #endif
  182. void _VMEvent_deinit(void) {
  183. #if !PIKA_EVENT_ENABLE
  184. pika_platform_printf("PIKA_EVENT_ENABLE is not enable");
  185. pika_platform_panic_handle();
  186. #else
  187. for (int i = 0; i < PIKA_EVENT_LIST_SIZE; i++) {
  188. if (NULL != g_PikaVMState.cq.res[i]) {
  189. arg_deinit(g_PikaVMState.cq.res[i]);
  190. g_PikaVMState.cq.res[i] = NULL;
  191. }
  192. if (NULL != g_PikaVMState.cq.data[i].arg) {
  193. arg_deinit(g_PikaVMState.cq.data[i].arg);
  194. g_PikaVMState.cq.data[i].arg = NULL;
  195. }
  196. if (NULL != g_PikaVMState.sq.res[i]) {
  197. arg_deinit(g_PikaVMState.sq.res[i]);
  198. g_PikaVMState.sq.res[i] = NULL;
  199. }
  200. g_PikaVMState.cq.id[i] = 0;
  201. g_PikaVMState.cq.data[i].arg = NULL;
  202. g_PikaVMState.cq.listener[i] = NULL;
  203. g_PikaVMState.sq.id[i] = 0;
  204. g_PikaVMState.sq.data[i].signal = 0;
  205. g_PikaVMState.sq.listener[i] = NULL;
  206. }
  207. g_PikaVMState.cq.head = 0;
  208. g_PikaVMState.cq.tail = 0;
  209. g_PikaVMState.sq.head = 0;
  210. g_PikaVMState.sq.tail = 0;
  211. if (NULL != g_PikaVMState.event_thread) {
  212. g_PikaVMState.event_thread_exit = 1;
  213. pika_platform_thread_destroy(g_PikaVMState.event_thread);
  214. g_PikaVMState.event_thread = NULL;
  215. pika_GIL_EXIT();
  216. while (!g_PikaVMState.event_thread_exit_done) {
  217. pika_platform_thread_yield();
  218. }
  219. g_PikaVMState.event_thread_exit = 0;
  220. g_PikaVMState.event_thread_exit_done = 0;
  221. pika_GIL_ENTER();
  222. }
  223. #endif
  224. }
  225. PIKA_RES __eventListener_pushEvent(PikaEventListener* lisener,
  226. uintptr_t eventId,
  227. Arg* eventData) {
  228. #if !PIKA_EVENT_ENABLE
  229. pika_platform_printf("PIKA_EVENT_ENABLE is not enable");
  230. pika_platform_panic_handle();
  231. return PIKA_RES_ERR_OPERATION_FAILED;
  232. #else
  233. if (arg_getType(eventData) == ARG_TYPE_OBJECT_NEW) {
  234. arg_setType(eventData, ARG_TYPE_OBJECT);
  235. }
  236. /* push to event_cq_buff */
  237. if (_ecq_isFull(&g_PikaVMState.cq)) {
  238. // pika_debug("event_cq_buff is full");
  239. arg_deinit(eventData);
  240. return PIKA_RES_ERR_SIGNAL_EVENT_FULL;
  241. }
  242. if (g_PikaVMState.cq.res[g_PikaVMState.cq.tail] != NULL) {
  243. arg_deinit(g_PikaVMState.cq.res[g_PikaVMState.cq.tail]);
  244. g_PikaVMState.cq.res[g_PikaVMState.cq.tail] = NULL;
  245. }
  246. if (g_PikaVMState.cq.data[g_PikaVMState.cq.tail].arg != NULL) {
  247. arg_deinit(g_PikaVMState.cq.data[g_PikaVMState.cq.tail].arg);
  248. g_PikaVMState.cq.data[g_PikaVMState.cq.tail].arg = NULL;
  249. }
  250. g_PikaVMState.cq.id[g_PikaVMState.cq.tail] = eventId;
  251. g_PikaVMState.cq.data[g_PikaVMState.cq.tail].arg = eventData;
  252. g_PikaVMState.cq.listener[g_PikaVMState.cq.tail] = lisener;
  253. g_PikaVMState.cq.tail = (g_PikaVMState.cq.tail + 1) % PIKA_EVENT_LIST_SIZE;
  254. return PIKA_RES_OK;
  255. #endif
  256. }
  257. PIKA_RES __eventListener_pushSignal(PikaEventListener* lisener,
  258. uintptr_t eventId,
  259. int signal) {
  260. #if !PIKA_EVENT_ENABLE
  261. pika_platform_printf("PIKA_EVENT_ENABLE is not enable");
  262. pika_platform_panic_handle();
  263. return PIKA_RES_ERR_OPERATION_FAILED;
  264. #else
  265. /* push to event_cq_buff */
  266. if (_ecq_isFull(&g_PikaVMState.sq)) {
  267. // pika_debug("event_cq_buff is full");
  268. return PIKA_RES_ERR_SIGNAL_EVENT_FULL;
  269. }
  270. g_PikaVMState.sq.id[g_PikaVMState.sq.tail] = eventId;
  271. g_PikaVMState.sq.data[g_PikaVMState.sq.tail].signal = signal;
  272. g_PikaVMState.sq.listener[g_PikaVMState.sq.tail] = lisener;
  273. g_PikaVMState.sq.tail = (g_PikaVMState.sq.tail + 1) % PIKA_EVENT_LIST_SIZE;
  274. if (_VM_is_first_lock()) {
  275. pika_GIL_ENTER();
  276. if (g_PikaVMState.sq.res[g_PikaVMState.sq.tail] != NULL) {
  277. arg_deinit(g_PikaVMState.sq.res[g_PikaVMState.sq.tail]);
  278. g_PikaVMState.sq.res[g_PikaVMState.sq.tail] = NULL;
  279. }
  280. pika_GIL_EXIT();
  281. }
  282. return PIKA_RES_OK;
  283. #endif
  284. }
  285. PIKA_RES __eventListener_popEvent(PikaEventListener** lisener_p,
  286. uintptr_t* id,
  287. Arg** data,
  288. int* signal,
  289. int* head) {
  290. #if !PIKA_EVENT_ENABLE
  291. pika_platform_printf("PIKA_EVENT_ENABLE is not enable");
  292. pika_platform_panic_handle();
  293. return PIKA_RES_ERR_OPERATION_FAILED;
  294. #else
  295. PikaEventQueue* cq = NULL;
  296. /* pop from event_cq_buff */
  297. if (!_ecq_isEmpty(&g_PikaVMState.cq)) {
  298. cq = (PikaEventQueue*)&g_PikaVMState.cq;
  299. } else if (!_ecq_isEmpty(&g_PikaVMState.sq)) {
  300. cq = (PikaEventQueue*)&g_PikaVMState.sq;
  301. }
  302. if (NULL == cq) {
  303. return PIKA_RES_ERR_SIGNAL_EVENT_EMPTY;
  304. }
  305. *id = cq->id[g_PikaVMState.cq.head];
  306. if (cq == &g_PikaVMState.cq) {
  307. *data = cq->data[g_PikaVMState.cq.head].arg;
  308. } else {
  309. *signal = cq->data[g_PikaVMState.cq.head].signal;
  310. *data = NULL;
  311. }
  312. *lisener_p = cq->listener[g_PikaVMState.cq.head];
  313. *head = cq->head;
  314. cq->head = (cq->head + 1) % PIKA_EVENT_LIST_SIZE;
  315. return PIKA_RES_OK;
  316. #endif
  317. }
  318. PIKA_RES __eventListener_popSignalEvent(PikaEventListener** lisener_p,
  319. uintptr_t* id,
  320. int* signal,
  321. int* head) {
  322. #if !PIKA_EVENT_ENABLE
  323. pika_platform_printf("PIKA_EVENT_ENABLE is not enable");
  324. pika_platform_panic_handle();
  325. return PIKA_RES_ERR_OPERATION_FAILED;
  326. #else
  327. /* pop from event_cq_buff */
  328. if (_ecq_isEmpty(&g_PikaVMState.sq)) {
  329. return PIKA_RES_ERR_SIGNAL_EVENT_EMPTY;
  330. }
  331. *id = g_PikaVMState.sq.id[g_PikaVMState.sq.head];
  332. *signal = g_PikaVMState.sq.data[g_PikaVMState.sq.head].signal;
  333. *lisener_p = g_PikaVMState.sq.listener[g_PikaVMState.sq.head];
  334. *head = g_PikaVMState.sq.head;
  335. g_PikaVMState.sq.head = (g_PikaVMState.sq.head + 1) % PIKA_EVENT_LIST_SIZE;
  336. return PIKA_RES_OK;
  337. #endif
  338. }
  339. void __VMEvent_pickupEvent(char* info) {
  340. #if !PIKA_EVENT_ENABLE
  341. pika_platform_printf("PIKA_EVENT_ENABLE is not enable\r\n");
  342. pika_platform_panic_handle();
  343. #else
  344. int evt_pickup_cnt = _VMEvent_getEventPickupCnt();
  345. if (evt_pickup_cnt >= PIKA_EVENT_PICKUP_MAX) {
  346. return;
  347. }
  348. PikaObj* event_listener;
  349. uintptr_t event_id;
  350. Arg* event_data;
  351. int signal;
  352. int head;
  353. if (PIKA_RES_OK == __eventListener_popEvent(&event_listener, &event_id,
  354. &event_data, &signal, &head)) {
  355. g_PikaVMState.event_pickup_cnt++;
  356. pika_debug("pickup_info: %s", info);
  357. pika_debug("pickup_cnt: %d", g_PikaVMState.event_pickup_cnt);
  358. Arg* res = NULL;
  359. if (NULL != event_data) {
  360. res =
  361. __eventListener_runEvent(event_listener, event_id, event_data);
  362. } else {
  363. event_data = arg_newInt(signal);
  364. res =
  365. __eventListener_runEvent(event_listener, event_id, event_data);
  366. arg_deinit(event_data);
  367. event_data = NULL;
  368. }
  369. // only on muti thread, keep the res
  370. if (_VM_is_first_lock()) {
  371. if (NULL == event_data) {
  372. // from signal
  373. g_PikaVMState.sq.res[head] = res;
  374. } else {
  375. // from event
  376. g_PikaVMState.cq.res[head] = res;
  377. }
  378. } else {
  379. if (NULL != res) {
  380. arg_deinit(res);
  381. }
  382. }
  383. g_PikaVMState.event_pickup_cnt--;
  384. }
  385. #endif
  386. }
  387. VM_SIGNAL_CTRL VMSignal_getCtrl(void) {
  388. return g_PikaVMState.signal_ctrl;
  389. }
  390. void pika_vm_exit(void) {
  391. g_PikaVMState.signal_ctrl = VM_SIGNAL_CTRL_EXIT;
  392. }
  393. void pika_vm_exit_await(void) {
  394. pika_vm_exit();
  395. while (1) {
  396. pika_platform_thread_yield();
  397. if (_VMEvent_getVMCnt() == 0) {
  398. return;
  399. }
  400. }
  401. }
  402. void pika_vmSignal_setCtrlClear(void) {
  403. g_PikaVMState.signal_ctrl = VM_SIGNAL_CTRL_NONE;
  404. }
  405. /* head declare start */
  406. static uint32_t PikaVMFrame_getInputArgNum(PikaVMFrame* vm);
  407. static VMParameters* __pikaVM_runByteCodeFrameWithState(
  408. PikaObj* self,
  409. VMParameters* locals,
  410. VMParameters* globals,
  411. ByteCodeFrame* bytecode_frame,
  412. uint16_t pc,
  413. PikaVMThread* vm_thread,
  414. pika_bool in_repl);
  415. static VMParameters* _pikaVM_runByteCodeFrameWithState(
  416. PikaObj* self,
  417. VMParameters* locals,
  418. VMParameters* globals,
  419. ByteCodeFrame* bytecode_frame,
  420. uint16_t pc,
  421. PikaVMThread* vm_thread);
  422. /* head declare end */
  423. static void PikaVMFrame_setErrorCode(PikaVMFrame* vm, int8_t error_code) {
  424. vm->error.code = error_code;
  425. }
  426. void _do_vsysOut(char* fmt, va_list args);
  427. void PikaVMFrame_setSysOut(PikaVMFrame* vm, char* fmt, ...) {
  428. pika_assert(NULL != vm);
  429. if (vm->error.code == PIKA_RES_OK) {
  430. vm->error.code = PIKA_RES_ERR_RUNTIME_ERROR;
  431. }
  432. if (vm->vm_thread->try_state == TRY_STATE_INNER) {
  433. return;
  434. }
  435. va_list args;
  436. va_start(args, fmt);
  437. _do_vsysOut(fmt, args);
  438. va_end(args);
  439. }
  440. static enum InstructIndex PikaVMFrame_getInstructWithOffset(PikaVMFrame* vm,
  441. int32_t offset) {
  442. return instructUnit_getInstructIndex(
  443. PikaVMFrame_getInstructUnitWithOffset(vm, offset));
  444. }
  445. static int PikaVMFrame_getBlockDeepthNow(PikaVMFrame* vm) {
  446. /* support run byteCode */
  447. InstructUnit* ins_unit = PikaVMFrame_getInstructNow(vm);
  448. return instructUnit_getBlockDeepth(ins_unit);
  449. }
  450. #if !PIKA_NANO_ENABLE
  451. static char* PikaVMFrame_getConstWithOffset(PikaVMFrame* vm, int32_t offset) {
  452. return PikaVMFrame_getConstWithInstructUnit(
  453. vm, PikaVMFrame_getInstructUnitWithOffset(vm, offset));
  454. }
  455. #endif
  456. static int PikaVMFrame_getInvokeDeepthNow(PikaVMFrame* vm) {
  457. /* support run byteCode */
  458. InstructUnit* ins_unit = PikaVMFrame_getInstructNow(vm);
  459. return instructUnit_getInvokeDeepth(ins_unit);
  460. }
  461. pika_bool PikaVMFrame_checkBreakPoint(PikaVMFrame* vm) {
  462. #if !PIKA_DEBUG_BREAK_POINT_MAX
  463. return pika_false;
  464. #else
  465. if (g_PikaVMState.break_point_cnt == 0) {
  466. return pika_false;
  467. }
  468. if (NULL == vm->bytecode_frame->name) {
  469. return pika_false;
  470. }
  471. Hash module_hash = byteCodeFrame_getNameHash(vm->bytecode_frame);
  472. return pika_debug_check_break_hash(module_hash, vm->pc);
  473. #endif
  474. }
  475. static int32_t PikaVMFrame_getAddrOffsetOfJmpBack(PikaVMFrame* vm) {
  476. int offset = 0;
  477. int blockDeepthGot = -1;
  478. int blockDeepthNow = PikaVMFrame_getBlockDeepthNow(vm);
  479. /* find loop deepth */
  480. while (1) {
  481. offset -= instructUnit_getSize();
  482. InstructUnit* insUnitThis =
  483. PikaVMFrame_getInstructUnitWithOffset(vm, offset);
  484. uint16_t invokeDeepth = instructUnit_getInvokeDeepth(insUnitThis);
  485. enum InstructIndex ins = instructUnit_getInstructIndex(insUnitThis);
  486. char* data = PikaVMFrame_getConstWithInstructUnit(vm, insUnitThis);
  487. if ((0 == invokeDeepth) && (PIKA_INS(JEZ) == ins) && data[0] == '2') {
  488. InstructUnit* insUnitLast = PikaVMFrame_getInstructUnitWithOffset(
  489. vm, offset - instructUnit_getSize());
  490. enum InstructIndex insLast =
  491. instructUnit_getInstructIndex(insUnitLast);
  492. /* skip try stmt */
  493. if (PIKA_INS(GER) == insLast) {
  494. continue;
  495. }
  496. /* skip inner break */
  497. int blockDeepthThis = instructUnit_getBlockDeepth(insUnitThis);
  498. if (blockDeepthThis >= blockDeepthNow) {
  499. continue;
  500. }
  501. blockDeepthGot = instructUnit_getBlockDeepth(insUnitThis);
  502. break;
  503. }
  504. }
  505. offset = 0;
  506. while (1) {
  507. offset += instructUnit_getSize();
  508. InstructUnit* insUnitThis =
  509. PikaVMFrame_getInstructUnitWithOffset(vm, offset);
  510. enum InstructIndex ins = instructUnit_getInstructIndex(insUnitThis);
  511. char* data = PikaVMFrame_getConstWithInstructUnit(vm, insUnitThis);
  512. int blockDeepthThis = instructUnit_getBlockDeepth(insUnitThis);
  513. if ((blockDeepthThis == blockDeepthGot) && (PIKA_INS(JMP) == ins) &&
  514. data[0] == '-' && data[1] == '1') {
  515. return offset;
  516. }
  517. }
  518. }
  519. static int32_t PikaVMFrame_getAddrOffsetFromJmp(PikaVMFrame* vm) {
  520. int offset = 0;
  521. /* run byte Code */
  522. InstructUnit* this_ins_unit = PikaVMFrame_getInstructNow(vm);
  523. int thisBlockDeepth = instructUnit_getBlockDeepth(this_ins_unit);
  524. int8_t blockNum = 0;
  525. int pc_max = (int)PikaVMFrame_getInstructArraySize(vm);
  526. if (vm->jmp > 0) {
  527. offset = 0;
  528. while (1) {
  529. offset += instructUnit_getSize();
  530. /* reach the end */
  531. if (vm->pc + offset >= pc_max) {
  532. break;
  533. }
  534. this_ins_unit = PikaVMFrame_getInstructUnitWithOffset(vm, offset);
  535. if (instructUnit_getIsNewLine(this_ins_unit)) {
  536. uint8_t blockDeepth =
  537. instructUnit_getBlockDeepth(this_ins_unit);
  538. if (blockDeepth <= thisBlockDeepth) {
  539. blockNum++;
  540. }
  541. }
  542. if (blockNum >= vm->jmp) {
  543. break;
  544. }
  545. }
  546. }
  547. if (vm->jmp < 0) {
  548. while (1) {
  549. offset -= instructUnit_getSize();
  550. this_ins_unit = PikaVMFrame_getInstructUnitWithOffset(vm, offset);
  551. if (instructUnit_getIsNewLine(this_ins_unit)) {
  552. uint8_t blockDeepth =
  553. instructUnit_getBlockDeepth(this_ins_unit);
  554. if (blockDeepth == thisBlockDeepth) {
  555. blockNum--;
  556. }
  557. }
  558. if (blockNum <= vm->jmp) {
  559. break;
  560. }
  561. }
  562. }
  563. return offset;
  564. }
  565. static int32_t PikaVMFrame_getAddrOffsetOfBreak(PikaVMFrame* vm) {
  566. int32_t offset = PikaVMFrame_getAddrOffsetOfJmpBack(vm);
  567. /* byteCode */
  568. offset += instructUnit_getSize();
  569. return offset;
  570. }
  571. #if !PIKA_NANO_ENABLE
  572. static int32_t PikaVMFrame_getAddrOffsetOfRaise(PikaVMFrame* vm) {
  573. int offset = 0;
  574. InstructUnit* ins_unit_now = PikaVMFrame_getInstructNow(vm);
  575. while (1) {
  576. offset += instructUnit_getSize();
  577. if (vm->pc + offset >= (int)PikaVMFrame_getInstructArraySize(vm)) {
  578. return 0;
  579. }
  580. ins_unit_now = PikaVMFrame_getInstructUnitWithOffset(vm, offset);
  581. enum InstructIndex ins = instructUnit_getInstructIndex(ins_unit_now);
  582. if (PIKA_INS(NTR) == ins) {
  583. return offset;
  584. }
  585. /* if not found except, return */
  586. if (PIKA_INS(RET) == ins) {
  587. return 0;
  588. }
  589. }
  590. }
  591. #endif
  592. static int32_t PikaVMFrame_getAddrOffsetOfContinue(PikaVMFrame* vm) {
  593. int32_t offset = PikaVMFrame_getAddrOffsetOfJmpBack(vm);
  594. /* byteCode */
  595. return offset;
  596. }
  597. static void VMLocals_delLReg(VMLocals* self, uint8_t index) {
  598. PikaObj* obj = self->lreg[index];
  599. if (NULL != obj) {
  600. obj_enableGC(obj);
  601. self->lreg[index] = NULL;
  602. obj_GC(obj);
  603. }
  604. }
  605. static void Locals_delLReg(PikaObj* self, char* name) {
  606. if (!_checkLReg(name)) {
  607. return;
  608. }
  609. uint8_t reg_index = _getLRegIndex(name);
  610. VMLocals* locals = obj_getStruct(self, "@l");
  611. VMLocals_delLReg(locals, reg_index);
  612. }
  613. static void VMLocals_clearReg(VMLocals* self) {
  614. for (int i = 0; i < PIKA_REGIST_SIZE; i++) {
  615. VMLocals_delLReg(self, i);
  616. }
  617. }
  618. static PikaObj* Locals_getLReg(PikaObj* self, char* name) {
  619. /* get method host obj from reg */
  620. if (!_checkLReg(name)) {
  621. return NULL;
  622. }
  623. uint8_t reg_index = _getLRegIndex(name);
  624. VMLocals* locals = obj_getStruct(self, "@l");
  625. return locals->lreg[reg_index];
  626. }
  627. static PikaObj* New_Locals(Args* args) {
  628. PikaObj* self = New_PikaObj(NULL);
  629. self->constructor = New_Locals;
  630. #if PIKA_KERNAL_DEBUG_ENABLE
  631. self->name = "Locals";
  632. #endif
  633. return self;
  634. }
  635. void Locals_deinit(PikaObj* self) {
  636. VMLocals* tLocals = obj_getStruct(self, "@l");
  637. if (NULL == tLocals) {
  638. return;
  639. }
  640. VMLocals_clearReg(tLocals);
  641. }
  642. static int arg_getLen(Arg* self) {
  643. if (arg_isObject(self)) {
  644. return obj_getSize(arg_getPtr(self));
  645. }
  646. if (arg_getType(self) == ARG_TYPE_STRING) {
  647. int strGetSizeUtf8(char* str);
  648. return strGetSizeUtf8(arg_getStr(self));
  649. }
  650. if (arg_getType(self) == ARG_TYPE_BYTES) {
  651. return arg_getBytesSize(self);
  652. }
  653. return -1;
  654. }
  655. static void PikaVMFrame_initReg(PikaVMFrame* self) {
  656. for (uint8_t i = 0; i < PIKA_REGIST_SIZE; i++) {
  657. self->ireg[i] = pika_false;
  658. }
  659. pika_platform_memset(self->oreg, 0, sizeof(self->oreg));
  660. }
  661. static pika_bool _checkLReg(char* data) {
  662. if ((data[0] == '$') && (data[1] == 'l') && (data[2] >= '0') &&
  663. (data[2] <= '9')) {
  664. return pika_true;
  665. }
  666. return pika_false;
  667. }
  668. static uint8_t _getLRegIndex(char* data) {
  669. return data[2] - '0';
  670. }
  671. static void VMLocals_setLReg(VMLocals* self, uint8_t index, PikaObj* obj) {
  672. obj_refcntInc(obj);
  673. self->lreg[index] = obj;
  674. }
  675. static void Locals_setLReg(PikaObj* self, char* name, PikaObj* obj) {
  676. if (!_checkLReg(name)) {
  677. return;
  678. }
  679. uint8_t reg_index = _getLRegIndex(name);
  680. VMLocals* tlocals = obj_getStruct(self, "@l");
  681. if (NULL == tlocals) {
  682. /* init locals */
  683. VMLocals locals = {0};
  684. obj_setStruct(self, "@l", locals);
  685. tlocals = obj_getStruct(self, "@l");
  686. }
  687. pika_assert(tlocals != NULL);
  688. obj_setName(obj, name);
  689. VMLocals_setLReg(tlocals, reg_index, obj);
  690. }
  691. static Arg* VM_instruction_handler_NON(PikaObj* self,
  692. PikaVMFrame* vm,
  693. char* data,
  694. Arg* arg_ret_reg) {
  695. return NULL;
  696. }
  697. Arg* _vm_get(PikaVMFrame* vm, PikaObj* self, Arg* aKey, Arg* aObj) {
  698. ArgType eType = arg_getType(aObj);
  699. Arg* aObjNew = NULL;
  700. int iIndex = 0;
  701. int iLen = arg_getLen(aObj);
  702. if (ARG_TYPE_INT == arg_getType(aKey)) {
  703. iIndex = arg_getInt(aKey);
  704. }
  705. if (iLen != -1) {
  706. if (iIndex < 0) {
  707. iIndex += iLen;
  708. arg_setInt(aKey, "", iIndex);
  709. }
  710. if (iIndex >= iLen) {
  711. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OUT_OF_RANGE);
  712. PikaVMFrame_setSysOut(vm, "IndexError: index out of range");
  713. return arg_newNone();
  714. }
  715. }
  716. if (ARG_TYPE_STRING == eType) {
  717. #if PIKA_STRING_UTF8_ENABLE
  718. pika_bool bIsTemp = pika_false;
  719. aObjNew = arg_newObj(_arg_to_obj(aObj, &bIsTemp));
  720. eType = arg_getType(aObjNew);
  721. #else
  722. char* sPyload = arg_getStr(aObj);
  723. char sCharBuff[] = " ";
  724. if (iIndex < 0) {
  725. iIndex = strGetSize(sPyload) + iIndex;
  726. }
  727. sCharBuff[0] = sPyload[iIndex];
  728. return arg_newStr(sCharBuff);
  729. #endif
  730. }
  731. if (ARG_TYPE_BYTES == eType) {
  732. uint8_t* sBytesPyload = arg_getBytes(aObj);
  733. uint8_t sByteBuff[] = " ";
  734. sByteBuff[0] = sBytesPyload[iIndex];
  735. return arg_newInt(sByteBuff[0]);
  736. }
  737. if (argType_isObject(eType)) {
  738. PikaObj* oArg = NULL;
  739. Arg* aRes = NULL;
  740. if (aObjNew != NULL) {
  741. oArg = arg_getPtr(aObjNew);
  742. } else {
  743. oArg = arg_getPtr(aObj);
  744. }
  745. obj_setArg(oArg, "__key", aKey);
  746. /* clang-format off */
  747. PIKA_PYTHON(
  748. @res_item = __getitem__(__key)
  749. )
  750. /* clang-format on */
  751. const uint8_t bytes[] = {
  752. 0x0c, 0x00, 0x00, 0x00, /* instruct array size */
  753. 0x10, 0x81, 0x01, 0x00, 0x00, 0x02, 0x07, 0x00, 0x00, 0x04, 0x13,
  754. 0x00,
  755. /* instruct array */
  756. 0x1d, 0x00, 0x00, 0x00, /* const pool size */
  757. 0x00, 0x5f, 0x5f, 0x6b, 0x65, 0x79, 0x00, 0x5f, 0x5f, 0x67, 0x65,
  758. 0x74, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x5f, 0x00, 0x40, 0x72, 0x65,
  759. 0x73, 0x5f, 0x69, 0x74, 0x65, 0x6d, 0x00, /* const pool */
  760. };
  761. if (NULL != vm) {
  762. aRes = pikaVM_runByteCode_exReturn(oArg, oArg, oArg,
  763. (uint8_t*)bytes, vm->vm_thread,
  764. pika_true, "@res_item");
  765. } else {
  766. aRes = pikaVM_runByteCodeReturn(oArg, (uint8_t*)bytes, "@res_item");
  767. }
  768. if (NULL != aObjNew) {
  769. arg_deinit(aObjNew);
  770. }
  771. if (NULL == aRes) {
  772. if (NULL != vm) {
  773. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_ARG_NO_FOUND);
  774. }
  775. return arg_newNone();
  776. }
  777. return aRes;
  778. }
  779. return arg_newNone();
  780. }
  781. Arg* _vm_slice(PikaVMFrame* vm,
  782. PikaObj* self,
  783. Arg* aEnd,
  784. Arg* aObj,
  785. Arg* aStart,
  786. int step) {
  787. #if PIKA_SYNTAX_SLICE_ENABLE
  788. /* No interger index only support __getitem__ */
  789. if (!(arg_getType(aStart) == ARG_TYPE_INT &&
  790. arg_getType(aEnd) == ARG_TYPE_INT)) {
  791. return _vm_get(vm, self, aStart, aObj);
  792. }
  793. int iLen = arg_getLen(aObj);
  794. int iStart = arg_getInt(aStart);
  795. int iEnd = arg_getInt(aEnd);
  796. if (iStart < 0) {
  797. iStart += iLen;
  798. }
  799. /* magic code, to the end */
  800. if (iEnd == VM_PC_EXIT) {
  801. iEnd = iLen;
  802. }
  803. if (iEnd < 0) {
  804. iEnd += iLen;
  805. }
  806. if (iStart > iLen) {
  807. iStart = iLen;
  808. }
  809. if (iEnd > iLen) {
  810. iEnd = iLen;
  811. }
  812. if (iStart > iEnd) {
  813. return arg_newStr("");
  814. }
  815. /* __slice__ is equal to __getitem__ */
  816. if (iEnd - iStart == 1 && arg_getType(aObj) != ARG_TYPE_BYTES) {
  817. return _vm_get(vm, self, aStart, aObj);
  818. }
  819. if (ARG_TYPE_STRING == arg_getType(aObj)) {
  820. Args buffs = {0};
  821. Arg* aSliced = NULL;
  822. char* sSliced = string_slice(&buffs, arg_getStr(aObj), iStart, iEnd);
  823. if (NULL != sSliced) {
  824. aSliced = arg_newStr(sSliced);
  825. } else {
  826. aSliced = arg_newNone();
  827. }
  828. strsDeinit(&buffs);
  829. return aSliced;
  830. }
  831. if (ARG_TYPE_BYTES == arg_getType(aObj)) {
  832. uint8_t* sBytesOrigin = arg_getBytes(aObj);
  833. Arg* aSliced = arg_newBytes(sBytesOrigin + iStart, iEnd - iStart);
  834. return aSliced;
  835. }
  836. if (arg_isObject(aObj)) {
  837. PikaObj* oArg = arg_getPtr(aObj);
  838. PikaObj* New_PikaStdData_List(Args * args);
  839. PikaObj* New_PikaStdData_Tuple(Args * args);
  840. if (oArg->constructor == New_PikaStdData_List ||
  841. oArg->constructor == New_PikaStdData_Tuple) {
  842. PikaObj* oSliced = newNormalObj((NewFun)oArg->constructor);
  843. pikaList_init(oSliced);
  844. for (int i = iStart; i < iEnd; i++) {
  845. Arg* aIndex = arg_newInt(i);
  846. Arg* aItem = _vm_get(vm, self, aIndex, aObj);
  847. pikaList_append(oSliced, aItem);
  848. arg_deinit(aIndex);
  849. }
  850. return arg_newObj(oSliced);
  851. }
  852. }
  853. return arg_newNone();
  854. #else
  855. return _vm_get(vm, self, aStart, aObj);
  856. #endif
  857. }
  858. static Arg* VM_instruction_handler_SLC(PikaObj* self,
  859. PikaVMFrame* vm,
  860. char* data,
  861. Arg* arg_ret_reg) {
  862. #if PIKA_SYNTAX_SLICE_ENABLE
  863. uint32_t n_input = PikaVMFrame_getInputArgNum(vm);
  864. if (n_input < 2) {
  865. return arg_newNone();
  866. }
  867. if (n_input == 2) {
  868. Arg* key = stack_popArg_alloc(&vm->stack);
  869. Arg* obj = stack_popArg_alloc(&vm->stack);
  870. Arg* res = _vm_get(vm, self, key, obj);
  871. arg_deinit(key);
  872. arg_deinit(obj);
  873. return res;
  874. }
  875. if (n_input == 3) {
  876. Arg* end = stack_popArg_alloc(&vm->stack);
  877. Arg* start = stack_popArg_alloc(&vm->stack);
  878. if (arg_getType(start) != ARG_TYPE_INT ||
  879. arg_getType(end) != ARG_TYPE_INT) {
  880. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_INVALID_PARAM);
  881. PikaVMFrame_setSysOut(vm,
  882. "TypeError: slice indices must be integers");
  883. arg_deinit(end);
  884. arg_deinit(start);
  885. return arg_newNone();
  886. }
  887. Arg* obj = stack_popArg_alloc(&vm->stack);
  888. Arg* res = _vm_slice(vm, self, end, obj, start, 1);
  889. arg_deinit(end);
  890. arg_deinit(obj);
  891. arg_deinit(start);
  892. return res;
  893. }
  894. return arg_newNone();
  895. #else
  896. Arg* key = stack_popArg_alloc(&vm->stack);
  897. Arg* obj = stack_popArg_alloc(&vm->stack);
  898. Arg* res = _vm_get(vm, self, key, obj);
  899. arg_deinit(key);
  900. arg_deinit(obj);
  901. return res;
  902. #endif
  903. }
  904. static Arg* VM_instruction_handler_TRY(PikaObj* self,
  905. PikaVMFrame* vm,
  906. char* data,
  907. Arg* arg_ret_reg) {
  908. pika_assert(NULL != vm->vm_thread);
  909. vm->vm_thread->try_state = TRY_STATE_INNER;
  910. return NULL;
  911. }
  912. static Arg* VM_instruction_handler_EXP(PikaObj* self,
  913. PikaVMFrame* vm,
  914. char* data,
  915. Arg* arg_ret_reg) {
  916. pikaVMThread_clearExceptionStack(vm->vm_thread);
  917. return NULL;
  918. }
  919. static Arg* VM_instruction_handler_NTR(PikaObj* self,
  920. PikaVMFrame* vm,
  921. char* data,
  922. Arg* arg_ret_reg) {
  923. vm->vm_thread->try_state = TRY_STATE_NONE;
  924. pikaVMThread_convertExceptionStack(vm->vm_thread);
  925. return NULL;
  926. }
  927. static Arg* VM_instruction_handler_NEW(PikaObj* self,
  928. PikaVMFrame* vm,
  929. char* data,
  930. Arg* arg_ret_reg) {
  931. Arg* origin_arg = obj_getArg(vm->locals, data);
  932. Arg* new_arg = arg_copy(origin_arg);
  933. arg_setType(origin_arg, ARG_TYPE_OBJECT);
  934. arg_setType(new_arg, ARG_TYPE_OBJECT_NEW);
  935. return new_arg;
  936. }
  937. static Arg* _proxy_getattribute(PikaObj* host, char* name) {
  938. #if PIKA_NANO_ENABLE
  939. return NULL;
  940. #endif
  941. if ('@' != name[0] && obj_getFlag(host, OBJ_FLAG_PROXY_GETATTRIBUTE)) {
  942. Arg* aRes = obj_runMethod1(host, "__getattribute__", arg_newStr(name));
  943. return aRes;
  944. }
  945. return NULL;
  946. }
  947. static Arg* _proxy_getattr(PikaObj* host, char* name) {
  948. #if PIKA_NANO_ENABLE
  949. return NULL;
  950. #endif
  951. if ('@' != name[0] && obj_getFlag(host, OBJ_FLAG_PROXY_GETATTR)) {
  952. Arg* aRes = obj_runMethod1(host, "__getattr__", arg_newStr(name));
  953. return aRes;
  954. }
  955. return NULL;
  956. }
  957. static Arg* VM_instruction_handler_REF(PikaObj* self,
  958. PikaVMFrame* vm,
  959. char* data,
  960. Arg* aRetReg) {
  961. PikaObj* oHost = NULL;
  962. char* arg_path = data;
  963. char* arg_name = strPointToLastToken(arg_path, '.');
  964. pika_bool is_temp = pika_false;
  965. pika_bool is_alloc = pika_false;
  966. PikaObj* oBuiltins = NULL;
  967. switch (data[0]) {
  968. case 'T':
  969. if (strEqu(arg_path, (char*)"True")) {
  970. return arg_setBool(aRetReg, "", pika_true);
  971. }
  972. break;
  973. case 'F':
  974. if (strEqu(arg_path, (char*)"False")) {
  975. return arg_setBool(aRetReg, "", pika_false);
  976. }
  977. break;
  978. case 'N':
  979. if (strEqu(arg_path, (char*)"None")) {
  980. return arg_setNone(aRetReg);
  981. }
  982. break;
  983. case 'R':
  984. if (strEqu(arg_path, (char*)"RuntimeError")) {
  985. return arg_setInt(aRetReg, "", PIKA_RES_ERR_RUNTIME_ERROR);
  986. }
  987. break;
  988. }
  989. Arg* aRes = NULL;
  990. if (arg_path[0] == '.') {
  991. /* find host from stack */
  992. Arg* host_arg = stack_popArg_alloc(&(vm->stack));
  993. if (NULL == host_arg) {
  994. goto __exit;
  995. }
  996. if (arg_isObject(host_arg)) {
  997. oHost = arg_getPtr(host_arg);
  998. aRes = arg_copy_noalloc(obj_getArg(oHost, arg_path + 1), aRetReg);
  999. }
  1000. arg_deinit(host_arg);
  1001. goto __exit;
  1002. }
  1003. /* find in local list first */
  1004. if (NULL == oHost) {
  1005. oHost = obj_getHostObjWithIsTemp(vm->locals, arg_path, &is_temp);
  1006. }
  1007. /* find in global list */
  1008. if (NULL == oHost) {
  1009. oHost = obj_getHostObjWithIsTemp(vm->globals, arg_path, &is_temp);
  1010. }
  1011. /* error cannot found host_object */
  1012. if (NULL == oHost) {
  1013. goto __exit;
  1014. }
  1015. /* proxy */
  1016. if (NULL == aRes) {
  1017. aRes = _proxy_getattribute(oHost, arg_name);
  1018. if (NULL != aRes) {
  1019. is_alloc = pika_true;
  1020. }
  1021. }
  1022. /* find res in host */
  1023. if (NULL == aRes) {
  1024. aRes = args_getArg(oHost->list, arg_name);
  1025. }
  1026. /* find res in host prop */
  1027. if (NULL == aRes) {
  1028. aRes = _obj_getPropArg(oHost, arg_name);
  1029. }
  1030. /* find res in globals */
  1031. if (arg_path == arg_name) {
  1032. if (NULL == aRes) {
  1033. aRes = args_getArg(vm->globals->list, arg_name);
  1034. }
  1035. /* find res in globals prop */
  1036. if (NULL == aRes) {
  1037. aRes = _obj_getPropArg(vm->globals, arg_name);
  1038. }
  1039. /* find res in builtins */
  1040. if (NULL == aRes) {
  1041. oBuiltins = obj_getBuiltins();
  1042. aRes = args_getArg(oBuiltins->list, arg_name);
  1043. }
  1044. if (NULL == aRes) {
  1045. aRes = _obj_getPropArg(oBuiltins, arg_name);
  1046. }
  1047. }
  1048. /* proxy */
  1049. if (NULL == aRes) {
  1050. aRes = _proxy_getattr(oHost, arg_name);
  1051. if (NULL != aRes) {
  1052. is_alloc = pika_true;
  1053. }
  1054. }
  1055. __exit:
  1056. if (NULL != oBuiltins) {
  1057. obj_deinit(oBuiltins);
  1058. }
  1059. if (NULL == aRes) {
  1060. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_ARG_NO_FOUND);
  1061. PikaVMFrame_setSysOut(vm, "NameError: name '%s' is not defined",
  1062. arg_path);
  1063. } else {
  1064. aRes = methodArg_setHostObj(aRes, oHost);
  1065. if ((arg_getType(aRes) != ARG_TYPE_METHOD_NATIVE_ACTIVE) && !is_alloc) {
  1066. aRes = arg_copy_noalloc(aRes, aRetReg);
  1067. }
  1068. pika_assert_arg_alive(aRes);
  1069. }
  1070. if (is_temp) {
  1071. obj_GC(oHost);
  1072. }
  1073. return aRes;
  1074. }
  1075. static Arg* VM_instruction_handler_GER(PikaObj* self,
  1076. PikaVMFrame* vm,
  1077. char* data,
  1078. Arg* arg_ret_reg) {
  1079. PIKA_RES err = pikaVMFrame_checkExceptionStack(vm);
  1080. Arg* err_arg = arg_newInt(err);
  1081. return err_arg;
  1082. }
  1083. Arg* _get_return_arg(PikaObj* locals) {
  1084. Arg* res = args_getArg(locals->list, (char*)"@rt");
  1085. args_removeArg_notDeinitArg(locals->list, res);
  1086. return res;
  1087. }
  1088. Arg* _obj_runMethodArgWithState(PikaObj* self,
  1089. PikaObj* locals,
  1090. Arg* aMethod,
  1091. PikaVMThread* vm_thread,
  1092. Arg* aReturnCache) {
  1093. pika_assert(NULL != vm_thread);
  1094. Arg* aReturn = NULL;
  1095. /* get method Ptr */
  1096. Method fMethod = methodArg_getPtr(aMethod);
  1097. /* get method type list */
  1098. ArgType methodType = arg_getType(aMethod);
  1099. /* error */
  1100. if (ARG_TYPE_NONE == methodType) {
  1101. return NULL;
  1102. }
  1103. /* redirect to def context */
  1104. if (!argType_isNative(methodType)) {
  1105. self = methodArg_getDefContext(aMethod);
  1106. }
  1107. /* run method */
  1108. if (argType_isNative(methodType)) {
  1109. /* native method */
  1110. PikaObj* oHost = self;
  1111. if (methodType == ARG_TYPE_METHOD_NATIVE_ACTIVE) {
  1112. oHost = methodArg_getHostObj(aMethod);
  1113. }
  1114. fMethod(oHost, locals->list);
  1115. /* get method return */
  1116. aReturn = _get_return_arg(locals);
  1117. } else {
  1118. /* static method and object method */
  1119. /* byteCode */
  1120. ByteCodeFrame* method_bytecodeFrame =
  1121. methodArg_getBytecodeFrame(aMethod);
  1122. uintptr_t insturctArray_start = (uintptr_t)instructArray_getByOffset(
  1123. &(method_bytecodeFrame->instruct_array), 0);
  1124. uint16_t pc = (uintptr_t)fMethod - insturctArray_start;
  1125. locals = _pikaVM_runByteCodeFrameWithState(
  1126. self, locals, self, method_bytecodeFrame, pc, vm_thread);
  1127. /* get method return */
  1128. aReturn = _get_return_arg(locals);
  1129. }
  1130. #if PIKA_TYPE_FULL_FEATURE_ENABLE
  1131. PikaObj* oReturn = NULL;
  1132. if (arg_isConstructor(aMethod)) {
  1133. if (arg_isObject(aReturn)) {
  1134. oReturn = arg_getPtr(aReturn);
  1135. obj_setArg(oReturn, "__class__", aMethod);
  1136. }
  1137. }
  1138. #endif
  1139. pika_assert_arg_alive(aReturn);
  1140. return aReturn;
  1141. }
  1142. Arg* obj_runMethodArgWithState(PikaObj* self,
  1143. PikaObj* method_args_obj,
  1144. Arg* method_arg,
  1145. PikaVMThread* vm_thread) {
  1146. return _obj_runMethodArgWithState(self, method_args_obj, method_arg,
  1147. vm_thread, NULL);
  1148. }
  1149. Arg* obj_runMethodArgWithState_noalloc(PikaObj* self,
  1150. PikaObj* locals,
  1151. Arg* method_arg,
  1152. PikaVMThread* vm_thread,
  1153. Arg* ret_arg_reg) {
  1154. return _obj_runMethodArgWithState(self, locals, method_arg, vm_thread,
  1155. ret_arg_reg);
  1156. }
  1157. Arg* obj_runMethodArg(PikaObj* self,
  1158. PikaObj* method_args_obj,
  1159. Arg* method_arg) {
  1160. PikaVMThread* vm_thread = pikaVMThread_require();
  1161. return obj_runMethodArgWithState(self, method_args_obj, method_arg,
  1162. vm_thread);
  1163. }
  1164. static char* _kw_pos_to_default_all(FunctionArgsInfo* f,
  1165. char* sArgName,
  1166. int* argc,
  1167. Arg* argv[],
  1168. Arg* aCall) {
  1169. #if PIKA_NANO_ENABLE
  1170. return sArgName;
  1171. #endif
  1172. int iDefaultSkip = 0;
  1173. int iDefaultSkiped = 0;
  1174. if (f->i_arg == f->n_arg) {
  1175. iDefaultSkip = f->n_default - f->n_arg + f->n_positional;
  1176. }
  1177. while (strIsContain(sArgName, '=')) {
  1178. strPopLastToken(sArgName, '=');
  1179. Arg* aKeyword = NULL;
  1180. /* load default arg from kws */
  1181. if (f->kw != NULL) {
  1182. aKeyword = pikaDict_get(f->kw, sArgName);
  1183. if (aKeyword != NULL) {
  1184. argv[(*argc)++] = arg_copy(aKeyword);
  1185. pikaDict_removeArg(f->kw, aKeyword);
  1186. goto __next;
  1187. }
  1188. }
  1189. /* load default arg from pos */
  1190. if (NULL != aCall && f->is_default) {
  1191. /* load pos to default with right order */
  1192. if (iDefaultSkiped < iDefaultSkip) {
  1193. iDefaultSkiped++;
  1194. sArgName = strPopLastToken(f->type_list, ',');
  1195. continue;
  1196. }
  1197. /* load default from pos */
  1198. if (f->i_arg > f->n_positional) {
  1199. arg_setNameHash(aCall, hash_time33EndWith(sArgName, ':'));
  1200. argv[(*argc)++] = aCall;
  1201. return (char*)1;
  1202. }
  1203. }
  1204. __next:
  1205. sArgName = strPopLastToken(f->type_list, ',');
  1206. }
  1207. return sArgName;
  1208. }
  1209. static int _kw_to_pos_one(FunctionArgsInfo* f,
  1210. char* arg_name,
  1211. int* argc,
  1212. Arg* argv[]) {
  1213. if (f->kw == NULL) {
  1214. return 0;
  1215. }
  1216. Arg* pos_arg = pikaDict_get(f->kw, arg_name);
  1217. if (pos_arg == NULL) {
  1218. return 0;
  1219. }
  1220. argv[(*argc)++] = arg_copy(pos_arg);
  1221. pikaDict_removeArg(f->kw, pos_arg);
  1222. return 1;
  1223. }
  1224. static void _kw_to_pos_all(FunctionArgsInfo* f, int* argc, Arg* argv[]) {
  1225. int arg_num_need = f->n_positional - f->n_positional_got;
  1226. if (0 == arg_num_need) {
  1227. return;
  1228. }
  1229. for (int i = 0; i < arg_num_need; i++) {
  1230. char* arg_name = strPopLastToken(f->type_list, ',');
  1231. pika_assert(f->kw != NULL);
  1232. Arg* pos_arg = pikaDict_get(f->kw, arg_name);
  1233. pika_assert(pos_arg != NULL);
  1234. argv[(*argc)++] = arg_copy(pos_arg);
  1235. pikaDict_removeArg(f->kw, pos_arg);
  1236. }
  1237. }
  1238. static void _loadLocalsFromArgv(Args* locals, int argc, Arg* argv[]) {
  1239. for (int i = 0; i < argc; i++) {
  1240. Arg* arg = argv[i];
  1241. pika_assert(arg != NULL);
  1242. args_setArg(locals, arg);
  1243. }
  1244. }
  1245. static void _type_list_parse(FunctionArgsInfo* f) {
  1246. if (f->type_list[0] == 0) {
  1247. f->n_positional = 0;
  1248. return;
  1249. }
  1250. int8_t iArgc = strCountSign(f->type_list, ',') + 1;
  1251. int8_t iStar = strCountSign(f->type_list, '*');
  1252. int8_t iAssign = strCountSign(f->type_list, '=');
  1253. /* default */
  1254. if (iAssign > 0) {
  1255. iArgc -= iAssign;
  1256. f->is_default = pika_true;
  1257. f->n_default = iAssign;
  1258. }
  1259. /* vars */
  1260. if (iStar == 1) {
  1261. f->is_vars = pika_true;
  1262. f->n_positional = iArgc - 1;
  1263. return;
  1264. }
  1265. /* kw */
  1266. if (iStar == 2) {
  1267. f->is_keys = pika_true;
  1268. f->n_positional = iArgc - 1;
  1269. return;
  1270. }
  1271. /* vars and kw */
  1272. if (iStar == 3) {
  1273. f->is_vars = pika_true;
  1274. f->is_keys = pika_true;
  1275. f->n_positional = iArgc - 2;
  1276. return;
  1277. }
  1278. f->n_positional = iArgc;
  1279. return;
  1280. }
  1281. static void _kw_push(FunctionArgsInfo* f, Arg* call_arg, int i) {
  1282. if (NULL == f->kw) {
  1283. f->kw = New_PikaDict();
  1284. }
  1285. arg_setIsKeyword(call_arg, pika_false);
  1286. Hash kw_hash = call_arg->name_hash;
  1287. char buff[32] = {0};
  1288. _pikaDict_setVal(f->kw, call_arg);
  1289. char* sHash = fast_itoa(buff, kw_hash);
  1290. args_setStr(_OBJ2KEYS(f->kw), sHash, sHash);
  1291. pikaDict_reverse(f->kw);
  1292. }
  1293. static void _load_call_arg(PikaVMFrame* vm,
  1294. Arg* call_arg,
  1295. FunctionArgsInfo* f,
  1296. int* i,
  1297. int* argc,
  1298. Arg* argv[]) {
  1299. /* load the kw arg */
  1300. pika_assert(NULL != call_arg);
  1301. if (arg_getIsKeyword(call_arg)) {
  1302. _kw_push(f, call_arg, *i);
  1303. return;
  1304. }
  1305. /* load variable arg */
  1306. if (f->i_arg > f->n_positional) {
  1307. if (f->is_vars) {
  1308. pikaList_append(f->tuple, call_arg);
  1309. return;
  1310. }
  1311. }
  1312. char* arg_name = strPopLastToken(f->type_list, ',');
  1313. /* load default from kw */
  1314. arg_name = _kw_pos_to_default_all(f, arg_name, argc, argv, call_arg);
  1315. if (((char*)1) == arg_name) {
  1316. /* load default from pos */
  1317. return;
  1318. }
  1319. /* load position arg */
  1320. if (_kw_to_pos_one(f, arg_name, argc, argv)) {
  1321. /* load pos from kw */
  1322. (f->n_positional_got)++;
  1323. /* restore the stack */
  1324. (*i)--;
  1325. stack_pushArg(&(vm->stack), call_arg);
  1326. return;
  1327. }
  1328. /*load pos from pos */
  1329. arg_setNameHash(call_arg, hash_time33EndWith(arg_name, ':'));
  1330. pika_assert(call_arg != NULL);
  1331. argv[(*argc)++] = call_arg;
  1332. (f->n_positional_got)++;
  1333. }
  1334. static uint32_t _get_n_input_with_unpack(PikaVMFrame* vm, int n_used) {
  1335. #if PIKA_NANO_ENABLE
  1336. return PikaVMFrame_getInputArgNum(vm);
  1337. #else
  1338. uint32_t n_input = PikaVMFrame_getInputArgNum(vm) - n_used;
  1339. int get_star = 0;
  1340. int unpack_num = 0;
  1341. for (int i = 0; i < n_input; i++) {
  1342. Arg* arg_check = stack_checkArg(&(vm->stack), i);
  1343. if (NULL == arg_check) {
  1344. break;
  1345. }
  1346. if (arg_getIsDoubleStarred(arg_check) || arg_getIsStarred(arg_check)) {
  1347. get_star++;
  1348. }
  1349. }
  1350. if (0 == get_star) {
  1351. return n_input;
  1352. }
  1353. Stack stack_tmp = {0};
  1354. stack_init(&stack_tmp);
  1355. for (int i = 0; i < n_input; i++) {
  1356. /* unpack starred arg */
  1357. Arg* call_arg = stack_popArg_alloc(&(vm->stack));
  1358. if (call_arg == NULL) {
  1359. break;
  1360. }
  1361. if (arg_getIsStarred(call_arg)) {
  1362. if (!arg_isObject(call_arg)) {
  1363. stack_pushArg(&stack_tmp, arg_copy(call_arg));
  1364. goto __continue;
  1365. }
  1366. PikaObj* obj = arg_getPtr(call_arg);
  1367. int len = obj_getSize(obj);
  1368. for (int i_star_arg = len - 1; i_star_arg >= 0; i_star_arg--) {
  1369. Arg* arg_a =
  1370. obj_runMethod1(obj, "__getitem__", arg_newInt(i_star_arg));
  1371. stack_pushArg(&stack_tmp, arg_a);
  1372. unpack_num++;
  1373. }
  1374. goto __continue;
  1375. }
  1376. if (arg_getIsDoubleStarred(call_arg)) {
  1377. pika_assert(arg_isObject(call_arg));
  1378. PikaObj* New_PikaStdData_Dict(Args * args);
  1379. PikaObj* obj = arg_getPtr(call_arg);
  1380. pika_assert(obj->constructor == New_PikaStdData_Dict);
  1381. Args* dict = _OBJ2DICT(obj);
  1382. int i_item = args_getSize(dict);
  1383. while (pika_true) {
  1384. i_item--;
  1385. if (i_item < 0) {
  1386. break;
  1387. }
  1388. Arg* item_val = args_getArgByIndex(dict, i_item);
  1389. /* unpack as keyword arg */
  1390. arg_setIsKeyword(item_val, pika_true);
  1391. stack_pushArg(&stack_tmp, arg_copy(item_val));
  1392. }
  1393. goto __continue;
  1394. }
  1395. stack_pushArg(&stack_tmp, arg_copy(call_arg));
  1396. __continue:
  1397. if (NULL != call_arg) {
  1398. arg_deinit(call_arg);
  1399. }
  1400. }
  1401. uint32_t n_input_new = stack_getTop(&stack_tmp);
  1402. for (int i = 0; i < n_input_new; i++) {
  1403. Arg* arg = stack_popArg_alloc(&stack_tmp);
  1404. stack_pushArg(&(vm->stack), arg);
  1405. }
  1406. stack_deinit(&stack_tmp);
  1407. return n_input_new;
  1408. #endif
  1409. }
  1410. #define vars_or_keys_or_default (f.is_vars || f.is_keys || f.is_default)
  1411. #define METHOD_TYPE_LIST_MAX_LEN PIKA_LINE_BUFF_SIZE * 2
  1412. static int PikaVMFrame_loadArgsFromMethodArg(PikaVMFrame* vm,
  1413. PikaObj* oMethodHost,
  1414. Args* aLoclas,
  1415. Arg* aMethod,
  1416. char* sMethodName,
  1417. char* sProxyName,
  1418. int iNumUsed) {
  1419. int argc = 0;
  1420. Arg** argv = (Arg**)pikaMalloc(sizeof(Arg*) * PIKA_ARG_NUM_MAX);
  1421. char* buffs1 = (char*)pikaMalloc(METHOD_TYPE_LIST_MAX_LEN);
  1422. char* buffs2 = (char*)pikaMalloc(METHOD_TYPE_LIST_MAX_LEN);
  1423. FunctionArgsInfo f = {0};
  1424. char* type_list_buff = NULL;
  1425. /* get method type list */
  1426. f.type_list =
  1427. methodArg_getTypeList(aMethod, buffs1, METHOD_TYPE_LIST_MAX_LEN);
  1428. pika_assert_msg(NULL != f.type_list, "method: %s", sMethodName);
  1429. if (NULL == f.type_list) {
  1430. pika_platform_printf(
  1431. "OverflowError: type list is too long, please use bigger "
  1432. "PIKA_LINE_BUFF_SIZE\r\n");
  1433. pika_platform_panic_handle();
  1434. }
  1435. f.method_type = arg_getType(aMethod);
  1436. /* get arg_num_pos */
  1437. _type_list_parse(&f);
  1438. if (f.method_type == ARG_TYPE_METHOD_OBJECT) {
  1439. /* delete the 'self' */
  1440. f.n_positional--;
  1441. }
  1442. f.n_input = _get_n_input_with_unpack(vm, iNumUsed);
  1443. if (NULL != sProxyName) {
  1444. /* method proxy takes the first arg as method name */
  1445. f.n_input++;
  1446. }
  1447. do {
  1448. /* check arg num */
  1449. if (f.method_type == ARG_TYPE_METHOD_NATIVE_CONSTRUCTOR ||
  1450. f.method_type == ARG_TYPE_METHOD_CONSTRUCTOR || iNumUsed != 0) {
  1451. /* skip for constrctor */
  1452. /* skip for variable args */
  1453. /* n_used != 0 means it is a factory method */
  1454. break;
  1455. }
  1456. /* check position arg num */
  1457. if (!vars_or_keys_or_default) {
  1458. if (f.n_positional != f.n_input) {
  1459. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_INVALID_PARAM);
  1460. PikaVMFrame_setSysOut(
  1461. vm,
  1462. "TypeError: %s() takes %d positional argument but %d "
  1463. "were "
  1464. "given",
  1465. sMethodName, f.n_positional, f.n_input);
  1466. goto __exit;
  1467. }
  1468. break;
  1469. }
  1470. #if !PIKA_NANO_ENABLE
  1471. if (f.is_keys) {
  1472. break;
  1473. }
  1474. if (f.is_vars) {
  1475. if (f.n_input < f.n_positional) {
  1476. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_INVALID_PARAM);
  1477. PikaVMFrame_setSysOut(
  1478. vm,
  1479. "TypeError: %s() takes %d positional argument but "
  1480. "%d "
  1481. "were "
  1482. "given",
  1483. sMethodName, f.n_positional, f.n_input);
  1484. goto __exit;
  1485. }
  1486. break;
  1487. }
  1488. if (f.is_default) {
  1489. int8_t n_min = f.n_positional;
  1490. int8_t n_max = f.n_positional + f.n_default;
  1491. if (f.n_input < n_min || f.n_input > n_max) {
  1492. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_INVALID_PARAM);
  1493. PikaVMFrame_setSysOut(
  1494. vm,
  1495. "TypeError: %s() takes from %d to %d positional "
  1496. "arguments "
  1497. "but %d were given",
  1498. sMethodName, n_min, n_max, f.n_input);
  1499. goto __exit;
  1500. }
  1501. }
  1502. #endif
  1503. } while (0);
  1504. if (vars_or_keys_or_default) {
  1505. f.n_arg = f.n_input;
  1506. } else {
  1507. f.n_arg = f.n_positional;
  1508. }
  1509. /* create tuple/dict for vars/keys */
  1510. if (vars_or_keys_or_default) {
  1511. if (strGetSize(f.type_list) > METHOD_TYPE_LIST_MAX_LEN) {
  1512. pika_platform_printf(
  1513. "OverFlowError: please use bigger PIKA_LINE_BUFF_SIZE\r\n");
  1514. while (1) {
  1515. }
  1516. }
  1517. type_list_buff = strCopy(buffs2, f.type_list);
  1518. uint8_t n_typelist = strCountSign(type_list_buff, ',') + 1;
  1519. for (int i = 0; i < n_typelist; i++) {
  1520. char* arg_def = strPopLastToken(type_list_buff, ',');
  1521. if (arg_def[0] == '*' && arg_def[1] != '*') {
  1522. /* get variable tuple name */
  1523. /* skip the '*' */
  1524. f.var_tuple_name = arg_def + 1;
  1525. /* create tuple */
  1526. if (NULL == f.tuple) {
  1527. f.tuple = New_pikaTuple();
  1528. /* remove the format arg */
  1529. strPopLastToken(f.type_list, ',');
  1530. }
  1531. continue;
  1532. }
  1533. if (arg_def[0] == '*' && arg_def[1] == '*') {
  1534. /* get kw dict name */
  1535. f.kw_dict_name = arg_def + 2;
  1536. f.kw = New_PikaDict();
  1537. /* remove the format arg */
  1538. strPopLastToken(f.type_list, ',');
  1539. continue;
  1540. }
  1541. }
  1542. }
  1543. /* load args */
  1544. for (int i = 0; i < f.n_arg; i++) {
  1545. Arg* call_arg = NULL;
  1546. f.i_arg = f.n_arg - i;
  1547. if (NULL != sProxyName && i == f.n_arg - 1) {
  1548. call_arg = arg_newStr(sProxyName);
  1549. } else {
  1550. call_arg = stack_popArg_alloc(&(vm->stack));
  1551. }
  1552. if (NULL == call_arg) {
  1553. call_arg = arg_newNone();
  1554. }
  1555. _load_call_arg(vm, call_arg, &f, &i, &argc, argv);
  1556. }
  1557. /* only default */
  1558. #if !PIKA_NANO_ENABLE
  1559. if (strIsContain(f.type_list, '=')) {
  1560. char* arg_name = strPopLastToken(f.type_list, ',');
  1561. _kw_pos_to_default_all(&f, arg_name, &argc, argv, NULL);
  1562. }
  1563. /* load kw to pos */
  1564. _kw_to_pos_all(&f, &argc, argv);
  1565. #endif
  1566. if (f.tuple != NULL) {
  1567. pikaList_reverse(f.tuple);
  1568. /* load variable tuple */
  1569. Arg* argi =
  1570. arg_setPtr(NULL, f.var_tuple_name, ARG_TYPE_OBJECT, f.tuple);
  1571. argv[argc++] = argi;
  1572. }
  1573. if (f.kw != NULL) {
  1574. if (NULL == f.kw_dict_name) {
  1575. f.kw_dict_name = "__kwargs";
  1576. }
  1577. /* load kw dict */
  1578. PikaObj* New_PikaStdData_Dict(Args * args);
  1579. Arg* argi = arg_setPtr(NULL, f.kw_dict_name, ARG_TYPE_OBJECT, f.kw);
  1580. argv[argc++] = argi;
  1581. }
  1582. /* load 'self' as the first arg when call object method */
  1583. if (f.method_type == ARG_TYPE_METHOD_OBJECT) {
  1584. PikaObj* method_self = NULL;
  1585. method_self = methodArg_getHostObj(aMethod);
  1586. if (NULL == method_self) {
  1587. method_self = oMethodHost;
  1588. }
  1589. Arg* call_arg = arg_setRef(NULL, "self", method_self);
  1590. pika_assert(call_arg != NULL);
  1591. argv[argc++] = call_arg;
  1592. }
  1593. _loadLocalsFromArgv(aLoclas, argc, argv);
  1594. __exit:
  1595. pikaFree(buffs1, METHOD_TYPE_LIST_MAX_LEN);
  1596. pikaFree(buffs2, METHOD_TYPE_LIST_MAX_LEN);
  1597. pikaFree(argv, sizeof(Arg*) * PIKA_ARG_NUM_MAX);
  1598. return f.n_arg;
  1599. }
  1600. #if PIKA_BUILTIN_STRUCT_ENABLE
  1601. PikaObj* New_PikaStdData_List(Args* args);
  1602. PikaObj* New_PikaStdData_Tuple(Args* args);
  1603. #endif
  1604. static Arg* _vm_create_list_or_tuple(PikaObj* self,
  1605. PikaVMFrame* vm,
  1606. pika_bool is_list) {
  1607. #if PIKA_BUILTIN_STRUCT_ENABLE
  1608. NewFun constructor = is_list ? New_PikaStdData_List : New_PikaStdData_Tuple;
  1609. uint32_t n_arg = PikaVMFrame_getInputArgNum(vm);
  1610. PikaObj* list = newNormalObj(constructor);
  1611. pikaList_init(list);
  1612. Stack stack = {0};
  1613. stack_init(&stack);
  1614. /* load to local stack to change sort */
  1615. for (int i = 0; i < n_arg; i++) {
  1616. Arg* arg = stack_popArg_alloc(&(vm->stack));
  1617. pika_assert(arg != NULL);
  1618. stack_pushArg(&stack, arg);
  1619. }
  1620. for (int i = 0; i < n_arg; i++) {
  1621. Arg* arg = stack_popArg_alloc(&stack);
  1622. pika_assert(arg != NULL);
  1623. pikaList_append(list, arg);
  1624. }
  1625. stack_deinit(&stack);
  1626. return arg_newObj(list);
  1627. #else
  1628. return VM_instruction_handler_NON(self, vm, "", NULL);
  1629. #endif
  1630. }
  1631. static Arg* VM_instruction_handler_LST(PikaObj* self,
  1632. PikaVMFrame* vm,
  1633. char* data,
  1634. Arg* arg_ret_reg) {
  1635. #if PIKA_BUILTIN_STRUCT_ENABLE
  1636. PikaObj* list = newNormalObj(New_PikaStdData_List);
  1637. pikaList_init(list);
  1638. vm->oreg[PikaVMFrame_getInvokeDeepthNow(vm)] = list;
  1639. #endif
  1640. return NULL;
  1641. }
  1642. static Arg* VM_instruction_handler_NLS(PikaObj* self,
  1643. PikaVMFrame* vm,
  1644. char* data,
  1645. Arg* arg_ret_reg) {
  1646. #if PIKA_BUILTIN_STRUCT_ENABLE
  1647. PikaObj* list = vm->oreg[PikaVMFrame_getInvokeDeepthNow(vm)];
  1648. vm->oreg[PikaVMFrame_getInvokeDeepthNow(vm)] = NULL;
  1649. return arg_newObj(list);
  1650. #else
  1651. return VM_instruction_handler_NON(self, vm, "", NULL);
  1652. #endif
  1653. }
  1654. static Arg* VM_instruction_handler_TPL(PikaObj* self,
  1655. PikaVMFrame* vm,
  1656. char* data,
  1657. Arg* arg_ret_reg) {
  1658. return _vm_create_list_or_tuple(self, vm, pika_false);
  1659. }
  1660. #if PIKA_BUILTIN_STRUCT_ENABLE
  1661. PikaObj* New_PikaStdData_Dict(Args* args);
  1662. #endif
  1663. static Arg* VM_instruction_handler_DCT(PikaObj* self,
  1664. PikaVMFrame* vm,
  1665. char* data,
  1666. Arg* arg_ret_reg) {
  1667. #if PIKA_BUILTIN_STRUCT_ENABLE
  1668. uint32_t n_arg = PikaVMFrame_getInputArgNum(vm);
  1669. PikaObj* dict = New_PikaDict();
  1670. Stack stack = {0};
  1671. stack_init(&stack);
  1672. /* load to local stack to change sort */
  1673. for (int i = 0; i < n_arg; i++) {
  1674. Arg* arg = stack_popArg_alloc(&(vm->stack));
  1675. stack_pushArg(&stack, arg);
  1676. }
  1677. for (int i = 0; i < n_arg / 2; i++) {
  1678. Arg* key_arg = stack_popArg_alloc(&stack);
  1679. Arg* val_arg = stack_popArg_alloc(&stack);
  1680. pikaDict_set(dict, arg_getStr(key_arg), val_arg);
  1681. arg_deinit(key_arg);
  1682. }
  1683. stack_deinit(&stack);
  1684. return arg_newObj(dict);
  1685. #else
  1686. return VM_instruction_handler_NON(self, vm, data, arg_ret_reg);
  1687. #endif
  1688. }
  1689. static Arg* VM_instruction_handler_RET(PikaObj* self,
  1690. PikaVMFrame* vm,
  1691. char* data,
  1692. Arg* arg_ret_reg) {
  1693. /* exit jmp signal */
  1694. vm->jmp = VM_JMP_EXIT;
  1695. Arg* aReturn = stack_popArg_alloc(&(vm->stack));
  1696. /* set gc root to avoid gc */
  1697. arg_setObjFlag(aReturn, OBJ_FLAG_GC_ROOT);
  1698. method_returnArg(vm->locals->list, aReturn);
  1699. return NULL;
  1700. }
  1701. InstructUnit* byteCodeFrame_findInstructUnit(ByteCodeFrame* bcframe,
  1702. int32_t iPcStart,
  1703. enum InstructIndex index,
  1704. int32_t* iOffset_p,
  1705. pika_bool bIsForward) {
  1706. /* find instruct unit */
  1707. int instructArray_size = instructArray_getSize(&(bcframe->instruct_array));
  1708. while (1) {
  1709. *iOffset_p += (bIsForward ? -1 : 1) * instructUnit_getSize();
  1710. if (iPcStart + *iOffset_p >= instructArray_size) {
  1711. return NULL;
  1712. }
  1713. if (iPcStart + *iOffset_p < 0) {
  1714. return NULL;
  1715. }
  1716. InstructUnit* unit = instructArray_getByOffset(
  1717. &(bcframe->instruct_array), iPcStart + *iOffset_p);
  1718. if (index == instructUnit_getInstructIndex(unit)) {
  1719. return unit;
  1720. }
  1721. }
  1722. }
  1723. InstructUnit* byteCodeFrame_findInsForward(ByteCodeFrame* bcframe,
  1724. int32_t pc_start,
  1725. enum InstructIndex index,
  1726. int32_t* p_offset) {
  1727. return byteCodeFrame_findInstructUnit(bcframe, pc_start, index, p_offset,
  1728. pika_true);
  1729. }
  1730. Hash byteCodeFrame_getNameHash(ByteCodeFrame* bcframe) {
  1731. if (0 == bcframe->name_hash) {
  1732. bcframe->name_hash = hash_time33(bcframe->name);
  1733. }
  1734. return bcframe->name_hash;
  1735. }
  1736. InstructUnit* byteCodeFrame_findInsUnitBackward(ByteCodeFrame* bcframe,
  1737. int32_t pc_start,
  1738. enum InstructIndex index,
  1739. int32_t* p_offset) {
  1740. return byteCodeFrame_findInstructUnit(bcframe, pc_start, index, p_offset,
  1741. pika_false);
  1742. }
  1743. char* _find_super_class_name(ByteCodeFrame* bcframe, int32_t pc_start) {
  1744. /* find super class */
  1745. int32_t offset = 0;
  1746. char* super_class_name = NULL;
  1747. byteCodeFrame_findInsForward(bcframe, pc_start, PIKA_INS(CLS), &offset);
  1748. InstructUnit* unit_run = byteCodeFrame_findInsUnitBackward(
  1749. bcframe, pc_start, PIKA_INS(RUN), &offset);
  1750. super_class_name = constPool_getByOffset(
  1751. &(bcframe->const_pool), instructUnit_getConstPoolIndex(unit_run));
  1752. return super_class_name;
  1753. }
  1754. #if !PIKA_NANO_ENABLE
  1755. static char* _find_self_name(PikaVMFrame* vm) {
  1756. /* find super class */
  1757. int offset = 0;
  1758. char* self_name = NULL;
  1759. while (1) {
  1760. offset -= instructUnit_getSize();
  1761. if (vm->pc + offset >= (int)PikaVMFrame_getInstructArraySize(vm)) {
  1762. return 0;
  1763. }
  1764. if ((PIKA_INS(CLS) == PikaVMFrame_getInstructWithOffset(vm, offset))) {
  1765. break;
  1766. }
  1767. }
  1768. while (1) {
  1769. offset += instructUnit_getSize();
  1770. if (vm->pc + offset >= (int)PikaVMFrame_getInstructArraySize(vm)) {
  1771. return 0;
  1772. }
  1773. if ((PIKA_INS(OUT) ==
  1774. instructUnit_getInstructIndex(
  1775. PikaVMFrame_getInstructUnitWithOffset(vm, offset)))) {
  1776. self_name = PikaVMFrame_getConstWithOffset(vm, offset);
  1777. return self_name;
  1778. }
  1779. }
  1780. }
  1781. #endif
  1782. PikaObj* New_builtins_object(Args* args);
  1783. static Arg* _VM_instruction_eval(PikaObj* self,
  1784. PikaVMFrame* vm,
  1785. char* sRunPath,
  1786. pika_bool* bIsEval) {
  1787. Arg* aReturn = NULL;
  1788. Args buffs = {0};
  1789. *bIsEval = pika_false;
  1790. if (sRunPath[0] != 'e') {
  1791. return NULL;
  1792. }
  1793. if (!strEqu(sRunPath, "eval") && !strEqu(sRunPath, "exec")) {
  1794. return NULL;
  1795. }
  1796. /* eval || exec */
  1797. *bIsEval = pika_true;
  1798. ByteCodeFrame bcFrame = {0};
  1799. /* generate byte code */
  1800. byteCodeFrame_init(&bcFrame);
  1801. Arg* aCode = stack_popArg_alloc(&(vm->stack));
  1802. char* sCode = arg_getStr(aCode);
  1803. char* sCmd = strsAppend(&buffs, "@res = ", sCode);
  1804. if (PIKA_RES_OK != pika_lines2Bytes(&bcFrame, sCmd)) {
  1805. PikaVMFrame_setSysOut(vm, PIKA_ERR_STRING_SYNTAX_ERROR);
  1806. aReturn = NULL;
  1807. goto __exit;
  1808. }
  1809. _pikaVM_runByteCodeFrameWithState(self, vm->locals, vm->globals, &bcFrame,
  1810. 0, vm->vm_thread);
  1811. aReturn = obj_getArg(vm->locals, "@res");
  1812. if (NULL == aReturn) {
  1813. aReturn = obj_getArg(vm->globals, "@res");
  1814. }
  1815. if (strEqu(sRunPath, "eval")) {
  1816. aReturn = arg_copy(aReturn);
  1817. }
  1818. goto __exit;
  1819. __exit:
  1820. byteCodeFrame_deinit(&bcFrame);
  1821. arg_deinit(aCode);
  1822. strsDeinit(&buffs);
  1823. return aReturn;
  1824. }
  1825. static Arg* VM_instruction_handler_RUN(PikaObj* self,
  1826. PikaVMFrame* vm,
  1827. char* data,
  1828. Arg* aReturnRegistor) {
  1829. Arg* aReturn = NULL;
  1830. VMParameters* oSublocals = NULL;
  1831. VMParameters* oSublocalsInit = NULL;
  1832. char* sRunPath = data;
  1833. char* sArgName = NULL;
  1834. char* sProxyName = NULL;
  1835. PikaObj* oMethodHost = NULL;
  1836. PikaObj* oThis = NULL;
  1837. Arg* aMethod = NULL;
  1838. Arg* aStack = NULL;
  1839. pika_bool bIsTemp = pika_false;
  1840. pika_bool bSkipInit = pika_false;
  1841. pika_bool bIsEval = pika_false;
  1842. int iNumUsed = 0;
  1843. PikaObj* oBuiltin = NULL;
  1844. arg_newReg(arg_reg1, 32);
  1845. pika_assert(NULL != vm->vm_thread);
  1846. if (NULL != sRunPath) {
  1847. sArgName = strPointToLastToken(sRunPath, '.');
  1848. }
  1849. /* inhert */
  1850. if (vm->pc - 2 * (int)instructUnit_getSize() >= 0) {
  1851. if (PIKA_INS(CLS) == PikaVMFrame_getInstructWithOffset(
  1852. vm, -2 * (int)instructUnit_getSize())) {
  1853. bSkipInit = pika_true;
  1854. }
  1855. }
  1856. /* tuple or single arg */
  1857. if (NULL == sRunPath || sRunPath[0] == 0) {
  1858. if (PikaVMFrame_getInputArgNum(vm) == 1) {
  1859. /* return arg directly */
  1860. aReturn = stack_popArg(&(vm->stack), aReturnRegistor);
  1861. goto __exit;
  1862. }
  1863. /* create a tuple */
  1864. aReturn = _vm_create_list_or_tuple(self, vm, pika_false);
  1865. goto __exit;
  1866. }
  1867. #if !PIKA_NANO_ENABLE
  1868. /* support for super() */
  1869. if (strEqu(sRunPath, "super")) {
  1870. sRunPath = _find_super_class_name(vm->bytecode_frame, vm->pc);
  1871. sArgName = strPointToLastToken(sRunPath, '.');
  1872. vm->in_super = pika_true;
  1873. vm->super_invoke_deepth = PikaVMFrame_getInvokeDeepthNow(vm);
  1874. bSkipInit = pika_true;
  1875. }
  1876. #endif
  1877. /* return tiny obj */
  1878. if (strEqu(sRunPath, "TinyObj")) {
  1879. aReturn = arg_newMetaObj(New_builtins_object);
  1880. if (NULL != aReturn) {
  1881. goto __exit;
  1882. }
  1883. }
  1884. /* eval and exec */
  1885. aReturn = _VM_instruction_eval(self, vm, sRunPath, &bIsEval);
  1886. if (bIsEval) {
  1887. goto __exit;
  1888. }
  1889. /* get method host obj from reg */
  1890. if (NULL == oMethodHost) {
  1891. oMethodHost = Locals_getLReg(vm->locals, sRunPath);
  1892. }
  1893. #if !PIKA_NANO_ENABLE
  1894. /* get method host obj from stack */
  1895. if (NULL == oMethodHost && sRunPath[0] == '.') {
  1896. /* get method host obj from stack */
  1897. Arg** stack_tmp = (Arg**)pikaMalloc(sizeof(Arg*) * PIKA_ARG_NUM_MAX);
  1898. uint32_t n_arg = PikaVMFrame_getInputArgNum(vm);
  1899. if (n_arg > PIKA_ARG_NUM_MAX) {
  1900. pika_platform_printf(
  1901. "[ERROR] Too many args in RUN instruction, please use "
  1902. "bigger "
  1903. "#define PIKA_ARG_NUM_MAX\n");
  1904. pika_platform_panic_handle();
  1905. }
  1906. for (int i = 0; i < n_arg; i++) {
  1907. stack_tmp[i] = stack_popArg_alloc(&(vm->stack));
  1908. }
  1909. aStack = stack_tmp[n_arg - 1];
  1910. if (sRunPath[1] == '\0') {
  1911. /* for .(...) */
  1912. aMethod = aStack;
  1913. pika_assert(arg_isCallable(aMethod));
  1914. } else {
  1915. /* for .xxx(...) */
  1916. oMethodHost = _arg_to_obj(aStack, &bIsTemp);
  1917. pika_assert(NULL != oMethodHost);
  1918. }
  1919. if (NULL != aStack) {
  1920. iNumUsed++;
  1921. }
  1922. /* push back other args to stack */
  1923. for (int i = n_arg - 2; i >= 0; i--) {
  1924. stack_pushArg(&(vm->stack), stack_tmp[i]);
  1925. }
  1926. pikaFree(stack_tmp, sizeof(Arg*) * PIKA_ARG_NUM_MAX);
  1927. }
  1928. #endif
  1929. /* use RunAs object */
  1930. if (obj_getFlag(vm->locals, OBJ_FLAG_RUN_AS)) {
  1931. PikaObj* oContext = args_getPtr(vm->locals->list, "@r");
  1932. oMethodHost = obj_getHostObjWithIsTemp(oContext, sRunPath, &bIsTemp);
  1933. }
  1934. /* get method host obj from local scope */
  1935. if (NULL == oMethodHost) {
  1936. oMethodHost = obj_getHostObjWithIsTemp(vm->locals, sRunPath, &bIsTemp);
  1937. }
  1938. /* get method host obj from global scope */
  1939. if (NULL == oMethodHost) {
  1940. oMethodHost = obj_getHostObjWithIsTemp(vm->globals, sRunPath, &bIsTemp);
  1941. }
  1942. /* method host obj is not found */
  1943. if (NULL == oMethodHost) {
  1944. /* error, not found object */
  1945. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_ARG_NO_FOUND);
  1946. PikaVMFrame_setSysOut(vm, "Error: method '%s' no found.", sRunPath);
  1947. goto __exit;
  1948. }
  1949. pika_assert(obj_checkAlive(oMethodHost));
  1950. #if !PIKA_NANO_ENABLE
  1951. if (!bSkipInit && vm->in_super &&
  1952. PikaVMFrame_getInvokeDeepthNow(vm) == vm->super_invoke_deepth - 1) {
  1953. vm->in_super = pika_false;
  1954. oThis = obj_getPtr(vm->locals, _find_self_name(vm));
  1955. }
  1956. #endif
  1957. /* get object this */
  1958. if (NULL == oThis) {
  1959. oThis = oMethodHost;
  1960. }
  1961. /* get method in object */
  1962. if (NULL == aMethod) {
  1963. aMethod = obj_getMethodArg_noalloc(oMethodHost, sArgName, &arg_reg1);
  1964. }
  1965. if (sArgName == sRunPath) {
  1966. /* find method in locals */
  1967. if (NULL == aMethod) {
  1968. aMethod = obj_getMethodArg_noalloc(vm->locals, sArgName, &arg_reg1);
  1969. }
  1970. /* find method in global */
  1971. if (NULL == aMethod) {
  1972. aMethod =
  1973. obj_getMethodArg_noalloc(vm->globals, sArgName, &arg_reg1);
  1974. if (aMethod != NULL) {
  1975. oThis = vm->globals;
  1976. }
  1977. }
  1978. /* find method in builtin */
  1979. if (NULL == aMethod) {
  1980. oBuiltin = obj_getBuiltins();
  1981. aMethod = obj_getMethodArg_noalloc(oBuiltin, sArgName, &arg_reg1);
  1982. if (aMethod != NULL) {
  1983. oThis = oBuiltin;
  1984. }
  1985. }
  1986. }
  1987. if (NULL == aMethod) {
  1988. /* get proxy method */
  1989. if (obj_getFlag(oMethodHost, OBJ_FLAG_PROXY_METHOD)) {
  1990. if (strCountSign(sArgName, '.') == 0) {
  1991. /* __proxy__ takes the first arg as the method name */
  1992. sProxyName = sArgName;
  1993. sArgName = "__proxy__";
  1994. aMethod =
  1995. obj_getMethodArg_noalloc(oMethodHost, sArgName, &arg_reg1);
  1996. }
  1997. }
  1998. }
  1999. /* assert method exist */
  2000. if (NULL == aMethod || ARG_TYPE_NONE == arg_getType(aMethod)) {
  2001. /* error, method no found */
  2002. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_ARG_NO_FOUND);
  2003. PikaVMFrame_setSysOut(vm, "NameError: name '%s' is not defined",
  2004. sRunPath);
  2005. goto __exit;
  2006. }
  2007. /* assert methodd type */
  2008. if (!argType_isCallable(arg_getType(aMethod))) {
  2009. /* error, method no found */
  2010. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_ARG_NO_FOUND);
  2011. PikaVMFrame_setSysOut(vm, "TypeError: '%s' object is not callable",
  2012. sRunPath);
  2013. goto __exit;
  2014. }
  2015. /* create sub local scope */
  2016. oSublocals = New_Locals(NULL);
  2017. oThis->vmFrame = vm;
  2018. /* load args from PikaVMFrame to sub_local->list */
  2019. iNumUsed += PikaVMFrame_loadArgsFromMethodArg(
  2020. vm, oThis, oSublocals->list, aMethod, sRunPath, sProxyName, iNumUsed);
  2021. /* load args failed */
  2022. if (pikaVMFrame_checkErrorStack(vm) != PIKA_RES_OK) {
  2023. goto __exit;
  2024. }
  2025. /* run method arg */
  2026. aReturn = obj_runMethodArgWithState_noalloc(oThis, oSublocals, aMethod,
  2027. vm->vm_thread, aReturnRegistor);
  2028. if (bSkipInit) {
  2029. if (arg_getType(aReturn) == ARG_TYPE_OBJECT_NEW) {
  2030. pika_assert(NULL != aReturn);
  2031. arg_setType(aReturn, ARG_TYPE_OBJECT);
  2032. }
  2033. }
  2034. if (vm->vm_thread->try_result != TRY_RESULT_NONE) {
  2035. /* try result */
  2036. vm->error.code = vm->vm_thread->try_result;
  2037. }
  2038. /* __init__() */
  2039. if (NULL != aReturn && ARG_TYPE_OBJECT_NEW == arg_getType(aReturn)) {
  2040. pika_assert(NULL != aReturn);
  2041. arg_setType(aReturn, ARG_TYPE_OBJECT);
  2042. /* init object */
  2043. PikaObj* oNew = arg_getPtr(aReturn);
  2044. obj_setName(oNew, sRunPath);
  2045. Arg* aMethod =
  2046. obj_getMethodArgWithFullPath_noalloc(oNew, "__init__", &arg_reg1);
  2047. oSublocalsInit = New_Locals(NULL);
  2048. Arg* aReturnInit = NULL;
  2049. if (NULL == aMethod) {
  2050. goto __init_exit;
  2051. }
  2052. PikaVMFrame_loadArgsFromMethodArg(vm, oNew, oSublocalsInit->list,
  2053. aMethod, "__init__", NULL, iNumUsed);
  2054. /* load args failed */
  2055. if (pikaVMFrame_checkErrorStack(vm) != PIKA_RES_OK) {
  2056. goto __init_exit;
  2057. }
  2058. aReturnInit = obj_runMethodArgWithState(oNew, oSublocalsInit, aMethod,
  2059. vm->vm_thread);
  2060. __init_exit:
  2061. if (NULL != aReturnInit) {
  2062. arg_deinit(aReturnInit);
  2063. }
  2064. #if PIKA_GC_MARK_SWEEP_ENABLE
  2065. pika_assert(obj_getFlag(oSublocals, OBJ_FLAG_GC_ROOT));
  2066. #endif
  2067. obj_deinit(oSublocalsInit);
  2068. if (NULL != aMethod) {
  2069. arg_deinit(aMethod);
  2070. }
  2071. }
  2072. goto __exit;
  2073. __exit:
  2074. if (NULL != aMethod) {
  2075. arg_deinit(aMethod);
  2076. }
  2077. if (NULL != oSublocals) {
  2078. #if PIKA_GC_MARK_SWEEP_ENABLE
  2079. pika_assert(obj_getFlag(oSublocals, OBJ_FLAG_GC_ROOT));
  2080. #endif
  2081. obj_deinit(oSublocals);
  2082. }
  2083. if (NULL != oBuiltin) {
  2084. obj_deinit(oBuiltin);
  2085. }
  2086. if (NULL != aStack && aMethod != aStack) {
  2087. arg_deinit(aStack);
  2088. }
  2089. if (NULL != oMethodHost && bIsTemp) {
  2090. /* class method */
  2091. obj_GC(oMethodHost);
  2092. }
  2093. pika_assert_arg_alive(aReturn);
  2094. return aReturn;
  2095. }
  2096. static Arg* VM_instruction_handler_STR(PikaObj* self,
  2097. PikaVMFrame* vm,
  2098. char* data,
  2099. Arg* arg_ret_reg) {
  2100. if (NULL == data) {
  2101. return arg_setStr(arg_ret_reg, "", "");
  2102. }
  2103. if (strIsContain(data, '\\')) {
  2104. Args buffs = {0};
  2105. size_t i_out = 0;
  2106. char* transfered_str = strsTransfer(&buffs, data, &i_out);
  2107. Arg* return_arg = arg_ret_reg;
  2108. return_arg = arg_setStr(return_arg, "", transfered_str);
  2109. strsDeinit(&buffs);
  2110. return return_arg;
  2111. }
  2112. return arg_setStr(arg_ret_reg, "", data);
  2113. }
  2114. static Arg* VM_instruction_handler_BYT(PikaObj* self,
  2115. PikaVMFrame* vm,
  2116. char* data,
  2117. Arg* arg_ret_reg) {
  2118. if (strIsContain(data, '\\')) {
  2119. Args buffs = {0};
  2120. size_t i_out = 0;
  2121. char* transfered_str = strsTransfer(&buffs, data, &i_out);
  2122. Arg* return_arg = New_arg(NULL);
  2123. return_arg =
  2124. arg_setBytes(return_arg, "", (uint8_t*)transfered_str, i_out);
  2125. strsDeinit(&buffs);
  2126. return return_arg;
  2127. }
  2128. return arg_newBytes((uint8_t*)data, strGetSize(data));
  2129. }
  2130. static pika_bool _proxy_setattr(PikaObj* self, char* name, Arg* arg) {
  2131. #if PIKA_NANO_ENABLE
  2132. return pika_false;
  2133. #endif
  2134. if (obj_getFlag(self, OBJ_FLAG_PROXY_SETATTR)) {
  2135. obj_setStr(self, "@name", name);
  2136. obj_setArg_noCopy(self, "@value", arg);
  2137. /* clang-format off */
  2138. PIKA_PYTHON(
  2139. __setattr__(@name, @value)
  2140. )
  2141. /* clang-format on */
  2142. const uint8_t bytes[] = {
  2143. 0x0c, 0x00, 0x00, 0x00, /* instruct array size */
  2144. 0x10, 0x81, 0x01, 0x00, 0x10, 0x01, 0x07, 0x00, 0x00, 0x02, 0x0e,
  2145. 0x00,
  2146. /* instruct array */
  2147. 0x1a, 0x00, 0x00, 0x00, /* const pool size */
  2148. 0x00, 0x40, 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x40, 0x76, 0x61, 0x6c,
  2149. 0x75, 0x65, 0x00, 0x5f, 0x5f, 0x73, 0x65, 0x74, 0x61, 0x74, 0x74,
  2150. 0x72, 0x5f, 0x5f, 0x00, /* const pool */
  2151. };
  2152. pikaVM_runByteCode(self, (uint8_t*)bytes);
  2153. return pika_true;
  2154. }
  2155. return pika_false;
  2156. }
  2157. static Arg* VM_instruction_handler_OUT(PikaObj* self,
  2158. PikaVMFrame* vm,
  2159. char* data,
  2160. Arg* aRetReg) {
  2161. char* sArgPath = data;
  2162. pika_assert(sArgPath != NULL);
  2163. char* sArgName = strPointToLastToken(sArgPath, '.');
  2164. PikaObj* oHost = NULL;
  2165. pika_bool bIsTemp = pika_false;
  2166. arg_newReg(aOutReg, PIKA_ARG_BUFF_SIZE);
  2167. PIKA_RES res = PIKA_RES_OK;
  2168. Arg* aOut = stack_popArg(&vm->stack, &aOutReg);
  2169. if (NULL == aOut) {
  2170. goto __exit;
  2171. }
  2172. ArgType eOutArgType = arg_getType(aOut);
  2173. if (PikaVMFrame_getInvokeDeepthNow(vm) > 0) {
  2174. /* in block, is a kw arg */
  2175. arg_setIsKeyword(aOut, pika_true);
  2176. arg_setName(aOut, sArgPath);
  2177. Arg* res = arg_copy_noalloc(aOut, aRetReg);
  2178. arg_deinit(aOut);
  2179. return res;
  2180. }
  2181. if (_checkLReg(sArgPath)) {
  2182. if (argType_isObject(eOutArgType)) {
  2183. PikaObj* obj = arg_getPtr(aOut);
  2184. Locals_setLReg(vm->locals, sArgPath, obj);
  2185. arg_deinit(aOut);
  2186. }
  2187. goto __exit;
  2188. }
  2189. PikaObj* oContext = vm->locals;
  2190. /* match global_list */
  2191. if (obj_getFlag(vm->locals, OBJ_FLAG_GLOBALS)) {
  2192. char* sGlobalList = args_getStr(vm->locals->list, "@g");
  2193. /* use a arg as buff */
  2194. Arg* aGlobalList = arg_newStr(sGlobalList);
  2195. char* sGlobalListBuff = arg_getStr(aGlobalList);
  2196. /* for each arg arg in global_list */
  2197. for (int i = 0; i < strCountSign(sGlobalList, ',') + 1; i++) {
  2198. char* sGlobalArg = strPopFirstToken(&sGlobalListBuff, ',');
  2199. /* matched global arg, context set to global */
  2200. if (strEqu(sGlobalArg, sArgPath)) {
  2201. oContext = vm->globals;
  2202. }
  2203. }
  2204. arg_deinit(aGlobalList);
  2205. }
  2206. /* use RunAs object */
  2207. if (obj_getFlag(vm->locals, OBJ_FLAG_RUN_AS)) {
  2208. oContext = args_getPtr(vm->locals->list, "@r");
  2209. }
  2210. /* set free object to nomal object */
  2211. if (ARG_TYPE_OBJECT_NEW == eOutArgType) {
  2212. pika_assert(NULL != aOut);
  2213. arg_setType(aOut, ARG_TYPE_OBJECT);
  2214. }
  2215. /* ouput arg to context */
  2216. if (sArgPath == sArgName) {
  2217. res = obj_setArg_noCopy(oContext, sArgPath, aOut);
  2218. goto __exit;
  2219. }
  2220. oHost = obj_getHostObjWithIsTemp(oContext, sArgPath, &bIsTemp);
  2221. if (NULL == oHost) {
  2222. oHost = obj_getHostObjWithIsTemp(vm->globals, sArgPath, &bIsTemp);
  2223. }
  2224. if (oHost != NULL) {
  2225. if (_proxy_setattr(oHost, sArgName, aOut)) {
  2226. goto __exit;
  2227. }
  2228. res = obj_setArg_noCopy(oHost, sArgName, aOut);
  2229. goto __exit;
  2230. }
  2231. res = obj_setArg_noCopy(oContext, sArgPath, aOut);
  2232. __exit:
  2233. if (res != PIKA_RES_OK) {
  2234. PikaVMFrame_setErrorCode(vm, res);
  2235. PikaVMFrame_setSysOut(vm, "Error: can't set '%s'", sArgPath);
  2236. }
  2237. return NULL;
  2238. }
  2239. /* run as */
  2240. static Arg* VM_instruction_handler_RAS(PikaObj* self,
  2241. PikaVMFrame* vm,
  2242. char* data,
  2243. Arg* arg_ret_reg) {
  2244. if (strEqu(data, "$origin")) {
  2245. /* use origin object to run */
  2246. obj_removeArg(vm->locals, "@r");
  2247. obj_clearFlag(vm->locals, OBJ_FLAG_RUN_AS);
  2248. return NULL;
  2249. }
  2250. /* use "data" object to run */
  2251. PikaObj* runAs = obj_getObj(vm->locals, data);
  2252. args_setRef(vm->locals->list, "@r", runAs);
  2253. obj_setFlag(vm->locals, OBJ_FLAG_RUN_AS);
  2254. return NULL;
  2255. }
  2256. static Arg* VM_instruction_handler_NUM(PikaObj* self,
  2257. PikaVMFrame* vm,
  2258. char* data,
  2259. Arg* arg_ret_reg) {
  2260. /* fast return */
  2261. if (data[1] == '\0') {
  2262. return arg_setInt(arg_ret_reg, "", data[0] - '0');
  2263. }
  2264. /* hex */
  2265. if (data[1] == 'x' || data[1] == 'X') {
  2266. return arg_setInt(arg_ret_reg, "", strtoll(data, NULL, 0));
  2267. }
  2268. if (data[1] == 'o' || data[1] == 'O') {
  2269. char strtoll_buff[10] = {0};
  2270. strtoll_buff[0] = '0';
  2271. pika_platform_memcpy(strtoll_buff + 1, data + 2, strGetSize(data) - 2);
  2272. return arg_setInt(arg_ret_reg, "", strtoll(strtoll_buff, NULL, 0));
  2273. }
  2274. if (data[1] == 'b' || data[1] == 'B') {
  2275. char strtoll_buff[10] = {0};
  2276. pika_platform_memcpy(strtoll_buff, data + 2, strGetSize(data) - 2);
  2277. return arg_setInt(arg_ret_reg, "", strtoll(strtoll_buff, NULL, 2));
  2278. }
  2279. /* float */
  2280. if (strIsContain(data, '.') ||
  2281. (strIsContain(data, 'e') || strIsContain(data, 'E'))) {
  2282. return arg_setFloat(arg_ret_reg, "", strtod(data, NULL));
  2283. }
  2284. /* int */
  2285. int64_t i64 = 0;
  2286. if (PIKA_RES_OK != fast_atoi_safe(data, &i64)) {
  2287. PikaVMFrame_setSysOut(vm, "ValueError: invalid literal for int(): '%s'",
  2288. data);
  2289. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2290. return NULL;
  2291. }
  2292. return arg_setInt(arg_ret_reg, "", i64);
  2293. }
  2294. static Arg* VM_instruction_handler_JMP(PikaObj* self,
  2295. PikaVMFrame* vm,
  2296. char* data,
  2297. Arg* arg_ret_reg) {
  2298. vm->jmp = fast_atoi(data);
  2299. return NULL;
  2300. }
  2301. static Arg* VM_instruction_handler_SER(PikaObj* self,
  2302. PikaVMFrame* vm,
  2303. char* data,
  2304. Arg* arg_ret_reg) {
  2305. PikaVMError error = {0};
  2306. error.code = fast_atoi(data);
  2307. pikaVMThread_pushError(vm->vm_thread, &error);
  2308. return NULL;
  2309. }
  2310. static Arg* _VM_JEZ(PikaObj* self,
  2311. PikaVMFrame* vm,
  2312. char* data,
  2313. Arg* arg_ret_reg,
  2314. int bAssert) {
  2315. int thisBlockDeepth = PikaVMFrame_getBlockDeepthNow(vm);
  2316. int jmp_expect = fast_atoi(data);
  2317. vm->ireg[thisBlockDeepth] = (pika_bool)!bAssert;
  2318. if (0 == bAssert) {
  2319. /* jump */
  2320. vm->jmp = jmp_expect;
  2321. }
  2322. /* restore loop deepth */
  2323. if (2 == jmp_expect && 0 == bAssert) {
  2324. int block_deepth_now = PikaVMFrame_getBlockDeepthNow(vm);
  2325. vm->loop_deepth = block_deepth_now;
  2326. }
  2327. return NULL;
  2328. }
  2329. static Arg* VM_instruction_handler_JEZ(PikaObj* self,
  2330. PikaVMFrame* vm,
  2331. char* data,
  2332. Arg* arg_ret_reg) {
  2333. Arg* aAssert = stack_popArg(&(vm->stack), arg_ret_reg);
  2334. pika_bool bAssert = 0;
  2335. if (NULL != aAssert) {
  2336. PIKA_RES res = _transeBool(aAssert, &bAssert);
  2337. if (PIKA_RES_OK != res) {
  2338. bAssert = 0;
  2339. }
  2340. arg_deinit(aAssert);
  2341. }
  2342. return _VM_JEZ(self, vm, data, arg_ret_reg, bAssert);
  2343. }
  2344. static Arg* VM_instruction_handler_JNZ(PikaObj* self,
  2345. PikaVMFrame* vm,
  2346. char* data,
  2347. Arg* arg_ret_reg) {
  2348. Arg* aAssert = stack_popArg(&(vm->stack), arg_ret_reg);
  2349. pika_bool bAssert = 0;
  2350. if (NULL != aAssert) {
  2351. PIKA_RES res = _transeBool(aAssert, &bAssert);
  2352. if (PIKA_RES_OK != res) {
  2353. bAssert = 0;
  2354. }
  2355. arg_deinit(aAssert);
  2356. }
  2357. return _VM_JEZ(self, vm, data, arg_ret_reg, !bAssert);
  2358. }
  2359. static uint32_t PikaVMFrame_getInputArgNum(PikaVMFrame* vm) {
  2360. InstructUnit* ins_unit_now = PikaVMFrame_getInstructNow(vm);
  2361. uint8_t invoke_deepth_this = instructUnit_getInvokeDeepth(ins_unit_now);
  2362. int32_t pc_this = vm->pc;
  2363. uint32_t num = 0;
  2364. while (1) {
  2365. ins_unit_now--;
  2366. pc_this -= instructUnit_getSize();
  2367. uint8_t invode_deepth = instructUnit_getInvokeDeepth(ins_unit_now);
  2368. if (pc_this < 0) {
  2369. break;
  2370. }
  2371. if (invode_deepth == invoke_deepth_this + 1) {
  2372. if (instructUnit_getInstructIndex(ins_unit_now) == PIKA_INS(OUT)) {
  2373. continue;
  2374. }
  2375. if (instructUnit_getInstructIndex(ins_unit_now) == PIKA_INS(NLS)) {
  2376. continue;
  2377. }
  2378. num++;
  2379. }
  2380. if (instructUnit_getIsNewLine(ins_unit_now)) {
  2381. break;
  2382. }
  2383. if (invode_deepth <= invoke_deepth_this) {
  2384. break;
  2385. }
  2386. }
  2387. return num;
  2388. }
  2389. int operatorInfo_init(OperatorInfo* info,
  2390. PikaObj* self,
  2391. PikaVMFrame* vm,
  2392. char* data,
  2393. Arg* arg_ret_reg) {
  2394. if (info->a1 == NULL && info->a2 == NULL) {
  2395. return -1;
  2396. }
  2397. info->opt = data;
  2398. info->res = arg_ret_reg;
  2399. if (info->a1 != NULL) {
  2400. info->t1 = arg_getType(info->a1);
  2401. if (info->t1 == ARG_TYPE_INT) {
  2402. info->i1 = arg_getInt(info->a1);
  2403. info->f1 = (pika_float)info->i1;
  2404. } else if (info->t1 == ARG_TYPE_FLOAT) {
  2405. info->f1 = arg_getFloat(info->a1);
  2406. info->i1 = (int64_t)info->f1;
  2407. } else if (info->t1 == ARG_TYPE_BOOL) {
  2408. info->i1 = arg_getBool(info->a1);
  2409. info->f1 = (pika_float)info->i1;
  2410. }
  2411. }
  2412. info->t2 = arg_getType(info->a2);
  2413. info->vm = vm;
  2414. if (info->t2 == ARG_TYPE_INT) {
  2415. info->i2 = arg_getInt(info->a2);
  2416. info->f2 = (pika_float)info->i2;
  2417. } else if (info->t2 == ARG_TYPE_FLOAT) {
  2418. info->f2 = arg_getFloat(info->a2);
  2419. info->i2 = (int64_t)info->f2;
  2420. } else if (info->t2 == ARG_TYPE_BOOL) {
  2421. info->i2 = arg_getBool(info->a2);
  2422. info->f2 = (pika_float)info->i2;
  2423. }
  2424. return 0;
  2425. }
  2426. static Arg* _OPT_Method_ex(PikaObj* host,
  2427. Arg* arg,
  2428. OperatorInfo* op,
  2429. char* method_name,
  2430. PIKA_RES err_no,
  2431. char* errinfo) {
  2432. Arg* method = obj_getMethodArgWithFullPath(host, method_name);
  2433. if (NULL == method) {
  2434. PikaVMFrame_setErrorCode(op->vm, err_no);
  2435. PikaVMFrame_setSysOut(op->vm, errinfo);
  2436. return NULL;
  2437. }
  2438. Arg* res = obj_runMethodArg1(host, method, arg_copy(arg));
  2439. return res;
  2440. }
  2441. static Arg* _OPT_Method(OperatorInfo* op,
  2442. char* method_name,
  2443. PIKA_RES err_no,
  2444. char* errinfo) {
  2445. PikaObj* obj1 = arg_getPtr(op->a1);
  2446. return _OPT_Method_ex(obj1, op->a2, op, method_name, err_no, errinfo);
  2447. }
  2448. static void _OPT_ADD(OperatorInfo* op) {
  2449. #if !PIKA_NANO_ENABLE
  2450. if (argType_isObject(op->t1)) {
  2451. if (!argType_isObject(op->t2)) {
  2452. PikaVMFrame_setErrorCode(op->vm, PIKA_RES_ERR_OPERATION_FAILED);
  2453. PikaVMFrame_setSysOut(op->vm, "TypeError: unsupported operand +");
  2454. op->res = NULL;
  2455. return;
  2456. }
  2457. op->res = _OPT_Method(op, "__add__", PIKA_RES_ERR_OPERATION_FAILED,
  2458. "TypeError: unsupported operand +");
  2459. return;
  2460. }
  2461. #endif
  2462. // Check if either argument is a string and the other is not a string
  2463. if ((op->t1 == ARG_TYPE_STRING && op->t2 != ARG_TYPE_STRING) ||
  2464. (op->t2 == ARG_TYPE_STRING && op->t1 != ARG_TYPE_STRING)) {
  2465. PikaVMFrame_setErrorCode(op->vm, PIKA_RES_ERR_OPERATION_FAILED);
  2466. PikaVMFrame_setSysOut(
  2467. op->vm, "TypeError: unsupported operand + between str and non-str");
  2468. op->res = NULL;
  2469. return;
  2470. }
  2471. if ((op->t1 == ARG_TYPE_STRING) && (op->t2 == ARG_TYPE_STRING)) {
  2472. char* num1_s = NULL;
  2473. char* num2_s = NULL;
  2474. Args str_opt_buffs = {0};
  2475. num1_s = arg_getStr(op->a1);
  2476. num2_s = arg_getStr(op->a2);
  2477. char* opt_str_out = strsAppend(&str_opt_buffs, num1_s, num2_s);
  2478. op->res = arg_setStr(op->res, "", opt_str_out);
  2479. strsDeinit(&str_opt_buffs);
  2480. return;
  2481. }
  2482. #if !PIKA_NANO_ENABLE
  2483. if ((op->t1 == ARG_TYPE_BYTES) && (op->t2 == ARG_TYPE_BYTES)) {
  2484. uint8_t* bytes1 = arg_getBytes(op->a1);
  2485. uint8_t* bytes2 = arg_getBytes(op->a2);
  2486. size_t size1 = arg_getBytesSize(op->a1);
  2487. size_t size2 = arg_getBytesSize(op->a2);
  2488. op->res = arg_setBytes(op->res, "", NULL, size1 + size2);
  2489. uint8_t* bytes_out = arg_getBytes(op->res);
  2490. pika_platform_memcpy(bytes_out, bytes1, size1);
  2491. pika_platform_memcpy(bytes_out + size1, bytes2, size2);
  2492. return;
  2493. }
  2494. #endif
  2495. /* match float */
  2496. if ((op->t1 == ARG_TYPE_FLOAT) || op->t2 == ARG_TYPE_FLOAT) {
  2497. op->res = arg_setFloat(op->res, "", op->f1 + op->f2);
  2498. return;
  2499. }
  2500. /* int is default */
  2501. op->res = arg_setInt(op->res, "", op->i1 + op->i2);
  2502. return;
  2503. }
  2504. static void _OPT_SUB(OperatorInfo* op) {
  2505. #if !PIKA_NANO_ENABLE
  2506. if (argType_isObject(op->t1)) {
  2507. if (!argType_isObject(op->t2)) {
  2508. PikaVMFrame_setErrorCode(op->vm, PIKA_RES_ERR_OPERATION_FAILED);
  2509. PikaVMFrame_setSysOut(op->vm, "TypeError: unsupported operand +");
  2510. op->res = NULL;
  2511. return;
  2512. }
  2513. op->res = _OPT_Method(op, "__sub__", PIKA_RES_ERR_OPERATION_FAILED,
  2514. "TypeError: unsupported operand -");
  2515. return;
  2516. }
  2517. #endif
  2518. if (op->t2 == ARG_TYPE_NONE) {
  2519. if (op->t1 == ARG_TYPE_INT) {
  2520. op->res = arg_setInt(op->res, "", -op->i1);
  2521. return;
  2522. }
  2523. if (op->t1 == ARG_TYPE_FLOAT) {
  2524. op->res = arg_setFloat(op->res, "", -op->f1);
  2525. return;
  2526. }
  2527. }
  2528. if ((op->t1 == ARG_TYPE_FLOAT) || op->t2 == ARG_TYPE_FLOAT) {
  2529. op->res = arg_setFloat(op->res, "", op->f1 - op->f2);
  2530. return;
  2531. }
  2532. op->res = arg_setInt(op->res, "", op->i1 - op->i2);
  2533. return;
  2534. }
  2535. static void _OPT_EQU(OperatorInfo* op) {
  2536. int8_t is_equ = -1;
  2537. if (op->t1 == ARG_TYPE_NONE && op->t2 == ARG_TYPE_NONE) {
  2538. is_equ = 1;
  2539. goto __exit;
  2540. }
  2541. /* type not equl, and type is not int or float or bool*/
  2542. if (!argType_isEqual(op->t1, op->t2)) {
  2543. if ((op->t1 != ARG_TYPE_FLOAT) && (op->t1 != ARG_TYPE_INT) &&
  2544. (op->t1 != ARG_TYPE_BOOL)) {
  2545. is_equ = 0;
  2546. goto __exit;
  2547. }
  2548. if ((op->t2 != ARG_TYPE_FLOAT) && (op->t2 != ARG_TYPE_INT) &&
  2549. (op->t2 != ARG_TYPE_BOOL)) {
  2550. is_equ = 0;
  2551. goto __exit;
  2552. }
  2553. }
  2554. /* string compire */
  2555. if (op->t1 == ARG_TYPE_STRING) {
  2556. is_equ = strEqu(arg_getStr(op->a1), arg_getStr(op->a2));
  2557. goto __exit;
  2558. }
  2559. /* bytes compire */
  2560. if (op->t1 == ARG_TYPE_BYTES) {
  2561. if (arg_getBytesSize(op->a1) != arg_getBytesSize(op->a2)) {
  2562. is_equ = 0;
  2563. goto __exit;
  2564. }
  2565. is_equ = 1;
  2566. for (size_t i = 0; i < arg_getBytesSize(op->a1); i++) {
  2567. if (arg_getBytes(op->a1)[i] != arg_getBytes(op->a2)[i]) {
  2568. is_equ = 0;
  2569. goto __exit;
  2570. }
  2571. }
  2572. goto __exit;
  2573. }
  2574. if (argType_isCallable(op->t1) && argType_isCallable(op->t2)) {
  2575. is_equ = (arg_getPtr(op->a1) == arg_getPtr(op->a2));
  2576. goto __exit;
  2577. }
  2578. if (argType_isObject(op->t1) && argType_isObject(op->t2)) {
  2579. is_equ = (arg_getPtr(op->a1) == arg_getPtr(op->a2));
  2580. if (is_equ) {
  2581. goto __exit;
  2582. }
  2583. Arg* __eq__ =
  2584. obj_getMethodArgWithFullPath(arg_getPtr(op->a1), "__eq__");
  2585. if (NULL == __eq__) {
  2586. goto __exit;
  2587. }
  2588. arg_deinit(__eq__);
  2589. Arg* res = _OPT_Method(op, "__eq__", PIKA_RES_ERR_OPERATION_FAILED,
  2590. "TypeError: unsupported operand ==");
  2591. if (NULL == res) {
  2592. is_equ = 0;
  2593. goto __exit;
  2594. }
  2595. is_equ = arg_getBool(res);
  2596. arg_deinit(res);
  2597. goto __exit;
  2598. }
  2599. /* default: int bool, and float */
  2600. is_equ = ((op->f1 - op->f2) * (op->f1 - op->f2) < (pika_float)0.000001);
  2601. goto __exit;
  2602. __exit:
  2603. if (op->opt[0] == '=') {
  2604. op->res = arg_setBool(op->res, "", is_equ);
  2605. } else {
  2606. op->res = arg_setBool(op->res, "", !is_equ);
  2607. }
  2608. return;
  2609. }
  2610. static void _OPT_POW(OperatorInfo* op) {
  2611. if (op->num == 1) {
  2612. op->res = arg_copy(op->a2);
  2613. arg_setIsDoubleStarred(op->res, 1);
  2614. return;
  2615. }
  2616. if (op->t1 == ARG_TYPE_INT && op->t2 == ARG_TYPE_INT) {
  2617. int lhs = op->i1;
  2618. int rhs = op->i2;
  2619. if (rhs < 0)
  2620. rhs = -rhs;
  2621. int64_t ret = 1;
  2622. while (rhs) {
  2623. if (rhs & 1)
  2624. ret *= lhs;
  2625. lhs *= lhs;
  2626. rhs >>= 1;
  2627. }
  2628. if (op->i2 < 0) {
  2629. op->res = arg_setFloat(op->res, "", 1.0 / ret);
  2630. } else {
  2631. op->res = arg_setInt(op->res, "", ret);
  2632. }
  2633. return;
  2634. }
  2635. if (op->t1 == ARG_TYPE_FLOAT && op->t2 == ARG_TYPE_INT) {
  2636. float res = 1;
  2637. for (int i = 0; i < op->i2; i++) {
  2638. res = res * op->f1;
  2639. }
  2640. op->res = arg_setFloat(op->res, "", res);
  2641. return;
  2642. }
  2643. #if PIKA_MATH_ENABLE
  2644. float res = 1;
  2645. res = pow(op->f1, op->f2);
  2646. op->res = arg_setFloat(op->res, "", res);
  2647. return;
  2648. #else
  2649. PikaVMFrame_setErrorCode(op->vm, PIKA_RES_ERR_OPERATION_FAILED);
  2650. PikaVMFrame_setSysOut(op->vm,
  2651. "Operation float ** float is not enabled, please set "
  2652. "PIKA_MATH_ENABLE");
  2653. #endif
  2654. }
  2655. static void _OPT_MUL(OperatorInfo* op) {
  2656. if (op->num == 1) {
  2657. op->res = arg_copy(op->a2);
  2658. arg_setIsStarred(op->res, 1);
  2659. return;
  2660. }
  2661. if ((op->t1 == ARG_TYPE_FLOAT) || op->t2 == ARG_TYPE_FLOAT) {
  2662. op->res = arg_setFloat(op->res, "", op->f1 * op->f2);
  2663. return;
  2664. }
  2665. if ((op->t1 == ARG_TYPE_STRING && op->t2 == ARG_TYPE_INT) ||
  2666. (op->t1 == ARG_TYPE_INT && op->t2 == ARG_TYPE_STRING)) {
  2667. char* str = NULL;
  2668. int64_t num = 0;
  2669. if (op->t1 == ARG_TYPE_STRING) {
  2670. str = arg_getStr(op->a1);
  2671. num = op->i2;
  2672. } else {
  2673. str = arg_getStr(op->a2);
  2674. num = op->i1;
  2675. }
  2676. Args str_opt_buffs = {0};
  2677. char* opt_str_out = strsRepeat(&str_opt_buffs, str, num);
  2678. op->res = arg_setStr(op->res, "", opt_str_out);
  2679. strsDeinit(&str_opt_buffs);
  2680. return;
  2681. }
  2682. if ((op->t1 == ARG_TYPE_BYTES && op->t2 == ARG_TYPE_INT) ||
  2683. (op->t1 == ARG_TYPE_INT && op->t2 == ARG_TYPE_BYTES)) {
  2684. uint8_t* bytes = NULL;
  2685. size_t size = 0;
  2686. int64_t num = 0;
  2687. if (op->t1 == ARG_TYPE_BYTES) {
  2688. bytes = arg_getBytes(op->a1);
  2689. size = arg_getBytesSize(op->a1);
  2690. num = op->i2;
  2691. } else {
  2692. bytes = arg_getBytes(op->a2);
  2693. size = arg_getBytesSize(op->a2);
  2694. num = op->i1;
  2695. }
  2696. op->res = arg_setBytes(op->res, "", NULL, size * num);
  2697. uint8_t* bytes_out = arg_getBytes(op->res);
  2698. for (int i = 0; i < num; i++) {
  2699. pika_platform_memcpy(bytes_out + i * size, bytes, size);
  2700. }
  2701. return;
  2702. }
  2703. if (argType_isObject(op->t1) || argType_isObject(op->t2)) {
  2704. Arg* __mul__ = NULL;
  2705. PikaObj* obj = NULL;
  2706. Arg* arg = NULL;
  2707. if (argType_isObject(op->t1)) {
  2708. __mul__ =
  2709. obj_getMethodArgWithFullPath(arg_getPtr(op->a1), "__mul__");
  2710. obj = arg_getPtr(op->a1);
  2711. arg = op->a2;
  2712. }
  2713. if (NULL == __mul__) {
  2714. if (argType_isObject(op->t2)) {
  2715. __mul__ =
  2716. obj_getMethodArgWithFullPath(arg_getPtr(op->a2), "__mul__");
  2717. obj = arg_getPtr(op->a2);
  2718. arg = op->a1;
  2719. }
  2720. }
  2721. if (NULL == __mul__) {
  2722. PikaVMFrame_setErrorCode(op->vm, PIKA_RES_ERR_OPERATION_FAILED);
  2723. PikaVMFrame_setSysOut(op->vm, "TypeError: unsupported operand *");
  2724. op->res = NULL;
  2725. return;
  2726. }
  2727. op->res = obj_runMethodArg1(obj, __mul__, arg_copy(arg));
  2728. return;
  2729. }
  2730. op->res = arg_setInt(op->res, "", op->i1 * op->i2);
  2731. return;
  2732. }
  2733. static Arg* VM_instruction_handler_OPT(PikaObj* self,
  2734. PikaVMFrame* vm,
  2735. char* data,
  2736. Arg* arg_ret_reg) {
  2737. OperatorInfo op = {0};
  2738. op.num = PikaVMFrame_getInputArgNum(vm);
  2739. arg_newReg(arg_reg1, PIKA_ARG_BUFF_SIZE);
  2740. arg_newReg(arg_reg2, PIKA_ARG_BUFF_SIZE);
  2741. if (op.num == 2) {
  2742. /* tow input */
  2743. op.a2 = stack_popArg(&(vm->stack), &arg_reg2);
  2744. op.a1 = stack_popArg(&(vm->stack), &arg_reg1);
  2745. } else if (op.num == 1) {
  2746. /* only one input */
  2747. op.a2 = stack_popArg(&(vm->stack), &arg_reg2);
  2748. op.a1 = NULL;
  2749. }
  2750. /* init operator info */
  2751. int ret = operatorInfo_init(&op, self, vm, data, arg_ret_reg);
  2752. if (0 != ret) {
  2753. PikaVMFrame_setSysOut(vm, PIKA_ERR_STRING_SYNTAX_ERROR);
  2754. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_SYNTAX_ERROR);
  2755. return NULL;
  2756. }
  2757. switch (data[0]) {
  2758. case '+':
  2759. _OPT_ADD(&op);
  2760. goto __exit;
  2761. case '%':
  2762. if ((op.t1 == ARG_TYPE_INT) && (op.t2 == ARG_TYPE_INT)) {
  2763. op.res = arg_setInt(op.res, "", op.i1 % op.i2);
  2764. goto __exit;
  2765. }
  2766. #if PIKA_MATH_ENABLE
  2767. if (op.t1 == ARG_TYPE_FLOAT || op.t2 == ARG_TYPE_FLOAT) {
  2768. op.res = arg_setFloat(op.res, "", fmod(op.f1, op.f2));
  2769. goto __exit;
  2770. }
  2771. #endif
  2772. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2773. PikaVMFrame_setSysOut(
  2774. vm, "TypeError: unsupported operand type(s) for %%: 'float'");
  2775. op.res = NULL;
  2776. goto __exit;
  2777. case '-':
  2778. _OPT_SUB(&op);
  2779. goto __exit;
  2780. }
  2781. if (data[1] == '=' && (data[0] == '!' || data[0] == '=')) {
  2782. _OPT_EQU(&op);
  2783. goto __exit;
  2784. }
  2785. if (data[1] == 0) {
  2786. switch (data[0]) {
  2787. case '<':
  2788. op.res = arg_setBool(op.res, "", op.f1 < op.f2);
  2789. goto __exit;
  2790. case '*':
  2791. _OPT_MUL(&op);
  2792. goto __exit;
  2793. case '&':
  2794. if ((op.t1 == ARG_TYPE_INT) && (op.t2 == ARG_TYPE_INT)) {
  2795. op.res = arg_setInt(op.res, "", op.i1 & op.i2);
  2796. goto __exit;
  2797. }
  2798. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2799. PikaVMFrame_setSysOut(vm,
  2800. "TypeError: unsupported operand "
  2801. "type(s) for &: 'float'");
  2802. op.res = NULL;
  2803. goto __exit;
  2804. case '|':
  2805. if ((op.t1 == ARG_TYPE_INT) && (op.t2 == ARG_TYPE_INT)) {
  2806. op.res = arg_setInt(op.res, "", op.i1 | op.i2);
  2807. goto __exit;
  2808. }
  2809. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2810. PikaVMFrame_setSysOut(vm,
  2811. "TypeError: unsupported operand "
  2812. "type(s) for |: 'float'");
  2813. op.res = NULL;
  2814. goto __exit;
  2815. case '~':
  2816. if (op.t2 == ARG_TYPE_INT) {
  2817. op.res = arg_setInt(op.res, "", ~op.i2);
  2818. goto __exit;
  2819. }
  2820. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2821. PikaVMFrame_setSysOut(vm,
  2822. "TypeError: unsupported operand "
  2823. "type(s) for ~: 'float'");
  2824. op.res = NULL;
  2825. goto __exit;
  2826. case '/':
  2827. if (0 == op.f2) {
  2828. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2829. PikaVMFrame_setSysOut(
  2830. vm, "ZeroDivisionError: division by zero");
  2831. op.res = NULL;
  2832. goto __exit;
  2833. }
  2834. op.res = arg_setFloat(op.res, "", op.f1 / op.f2);
  2835. goto __exit;
  2836. case '>':
  2837. op.res = arg_setInt(op.res, "", op.f1 > op.f2);
  2838. goto __exit;
  2839. case '^':
  2840. if ((op.t1 == ARG_TYPE_INT) && (op.t2 == ARG_TYPE_INT)) {
  2841. op.res = arg_setInt(op.res, "", op.i1 ^ op.i2);
  2842. goto __exit;
  2843. }
  2844. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2845. PikaVMFrame_setSysOut(vm,
  2846. "TypeError: unsupported operand "
  2847. "type(s) for ^: 'float'");
  2848. op.res = NULL;
  2849. goto __exit;
  2850. }
  2851. }
  2852. if (data[1] == 'i' && data[2] == 'n') {
  2853. if (op.t1 == ARG_TYPE_STRING && op.t2 == ARG_TYPE_STRING) {
  2854. if (strstr(arg_getStr(op.a2), arg_getStr(op.a1))) {
  2855. op.res = arg_setBool(op.res, "", pika_true);
  2856. } else {
  2857. op.res = arg_setBool(op.res, "", pika_false);
  2858. }
  2859. goto __exit;
  2860. }
  2861. if (op.t1 == ARG_TYPE_BYTES) {
  2862. op.res = arg_setBool(op.res, "", _bytes_contains(op.a1, op.a2));
  2863. goto __exit;
  2864. }
  2865. #if !PIKA_NANO_ENABLE
  2866. if (argType_isObject(op.t2)) {
  2867. PikaObj* obj2 = arg_getPtr(op.a2);
  2868. Arg* __contains__ =
  2869. obj_getMethodArgWithFullPath(obj2, "__contains__");
  2870. if (NULL != __contains__) {
  2871. arg_deinit(__contains__);
  2872. op.res = _OPT_Method_ex(obj2, op.a1, &op, "__contains__",
  2873. PIKA_RES_ERR_OPERATION_FAILED,
  2874. "TypeError: unsupported operand in");
  2875. goto __exit;
  2876. }
  2877. PikaObj* local = New_TinyObj(NULL);
  2878. obj_setArg(local, "@list", op.a2);
  2879. obj_setArg(local, "@val", op.a1);
  2880. /* clang-format off */
  2881. PIKA_PYTHON(
  2882. @res_contains = 0
  2883. for @item in @list:
  2884. if @item == @val:
  2885. @res_contains = 1
  2886. break
  2887. )
  2888. /* clang-format on */
  2889. const uint8_t bytes[] = {
  2890. 0x48, 0x00, 0x00, 0x00, /* instruct array size */
  2891. 0x00, 0x85, 0x01, 0x00, 0x00, 0x04, 0x03, 0x00, 0x10, 0x81,
  2892. 0x11, 0x00, 0x00, 0x02, 0x17, 0x00, 0x00, 0x04, 0x1c, 0x00,
  2893. 0x00, 0x82, 0x20, 0x00, 0x00, 0x04, 0x2d, 0x00, 0x00, 0x0d,
  2894. 0x2d, 0x00, 0x00, 0x07, 0x33, 0x00, 0x11, 0x81, 0x2d, 0x00,
  2895. 0x11, 0x01, 0x35, 0x00, 0x01, 0x08, 0x3a, 0x00, 0x01, 0x07,
  2896. 0x3d, 0x00, 0x02, 0x85, 0x3d, 0x00, 0x02, 0x04, 0x03, 0x00,
  2897. 0x02, 0x8e, 0x00, 0x00, 0x00, 0x86, 0x3f, 0x00, 0x00, 0x8c,
  2898. 0x1c, 0x00,
  2899. /* instruct array */
  2900. 0x42, 0x00, 0x00, 0x00, /* const pool size */
  2901. 0x00, 0x30, 0x00, 0x40, 0x72, 0x65, 0x73, 0x5f, 0x63, 0x6f,
  2902. 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x00, 0x40, 0x6c, 0x69,
  2903. 0x73, 0x74, 0x00, 0x69, 0x74, 0x65, 0x72, 0x00, 0x24, 0x6c,
  2904. 0x30, 0x00, 0x24, 0x6c, 0x30, 0x2e, 0x5f, 0x5f, 0x6e, 0x65,
  2905. 0x78, 0x74, 0x5f, 0x5f, 0x00, 0x40, 0x69, 0x74, 0x65, 0x6d,
  2906. 0x00, 0x32, 0x00, 0x40, 0x76, 0x61, 0x6c, 0x00, 0x3d, 0x3d,
  2907. 0x00, 0x31, 0x00, 0x2d, 0x31, 0x00, /* const pool */
  2908. };
  2909. pikaVM_runByteCode(local, (uint8_t*)bytes);
  2910. op.res =
  2911. arg_setBool(op.res, "", obj_getInt(local, "@res_contains"));
  2912. obj_deinit(local);
  2913. goto __exit;
  2914. }
  2915. #endif
  2916. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2917. PikaVMFrame_setSysOut(vm,
  2918. "Operation 'in' is not supported for this "
  2919. "type");
  2920. op.res = NULL;
  2921. goto __exit;
  2922. }
  2923. if (data[0] == '*' && data[1] == '*') {
  2924. _OPT_POW(&op);
  2925. goto __exit;
  2926. }
  2927. if (data[0] == '/' && data[1] == '/') {
  2928. if ((op.t1 == ARG_TYPE_INT) && (op.t2 == ARG_TYPE_INT)) {
  2929. op.res = arg_setInt(op.res, "", op.i1 / op.i2);
  2930. goto __exit;
  2931. }
  2932. #if PIKA_MATH_ENABLE
  2933. if ((op.t1 == ARG_TYPE_FLOAT) || (op.t2 == ARG_TYPE_FLOAT)) {
  2934. op.res = arg_setFloat(op.res, "", floor(op.f1 / op.f2));
  2935. goto __exit;
  2936. }
  2937. #endif
  2938. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2939. PikaVMFrame_setSysOut(
  2940. vm,
  2941. "Operation float \\\\ float is not enabled, please set "
  2942. "PIKA_MATH_ENABLE");
  2943. op.res = NULL;
  2944. goto __exit;
  2945. }
  2946. if (data[1] == 'i' && data[2] == 's') {
  2947. #if !PIKA_NANO_ENABLE
  2948. if (argType_isObject(op.t1) && argType_isObject(op.t2)) {
  2949. if (arg_getPtr(op.a1) == arg_getPtr(op.a2)) {
  2950. op.res = arg_setBool(op.res, "", pika_true);
  2951. } else {
  2952. op.res = arg_setBool(op.res, "", pika_false);
  2953. }
  2954. goto __exit;
  2955. }
  2956. if ((op.t1 != op.t2) && (op.t1 != ARG_TYPE_NONE) &&
  2957. (op.t2 != ARG_TYPE_NONE)) {
  2958. op.res = arg_setInt(op.res, "", 0);
  2959. goto __exit;
  2960. }
  2961. #endif
  2962. op.opt = "==";
  2963. _OPT_EQU(&op);
  2964. goto __exit;
  2965. }
  2966. if (data[0] == '>' && data[1] == '=') {
  2967. op.res = arg_setBool(
  2968. op.res, "",
  2969. (op.f1 > op.f2) ||
  2970. ((op.f1 - op.f2) * (op.f1 - op.f2) < (pika_float)0.000001));
  2971. goto __exit;
  2972. }
  2973. if (data[0] == '<' && data[1] == '=') {
  2974. op.res = arg_setBool(
  2975. op.res, "",
  2976. (op.f1 < op.f2) ||
  2977. ((op.f1 - op.f2) * (op.f1 - op.f2) < (pika_float)0.000001));
  2978. goto __exit;
  2979. }
  2980. if (data[0] == '>' && data[1] == '>') {
  2981. if ((op.t1 == ARG_TYPE_INT) && (op.t2 == ARG_TYPE_INT)) {
  2982. op.res = arg_setInt(op.res, "", op.i1 >> op.i2);
  2983. goto __exit;
  2984. }
  2985. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2986. PikaVMFrame_setSysOut(
  2987. vm, "TypeError: unsupported operand type(s) for >>: 'float'");
  2988. op.res = NULL;
  2989. goto __exit;
  2990. }
  2991. if (data[0] == '<' && data[1] == '<') {
  2992. if ((op.t1 == ARG_TYPE_INT) && (op.t2 == ARG_TYPE_INT)) {
  2993. op.res = arg_setInt(op.res, "", op.i1 << op.i2);
  2994. goto __exit;
  2995. }
  2996. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  2997. PikaVMFrame_setSysOut(
  2998. vm, "TypeError: unsupported operand type(s) for <<: 'float'");
  2999. op.res = NULL;
  3000. goto __exit;
  3001. }
  3002. if (data[0] == ' ' && data[1] == 'a' && data[2] == 'n' && data[3] == 'd' &&
  3003. data[4] == ' ') {
  3004. op.res = arg_setBool(op.res, "", op.i1 && op.i2);
  3005. goto __exit;
  3006. }
  3007. if (data[0] == ' ' && data[1] == 'o' && data[2] == 'r' && data[3] == ' ' &&
  3008. data[4] == 0) {
  3009. op.res = arg_setBool(op.res, "", op.i1 || op.i2);
  3010. goto __exit;
  3011. }
  3012. if (data[0] == ' ' && data[1] == 'n' && data[2] == 'o' && data[3] == 't' &&
  3013. data[4] == ' ' && data[5] == 0) {
  3014. pika_bool bTrue = pika_false;
  3015. _transeBool(op.a2, &bTrue);
  3016. op.res = arg_setBool(op.res, "", !bTrue);
  3017. goto __exit;
  3018. }
  3019. PikaVMFrame_setSysOut(vm, "Error: unknown operator '%s'", data);
  3020. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  3021. __exit:
  3022. if (NULL != op.a1) {
  3023. arg_deinit(op.a1);
  3024. }
  3025. if (NULL != op.a2) {
  3026. arg_deinit(op.a2);
  3027. }
  3028. if (NULL != op.res) {
  3029. return op.res;
  3030. }
  3031. return NULL;
  3032. }
  3033. static Arg* __VM_instruction_handler_DEF(PikaObj* self,
  3034. PikaVMFrame* vm,
  3035. char* data,
  3036. uint8_t is_class) {
  3037. int thisBlockDeepth = PikaVMFrame_getBlockDeepthNow(vm);
  3038. PikaObj* hostObj = vm->locals;
  3039. uint8_t is_in_class = 0;
  3040. /* use RunAs object */
  3041. if (obj_getFlag(vm->locals, OBJ_FLAG_RUN_AS)) {
  3042. hostObj = args_getPtr(vm->locals->list, "@r");
  3043. is_in_class = 1;
  3044. }
  3045. int offset = 0;
  3046. /* byteCode */
  3047. while (1) {
  3048. InstructUnit* ins_unit_now =
  3049. PikaVMFrame_getInstructUnitWithOffset(vm, offset);
  3050. if (!instructUnit_getIsNewLine(ins_unit_now)) {
  3051. offset += instructUnit_getSize();
  3052. continue;
  3053. }
  3054. if (instructUnit_getBlockDeepth(ins_unit_now) == thisBlockDeepth + 1) {
  3055. if (is_in_class) {
  3056. class_defineObjectMethod(hostObj, data, (Method)ins_unit_now,
  3057. self, vm->bytecode_frame);
  3058. } else {
  3059. if (is_class) {
  3060. class_defineRunTimeConstructor(hostObj, data,
  3061. (Method)ins_unit_now, self,
  3062. vm->bytecode_frame);
  3063. } else {
  3064. class_defineStaticMethod(hostObj, data,
  3065. (Method)ins_unit_now, self,
  3066. vm->bytecode_frame);
  3067. }
  3068. }
  3069. break;
  3070. }
  3071. offset += instructUnit_getSize();
  3072. }
  3073. return NULL;
  3074. }
  3075. static Arg* VM_instruction_handler_DEF(PikaObj* self,
  3076. PikaVMFrame* vm,
  3077. char* data,
  3078. Arg* arg_ret_reg) {
  3079. return __VM_instruction_handler_DEF(self, vm, data, 0);
  3080. }
  3081. static Arg* VM_instruction_handler_CLS(PikaObj* self,
  3082. PikaVMFrame* vm,
  3083. char* data,
  3084. Arg* arg_ret_reg) {
  3085. return __VM_instruction_handler_DEF(self, vm, data, 1);
  3086. }
  3087. static Arg* VM_instruction_handler_RIS(PikaObj* self,
  3088. PikaVMFrame* vm,
  3089. char* data,
  3090. Arg* arg_ret_reg) {
  3091. #if PIKA_NANO_ENABLE
  3092. return NULL;
  3093. #endif
  3094. Arg* err_arg = stack_popArg_alloc(&(vm->stack));
  3095. if (ARG_TYPE_INT == arg_getType(err_arg)) {
  3096. PIKA_RES err = (PIKA_RES)arg_getInt(err_arg);
  3097. if (PIKA_RES_ERR_RUNTIME_ERROR != err) {
  3098. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_INVALID_PARAM);
  3099. PikaVMFrame_setSysOut(
  3100. vm, "TypeError: exceptions must derive from BaseException");
  3101. goto __exit;
  3102. }
  3103. PikaVMFrame_setErrorCode(vm, err);
  3104. }
  3105. if (arg_isConstructor(err_arg)) {
  3106. MethodProp* method_prop = methodArg_getProp(err_arg);
  3107. PikaVMFrame_setErrorCode(vm, (uintptr_t)method_prop->ptr);
  3108. goto __exit;
  3109. }
  3110. __exit:
  3111. arg_deinit(err_arg);
  3112. return NULL;
  3113. }
  3114. static Arg* VM_instruction_handler_ASS(PikaObj* self,
  3115. PikaVMFrame* vm,
  3116. char* data,
  3117. Arg* arg_ret_reg) {
  3118. #if PIKA_NANO_ENABLE
  3119. return NULL;
  3120. #endif
  3121. arg_newReg(reg1, PIKA_ARG_BUFF_SIZE);
  3122. arg_newReg(reg2, PIKA_ARG_BUFF_SIZE);
  3123. Arg* arg1 = NULL;
  3124. Arg* arg2 = NULL;
  3125. Arg* res = NULL;
  3126. uint32_t n_arg = PikaVMFrame_getInputArgNum(vm);
  3127. if (n_arg == 1) {
  3128. arg1 = stack_popArg(&vm->stack, &reg1);
  3129. }
  3130. if (n_arg == 2) {
  3131. arg2 = stack_popArg(&vm->stack, &reg2);
  3132. arg1 = stack_popArg(&vm->stack, &reg1);
  3133. }
  3134. /* assert failed */
  3135. if ((arg_getType(arg1) == ARG_TYPE_INT && arg_getInt(arg1) == 0) ||
  3136. (arg_getType(arg1) == ARG_TYPE_BOOL &&
  3137. arg_getBool(arg1) == pika_false)) {
  3138. stack_pushArg(&vm->stack, arg_newInt(PIKA_RES_ERR_ASSERT));
  3139. res = VM_instruction_handler_RIS(self, vm, data, arg_ret_reg);
  3140. // if (vm->vm_thread->try_state == TRY_STATE_NONE) {
  3141. if (n_arg == 1) {
  3142. pika_platform_printf("AssertionError\n");
  3143. }
  3144. if (n_arg == 2) {
  3145. pika_platform_printf("AssertionError: %s\n", arg_getStr(arg2));
  3146. }
  3147. // }
  3148. goto __exit;
  3149. }
  3150. __exit:
  3151. arg_deinit(arg1);
  3152. if (NULL != arg2) {
  3153. arg_deinit(arg2);
  3154. }
  3155. return res;
  3156. }
  3157. static Arg* VM_instruction_handler_NEL(PikaObj* self,
  3158. PikaVMFrame* vm,
  3159. char* data,
  3160. Arg* arg_ret_reg) {
  3161. int thisBlockDeepth = PikaVMFrame_getBlockDeepthNow(vm);
  3162. if (0 == vm->ireg[thisBlockDeepth]) {
  3163. /* set __else flag */
  3164. vm->jmp = fast_atoi(data);
  3165. }
  3166. return NULL;
  3167. }
  3168. static Arg* VM_instruction_handler_DEL(PikaObj* self,
  3169. PikaVMFrame* vm,
  3170. char* data,
  3171. Arg* arg_ret_reg) {
  3172. if (_checkLReg(data)) {
  3173. Locals_delLReg(vm->locals, data);
  3174. goto __exit;
  3175. }
  3176. if (obj_isArgExist(vm->locals, data)) {
  3177. obj_removeArg(vm->locals, data);
  3178. goto __exit;
  3179. }
  3180. if (obj_isArgExist(vm->globals, data)) {
  3181. obj_removeArg(vm->globals, data);
  3182. goto __exit;
  3183. }
  3184. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_OPERATION_FAILED);
  3185. PikaVMFrame_setSysOut(vm, "NameError: name '%s' is not defined", data);
  3186. __exit:
  3187. return NULL;
  3188. }
  3189. static Arg* VM_instruction_handler_EST(PikaObj* self,
  3190. PikaVMFrame* vm,
  3191. char* data,
  3192. Arg* arg_ret_reg) {
  3193. Arg* arg = obj_getArg(vm->locals, data);
  3194. if (arg == NULL) {
  3195. return arg_setInt(arg_ret_reg, "", 0);
  3196. }
  3197. if (ARG_TYPE_NONE == arg_getType(arg)) {
  3198. return arg_setInt(arg_ret_reg, "", 0);
  3199. }
  3200. return arg_setInt(arg_ret_reg, "", 1);
  3201. }
  3202. static Arg* VM_instruction_handler_BRK(PikaObj* self,
  3203. PikaVMFrame* vm,
  3204. char* data,
  3205. Arg* arg_ret_reg) {
  3206. /* break jmp signal */
  3207. vm->jmp = VM_JMP_BREAK;
  3208. return NULL;
  3209. }
  3210. static Arg* VM_instruction_handler_CTN(PikaObj* self,
  3211. PikaVMFrame* vm,
  3212. char* data,
  3213. Arg* arg_ret_reg) {
  3214. /* continue jmp signal */
  3215. vm->jmp = VM_JMP_CONTINUE;
  3216. return NULL;
  3217. }
  3218. static Arg* VM_instruction_handler_GLB(PikaObj* self,
  3219. PikaVMFrame* vm,
  3220. char* data,
  3221. Arg* arg_ret_reg) {
  3222. Arg* global_list_buff = NULL;
  3223. char* global_list = args_getStr(vm->locals->list, "@g");
  3224. /* create new global_list */
  3225. if (NULL == global_list) {
  3226. args_setStr(vm->locals->list, "@g", data);
  3227. obj_setFlag(vm->locals, OBJ_FLAG_GLOBALS);
  3228. goto __exit;
  3229. }
  3230. /* append to exist global_list */
  3231. global_list_buff = arg_newStr(global_list);
  3232. global_list_buff = arg_strAppend(global_list_buff, ",");
  3233. global_list_buff = arg_strAppend(global_list_buff, data);
  3234. args_setStr(vm->locals->list, "@g", arg_getStr(global_list_buff));
  3235. goto __exit;
  3236. __exit:
  3237. if (NULL != global_list_buff) {
  3238. arg_deinit(global_list_buff);
  3239. }
  3240. return NULL;
  3241. }
  3242. static Arg* VM_instruction_handler_IMP(PikaObj* self,
  3243. PikaVMFrame* vm,
  3244. char* data,
  3245. Arg* arg_ret_reg) {
  3246. Args buffs = {0};
  3247. char* sModuleNameRedirect = NULL;
  3248. if (NULL == data) {
  3249. goto __exit;
  3250. }
  3251. sModuleNameRedirect = LibObj_redirectModule(pika_getLibObj(), &buffs, data);
  3252. if (NULL != sModuleNameRedirect) {
  3253. data = sModuleNameRedirect;
  3254. }
  3255. /* the module is already imported, skip. */
  3256. if (obj_isArgExist(self, data)) {
  3257. goto __exit;
  3258. }
  3259. extern volatile PikaObj* __pikaMain;
  3260. /* the module is already imported to root object, import it to self. */
  3261. if (obj_isArgExist((PikaObj*)__pikaMain, data)) {
  3262. obj_setArg(self, data, obj_getArg((PikaObj*)__pikaMain, data));
  3263. goto __exit;
  3264. }
  3265. if (NULL == sModuleNameRedirect) {
  3266. /* find cmodule in root object */
  3267. char* cmodule_try = strsGetFirstToken(&buffs, data, '.');
  3268. if (obj_isArgExist((PikaObj*)__pikaMain, cmodule_try)) {
  3269. obj_setArg(self, cmodule_try,
  3270. obj_getArg((PikaObj*)__pikaMain, cmodule_try));
  3271. goto __exit;
  3272. }
  3273. }
  3274. /* import module from '@lib' */
  3275. if (0 == obj_importModule(self, data)) {
  3276. goto __exit;
  3277. }
  3278. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_ARG_NO_FOUND);
  3279. PikaVMFrame_setSysOut(vm, "ModuleNotFoundError: No module named '%s'",
  3280. data);
  3281. __exit:
  3282. strsDeinit(&buffs);
  3283. return NULL;
  3284. }
  3285. static Arg* VM_instruction_handler_INH(PikaObj* self,
  3286. PikaVMFrame* vm,
  3287. char* data,
  3288. Arg* arg_ret_reg) {
  3289. /* find module bytecode */
  3290. uint8_t* bytecode = pika_getByteCodeFromModule(data);
  3291. if (NULL == bytecode) {
  3292. PikaVMFrame_setErrorCode(vm, PIKA_RES_ERR_ARG_NO_FOUND);
  3293. PikaVMFrame_setSysOut(vm, "ModuleNotFoundError: No module named '%s'",
  3294. data);
  3295. return NULL;
  3296. }
  3297. pikaVM_runByteCode(self, bytecode);
  3298. return NULL;
  3299. }
  3300. #if PIKA_INSTRUCT_EXTENSION_ENABLE
  3301. const VMInstructionSet VM_default_instruction_set = {
  3302. #define __INS_OPCODE
  3303. .instructions =
  3304. (const VMInstruction[]){
  3305. #include "__instruction_table.h"
  3306. },
  3307. .count = __INSTRUCTION_CNT,
  3308. .op_idx_start = PIKA_INS(NON),
  3309. .op_idx_end = PIKA_INS(NON) + __INSTRUCTION_CNT - 1,
  3310. };
  3311. #ifndef PIKA_INSTRUCT_SIGNATURE_DICT
  3312. #define PIKA_INSTRUCT_SIGNATURE_DICT 0
  3313. #endif
  3314. typedef struct VMInstructionSetItem VMInstructionSetItem;
  3315. struct VMInstructionSetItem {
  3316. VMInstructionSetItem* next;
  3317. const VMInstructionSet* ins_set;
  3318. };
  3319. static struct {
  3320. const VMInstructionSetItem default_ins_set;
  3321. VMInstructionSetItem* list;
  3322. VMInstructionSetItem* recent;
  3323. #if PIKA_INSTRUCT_SIGNATURE_DICT_COUNT > 0
  3324. const uint16_t signature_dict[PIKA_INSTRUCT_SIGNATURE_DICT_COUNT];
  3325. #endif
  3326. } g_PikaVMInsSet = {
  3327. .default_ins_set =
  3328. {
  3329. .ins_set = &VM_default_instruction_set,
  3330. .next = NULL,
  3331. },
  3332. .list = (VMInstructionSetItem*)&g_PikaVMInsSet.default_ins_set,
  3333. .recent = (VMInstructionSetItem*)&g_PikaVMInsSet.default_ins_set,
  3334. #if PIKA_INSTRUCT_SIGNATURE_DICT_COUNT > 0
  3335. .signature_dict = {PIKA_INSTRUCT_SIGNATURE_DICT},
  3336. #endif
  3337. };
  3338. pika_bool pikaVM_registerInstructionSet(VMInstructionSet* ins_set) {
  3339. pika_assert(NULL != ins_set);
  3340. #if PIKA_INSTRUCT_SIGNATURE_DICT_COUNT > 0
  3341. uint16_t signature = ins_set->signature;
  3342. pika_bool ins_set_valid = pika_false;
  3343. for (int n = 0;
  3344. n < sizeof(g_PikaVMInsSet.signature_dict) / sizeof(uint16_t); n++) {
  3345. if (g_PikaVMInsSet.signature_dict[n] == signature) {
  3346. ins_set_valid = pika_true;
  3347. break;
  3348. }
  3349. }
  3350. if (!ins_set_valid) {
  3351. return pika_false;
  3352. }
  3353. #endif
  3354. /* check whether the target instruction set exists or not */
  3355. VMInstructionSetItem* list_item = g_PikaVMInsSet.list;
  3356. do {
  3357. if (list_item->ins_set->signature == signature) {
  3358. return pika_true; /* already exist */
  3359. }
  3360. list_item = list_item->next;
  3361. } while (NULL != list_item->next);
  3362. VMInstructionSetItem* item =
  3363. pika_platform_malloc(sizeof(VMInstructionSetItem));
  3364. if (NULL == item) {
  3365. return pika_false;
  3366. }
  3367. item->ins_set = ins_set;
  3368. item->next = NULL;
  3369. /* add item to the tail of VM.list */
  3370. list_item->next = item;
  3371. return pika_true;
  3372. }
  3373. static const VMInstruction* instructUnit_getInstruct(
  3374. enum InstructIndex ins_idx) {
  3375. VMInstructionSetItem* item = g_PikaVMInsSet.recent;
  3376. if ((ins_idx >= item->ins_set->op_idx_start) &&
  3377. (ins_idx <= item->ins_set->op_idx_end)) {
  3378. return &(
  3379. item->ins_set->instructions[ins_idx - item->ins_set->op_idx_start]);
  3380. }
  3381. /* search list */
  3382. item = g_PikaVMInsSet.list;
  3383. do {
  3384. if ((ins_idx >= item->ins_set->op_idx_start) &&
  3385. (ins_idx <= item->ins_set->op_idx_end)) {
  3386. g_PikaVMInsSet.recent = item;
  3387. return &(item->ins_set
  3388. ->instructions[ins_idx - item->ins_set->op_idx_start]);
  3389. }
  3390. item = item->next;
  3391. } while (NULL != item->next);
  3392. return NULL;
  3393. }
  3394. static enum InstructIndex __find_ins_idx_in_ins_set(
  3395. char* ins_str,
  3396. const VMInstructionSet* set) {
  3397. const VMInstruction* ins = set->instructions;
  3398. uint_fast16_t count = set->count;
  3399. do {
  3400. if (0 == strncmp(ins_str, ins->op_str, ins->op_str_len)) {
  3401. return (enum InstructIndex)ins->op_idx;
  3402. }
  3403. ins++;
  3404. } while (--count);
  3405. return __INSTRUCTION_UNKNOWN;
  3406. }
  3407. enum InstructIndex pikaVM_getInstructFromAsm(char* ins_str) {
  3408. enum InstructIndex ins_idx =
  3409. __find_ins_idx_in_ins_set(ins_str, g_PikaVMInsSet.recent->ins_set);
  3410. if (__INSTRUCTION_UNKNOWN == ins_idx) {
  3411. VMInstructionSetItem* item = g_PikaVMInsSet.list;
  3412. do {
  3413. ins_idx = __find_ins_idx_in_ins_set(ins_str, item->ins_set);
  3414. if (__INSTRUCTION_UNKNOWN != ins_idx) {
  3415. g_PikaVMInsSet.recent = item;
  3416. return ins_idx;
  3417. }
  3418. item = item->next;
  3419. } while (NULL != item->next);
  3420. return PIKA_INS(NON);
  3421. }
  3422. return ins_idx;
  3423. }
  3424. #else
  3425. pika_bool pikaVM_registerInstructionSet(VMInstructionSet* ins_set) {
  3426. return pika_false;
  3427. }
  3428. enum InstructIndex pikaVM_getInstructFromAsm(char* ins_str) {
  3429. #define __INS_COMPARE
  3430. #include "__instruction_table.h"
  3431. return NON;
  3432. }
  3433. const VM_instruct_handler VM_instruct_handler_table[__INSTRUCTION_CNT] = {
  3434. #define __INS_TABLE
  3435. #include "__instruction_table.h"
  3436. };
  3437. #endif
  3438. extern volatile PikaObj* __pikaMain;
  3439. static enum shellCTRL __obj_shellLineHandler_debug(PikaObj* self,
  3440. char* input_line,
  3441. struct ShellConfig* config) {
  3442. /* continue */
  3443. if (strEqu("c", input_line)) {
  3444. return SHELL_CTRL_EXIT;
  3445. }
  3446. /* next */
  3447. if (strEqu("n", input_line)) {
  3448. return SHELL_CTRL_EXIT;
  3449. }
  3450. /* launch shell */
  3451. if (strEqu("sh", input_line)) {
  3452. /* exit pika shell */
  3453. pikaScriptShell((PikaObj*)__pikaMain);
  3454. return SHELL_CTRL_CONTINUE;
  3455. }
  3456. /* quit */
  3457. if (strEqu("q", input_line)) {
  3458. obj_setInt(self, "enable", 0);
  3459. return SHELL_CTRL_EXIT;
  3460. }
  3461. /* print */
  3462. if (strIsStartWith(input_line, "p ")) {
  3463. char* path = input_line + 2;
  3464. Arg* asm_buff = arg_newStr("print(");
  3465. asm_buff = arg_strAppend(asm_buff, path);
  3466. asm_buff = arg_strAppend(asm_buff, ")\n");
  3467. pikaVM_run_ex_cfg cfg = {0};
  3468. cfg.globals = config->globals;
  3469. cfg.in_repl = pika_true;
  3470. pikaVM_run_ex(config->locals, arg_getStr(asm_buff), &cfg);
  3471. arg_deinit(asm_buff);
  3472. return SHELL_CTRL_CONTINUE;
  3473. }
  3474. pikaVM_run_ex_cfg cfg = {0};
  3475. cfg.globals = config->globals;
  3476. cfg.in_repl = pika_true;
  3477. pikaVM_run_ex(config->locals, input_line, &cfg);
  3478. return SHELL_CTRL_CONTINUE;
  3479. }
  3480. void pika_debug_set_trace(PikaObj* self) {
  3481. if (!obj_getInt(self, "enable")) {
  3482. return;
  3483. }
  3484. char* name = "stdin";
  3485. pika_assert(NULL != self->vmFrame);
  3486. if (NULL != self->vmFrame->bytecode_frame->name) {
  3487. name = self->vmFrame->bytecode_frame->name;
  3488. }
  3489. pika_platform_printf("%s:%d\n", name, self->vmFrame->pc);
  3490. struct ShellConfig cfg = {
  3491. .prefix = "(Pdb-pika) ",
  3492. .handler = __obj_shellLineHandler_debug,
  3493. .fn_getchar = __platform_getchar,
  3494. .locals = self->vmFrame->locals,
  3495. .globals = self->vmFrame->globals,
  3496. };
  3497. _do_pikaScriptShell(self, &cfg);
  3498. shConfig_deinit(&cfg);
  3499. }
  3500. static int pikaVM_runInstructUnit(PikaObj* self,
  3501. PikaVMFrame* vm,
  3502. InstructUnit* ins_unit) {
  3503. enum InstructIndex instruct = instructUnit_getInstructIndex(ins_unit);
  3504. arg_newReg(ret_reg, PIKA_ARG_BUFF_SIZE);
  3505. Arg* return_arg = &ret_reg;
  3506. // char invode_deepth1_str[2] = {0};
  3507. int32_t pc_next = vm->pc + instructUnit_getSize();
  3508. char* data = PikaVMFrame_getConstWithInstructUnit(vm, ins_unit);
  3509. /* run instruct */
  3510. pika_assert(NULL != vm->vm_thread);
  3511. if (PikaVMFrame_checkBreakPoint(vm)) {
  3512. pika_debug_set_trace(self);
  3513. }
  3514. #if PIKA_INSTRUCT_EXTENSION_ENABLE
  3515. const VMInstruction* ins = instructUnit_getInstruct(instruct);
  3516. if (NULL == ins) {
  3517. /* todo: unsupported instruction */
  3518. pika_assert(NULL != ins);
  3519. }
  3520. pika_assert(NULL != ins->handler);
  3521. return_arg = ins->handler(self, vm, data, &ret_reg);
  3522. #else
  3523. return_arg = VM_instruct_handler_table[instruct](self, vm, data, &ret_reg);
  3524. #endif
  3525. if (pikaVMFrame_checkErrorStack(vm) != PIKA_RES_OK ||
  3526. VMSignal_getCtrl() == VM_SIGNAL_CTRL_EXIT) {
  3527. /* raise jmp */
  3528. if (vm->vm_thread->try_state == TRY_STATE_INNER) {
  3529. vm->jmp = VM_JMP_RAISE;
  3530. } else {
  3531. /* exit */
  3532. vm->jmp = VM_JMP_EXIT;
  3533. }
  3534. }
  3535. #if PIKA_BUILTIN_STRUCT_ENABLE
  3536. int invoke_deepth = PikaVMFrame_getInvokeDeepthNow(vm);
  3537. if (invoke_deepth > 0) {
  3538. PikaObj* oReg = vm->oreg[invoke_deepth - 1];
  3539. if (NULL != oReg && NULL != return_arg) {
  3540. pikaList_append(oReg, return_arg);
  3541. return_arg = NULL;
  3542. }
  3543. }
  3544. #endif
  3545. if (NULL != return_arg) {
  3546. stack_pushArg(&(vm->stack), return_arg);
  3547. }
  3548. goto __next_line;
  3549. __next_line:
  3550. /* exit */
  3551. if (VM_JMP_EXIT == vm->jmp) {
  3552. pc_next = VM_PC_EXIT;
  3553. goto __exit;
  3554. }
  3555. /* break */
  3556. if (VM_JMP_BREAK == vm->jmp) {
  3557. pc_next = vm->pc + PikaVMFrame_getAddrOffsetOfBreak(vm);
  3558. goto __exit;
  3559. }
  3560. /* continue */
  3561. if (VM_JMP_CONTINUE == vm->jmp) {
  3562. pc_next = vm->pc + PikaVMFrame_getAddrOffsetOfContinue(vm);
  3563. goto __exit;
  3564. }
  3565. /* raise */
  3566. #if !PIKA_NANO_ENABLE
  3567. if (VM_JMP_RAISE == vm->jmp) {
  3568. int offset = PikaVMFrame_getAddrOffsetOfRaise(vm);
  3569. if (0 == offset) {
  3570. /* can not found end of try, return */
  3571. pc_next = VM_PC_EXIT;
  3572. vm->vm_thread->try_result = TRY_RESULT_RAISE;
  3573. goto __exit;
  3574. }
  3575. pc_next = vm->pc + offset;
  3576. vm->vm_thread->try_result = TRY_RESULT_NONE;
  3577. goto __exit;
  3578. }
  3579. #endif
  3580. /* static jmp */
  3581. if (vm->jmp != 0) {
  3582. pc_next = vm->pc + PikaVMFrame_getAddrOffsetFromJmp(vm);
  3583. goto __exit;
  3584. }
  3585. /* not jmp */
  3586. pc_next = vm->pc + instructUnit_getSize();
  3587. /* jump to next line */
  3588. if (pikaVMFrame_checkErrorStack(vm) != PIKA_RES_OK) {
  3589. while (1) {
  3590. if (pc_next >= (int)PikaVMFrame_getInstructArraySize(vm)) {
  3591. pc_next = VM_PC_EXIT;
  3592. goto __exit;
  3593. }
  3594. InstructUnit* ins_next = instructArray_getByOffset(
  3595. &vm->bytecode_frame->instruct_array, pc_next);
  3596. if (instructUnit_getIsNewLine(ins_next)) {
  3597. goto __exit;
  3598. }
  3599. pc_next = pc_next + instructUnit_getSize();
  3600. }
  3601. }
  3602. goto __exit;
  3603. __exit:
  3604. vm->jmp = 0;
  3605. /* reach the end */
  3606. if (pc_next >= (int)PikaVMFrame_getInstructArraySize(vm)) {
  3607. return VM_PC_EXIT;
  3608. }
  3609. return pc_next;
  3610. }
  3611. VMParameters* pikaVM_runAsm(PikaObj* self, char* pikaAsm) {
  3612. ByteCodeFrame bytecode_frame;
  3613. byteCodeFrame_init(&bytecode_frame);
  3614. byteCodeFrame_appendFromAsm(&bytecode_frame, pikaAsm);
  3615. VMParameters* res = pikaVM_runByteCodeFrame(self, &bytecode_frame);
  3616. byteCodeFrame_deinit(&bytecode_frame);
  3617. return res;
  3618. }
  3619. static ByteCodeFrame* _cache_bytecodeframe(PikaObj* self) {
  3620. ByteCodeFrame bytecode_frame_stack = {0};
  3621. ByteCodeFrame* res = NULL;
  3622. if (!obj_isArgExist(self, "@bcn")) {
  3623. /* start form @bc0 */
  3624. obj_setInt(self, "@bcn", 0);
  3625. }
  3626. int bcn = obj_getInt(self, "@bcn");
  3627. char bcn_str[] = "@bcx";
  3628. bcn_str[3] = '0' + bcn;
  3629. /* load bytecode to heap */
  3630. args_setHeapStruct(self->list, bcn_str, bytecode_frame_stack,
  3631. byteCodeFrame_deinit);
  3632. /* get bytecode_ptr from heap */
  3633. res = args_getHeapStruct(self->list, bcn_str);
  3634. obj_setInt(self, "@bcn", bcn + 1);
  3635. return res;
  3636. }
  3637. static ByteCodeFrame* _cache_bcf_fn(PikaObj* self, char* py_lines) {
  3638. /* cache 'def' and 'class' to heap */
  3639. if ((NULL == strstr(py_lines, "def ")) &&
  3640. (NULL == strstr(py_lines, "class "))) {
  3641. return NULL;
  3642. }
  3643. return _cache_bytecodeframe(self);
  3644. }
  3645. static char* _get_data_from_bytecode2(uint8_t* bytecode,
  3646. enum InstructIndex ins1,
  3647. enum InstructIndex ins2) {
  3648. ByteCodeFrame bf = {0};
  3649. char* res = NULL;
  3650. byteCodeFrame_init(&bf);
  3651. byteCodeFrame_loadByteCode(&bf, bytecode);
  3652. while (1) {
  3653. InstructUnit* ins_unit = instructArray_getNow(&bf.instruct_array);
  3654. if (NULL == ins_unit) {
  3655. goto __exit;
  3656. }
  3657. enum InstructIndex ins = instructUnit_getInstructIndex(ins_unit);
  3658. if (ins == ins1 || ins == ins2) {
  3659. res = constPool_getByOffset(&bf.const_pool,
  3660. ins_unit->const_pool_index);
  3661. goto __exit;
  3662. }
  3663. instructArray_getNext(&bf.instruct_array);
  3664. }
  3665. __exit:
  3666. byteCodeFrame_deinit(&bf);
  3667. return res;
  3668. }
  3669. static ByteCodeFrame* _cache_bcf_fn_bc(PikaObj* self, uint8_t* bytecode) {
  3670. /* save 'def' and 'class' to heap */
  3671. if (NULL ==
  3672. _get_data_from_bytecode2(bytecode, PIKA_INS(DEF), PIKA_INS(CLS))) {
  3673. return NULL;
  3674. }
  3675. return _cache_bytecodeframe(self);
  3676. }
  3677. VMParameters* pikaVM_run_ex(PikaObj* self,
  3678. char* py_lines,
  3679. pikaVM_run_ex_cfg* cfg) {
  3680. ByteCodeFrame bytecode_frame_stack = {0};
  3681. ByteCodeFrame* bytecode_frame_p = NULL;
  3682. uint8_t is_use_heap_bytecode = 0;
  3683. PikaObj* globals = self;
  3684. if (NULL != cfg->globals) {
  3685. globals = cfg->globals;
  3686. }
  3687. /*
  3688. * the first obj_run, cache bytecode to heap, to support 'def' and
  3689. * 'class'
  3690. */
  3691. bytecode_frame_p = _cache_bcf_fn(self, py_lines);
  3692. if (NULL == bytecode_frame_p) {
  3693. is_use_heap_bytecode = 0;
  3694. /* get bytecode_ptr from stack */
  3695. bytecode_frame_p = &bytecode_frame_stack;
  3696. }
  3697. /* load or generate byte code frame */
  3698. /* generate byte code */
  3699. byteCodeFrame_init(bytecode_frame_p);
  3700. if (PIKA_RES_OK != pika_lines2Bytes(bytecode_frame_p, py_lines)) {
  3701. obj_setSysOut(self, PIKA_ERR_STRING_SYNTAX_ERROR);
  3702. globals = NULL;
  3703. goto __exit;
  3704. }
  3705. /* run byteCode */
  3706. if (NULL != cfg->module_name) {
  3707. byteCodeFrame_setName(bytecode_frame_p, cfg->module_name);
  3708. }
  3709. globals = _pikaVM_runByteCodeFrameGlobals(self, globals, bytecode_frame_p,
  3710. cfg->in_repl);
  3711. goto __exit;
  3712. __exit:
  3713. if (!is_use_heap_bytecode) {
  3714. byteCodeFrame_deinit(&bytecode_frame_stack);
  3715. }
  3716. return globals;
  3717. }
  3718. VMParameters* pikaVM_runByteCode_ex(PikaObj* self,
  3719. uint8_t* bytecode,
  3720. pikaVM_runBytecode_ex_cfg* cfg) {
  3721. ByteCodeFrame bytecode_frame_stack = {0};
  3722. ByteCodeFrame* bytecode_frame_p = NULL;
  3723. uint8_t is_use_heap_bytecode = 1;
  3724. /*
  3725. * the first obj_run, cache bytecode to heap, to support 'def' and
  3726. * 'class'
  3727. */
  3728. bytecode_frame_p = _cache_bcf_fn_bc(self, bytecode);
  3729. if (NULL == bytecode_frame_p) {
  3730. is_use_heap_bytecode = 0;
  3731. /* get bytecode_ptr from stack */
  3732. bytecode_frame_p = &bytecode_frame_stack;
  3733. /* no def/class ins, no need cache bytecode */
  3734. cfg->is_const_bytecode = pika_true;
  3735. }
  3736. /* load or generate byte code frame */
  3737. /* load bytecode */
  3738. _do_byteCodeFrame_loadByteCode(bytecode_frame_p, bytecode, cfg->name,
  3739. cfg->is_const_bytecode);
  3740. /* run byteCode */
  3741. cfg->globals = _pikaVM_runByteCodeFrameWithState(
  3742. self, cfg->locals, cfg->globals, bytecode_frame_p, 0, cfg->vm_thread);
  3743. goto __exit;
  3744. __exit:
  3745. if (!is_use_heap_bytecode) {
  3746. byteCodeFrame_deinit(&bytecode_frame_stack);
  3747. }
  3748. return cfg->globals;
  3749. }
  3750. VMParameters* pikaVM_runByteCodeFile(PikaObj* self, char* filename) {
  3751. Args buffs = {0};
  3752. Arg* file_arg = arg_loadFile(NULL, filename);
  3753. pika_assert(NULL != file_arg);
  3754. if (NULL == file_arg) {
  3755. pika_platform_printf("Error: can not open file '%s'\n", filename);
  3756. return NULL;
  3757. }
  3758. uint8_t* lines = arg_getBytes(file_arg);
  3759. /* clear the void line */
  3760. VMParameters* res = pikaVM_runByteCodeInconstant(self, lines);
  3761. arg_deinit(file_arg);
  3762. strsDeinit(&buffs);
  3763. return res;
  3764. }
  3765. VMParameters* pikaVM_runSingleFile(PikaObj* self, char* filename) {
  3766. Args buffs = {0};
  3767. Arg* file_arg = arg_loadFile(NULL, filename);
  3768. if (NULL == file_arg) {
  3769. pika_platform_printf("FileNotFoundError: %s\n", filename);
  3770. return NULL;
  3771. }
  3772. char* lines = (char*)arg_getBytes(file_arg);
  3773. lines = strsFilePreProcess(&buffs, lines);
  3774. /* clear the void line */
  3775. pikaVM_run_ex_cfg cfg = {0};
  3776. cfg.in_repl = pika_false;
  3777. char* module_name = strsPathGetFileName(&buffs, filename);
  3778. module_name = strsPopToken(&buffs, &module_name, '.');
  3779. cfg.module_name = module_name;
  3780. VMParameters* res = pikaVM_run_ex(self, lines, &cfg);
  3781. arg_deinit(file_arg);
  3782. strsDeinit(&buffs);
  3783. return res;
  3784. }
  3785. VMParameters* pikaVM_run(PikaObj* self, char* py_lines) {
  3786. pikaVM_run_ex_cfg cfg = {0};
  3787. cfg.in_repl = pika_false;
  3788. return pikaVM_run_ex(self, py_lines, &cfg);
  3789. }
  3790. VMParameters* pikaVM_runByteCode(PikaObj* self, const uint8_t* bytecode) {
  3791. pika_assert(NULL != self);
  3792. PikaVMThread* vm_thread = pikaVMThread_require();
  3793. pikaVM_runBytecode_ex_cfg cfg = {0};
  3794. cfg.locals = self;
  3795. cfg.globals = self;
  3796. cfg.name = NULL;
  3797. cfg.vm_thread = vm_thread;
  3798. cfg.is_const_bytecode = pika_true;
  3799. return pikaVM_runByteCode_ex(self, (uint8_t*)bytecode, &cfg);
  3800. }
  3801. Arg* pikaVM_runByteCodeReturn(PikaObj* self,
  3802. const uint8_t* bytecode,
  3803. char* returnName) {
  3804. pikaVM_runByteCode(self, bytecode);
  3805. Arg* ret = args_getArg(self->list, returnName);
  3806. if (NULL == ret) {
  3807. return NULL;
  3808. }
  3809. ret = arg_copy(ret);
  3810. /* set gc root to avoid be free */
  3811. arg_setObjFlag(ret, OBJ_FLAG_GC_ROOT);
  3812. obj_removeArg(self, returnName);
  3813. return ret;
  3814. }
  3815. Arg* pikaVM_runByteCode_exReturn(PikaObj* self,
  3816. VMParameters* locals,
  3817. VMParameters* globals,
  3818. uint8_t* bytecode,
  3819. PikaVMThread* vm_thread,
  3820. pika_bool is_const_bytecode,
  3821. char* return_name) {
  3822. pikaVM_runBytecode_ex_cfg cfg = {0};
  3823. cfg.locals = locals;
  3824. cfg.globals = globals;
  3825. cfg.vm_thread = vm_thread;
  3826. cfg.is_const_bytecode = is_const_bytecode;
  3827. pikaVM_runByteCode_ex(self, bytecode, &cfg);
  3828. Arg* ret = args_getArg(self->list, return_name);
  3829. if (NULL == ret) {
  3830. return NULL;
  3831. }
  3832. ret = arg_copy(ret);
  3833. /* set gc root to avoid be free */
  3834. arg_setObjFlag(ret, OBJ_FLAG_GC_ROOT);
  3835. obj_removeArg(self, return_name);
  3836. return ret;
  3837. }
  3838. VMParameters* pikaVM_runByteCodeInconstant(PikaObj* self, uint8_t* bytecode) {
  3839. PikaVMThread* vm_thread = pikaVMThread_require();
  3840. pikaVM_runBytecode_ex_cfg cfg = {0};
  3841. cfg.locals = self;
  3842. cfg.globals = self;
  3843. cfg.vm_thread = vm_thread;
  3844. cfg.is_const_bytecode = pika_false;
  3845. return pikaVM_runByteCode_ex(self, (uint8_t*)bytecode, &cfg);
  3846. }
  3847. void constPool_update(ConstPool* self) {
  3848. self->content_start = (void*)arg_getContent(self->arg_buff);
  3849. }
  3850. void constPool_init(ConstPool* self) {
  3851. self->arg_buff = NULL;
  3852. self->content_start = NULL;
  3853. self->content_offset_now = 0;
  3854. self->size = 1;
  3855. self->output_redirect_fun = NULL;
  3856. self->output_f = NULL;
  3857. }
  3858. void constPool_deinit(ConstPool* self) {
  3859. if (NULL != self->arg_buff) {
  3860. arg_deinit(self->arg_buff);
  3861. }
  3862. }
  3863. void constPool_append(ConstPool* self, char* content) {
  3864. if (NULL == self->arg_buff) {
  3865. self->arg_buff = arg_newStr("");
  3866. }
  3867. uint16_t size = strGetSize(content) + 1;
  3868. if (NULL == self->output_redirect_fun) {
  3869. self->arg_buff = arg_append(self->arg_buff, content, size);
  3870. } else {
  3871. self->output_redirect_fun(self, content);
  3872. };
  3873. constPool_update(self);
  3874. self->size += size;
  3875. }
  3876. char* constPool_getNow(ConstPool* self) {
  3877. if (self->content_offset_now >= self->size) {
  3878. /* is the end */
  3879. return NULL;
  3880. }
  3881. return (char*)((uintptr_t)constPool_getStart(self) +
  3882. (uintptr_t)(self->content_offset_now));
  3883. }
  3884. uint16_t constPool_getOffsetByData(ConstPool* self, char* data) {
  3885. uint16_t ptr_befor = self->content_offset_now;
  3886. /* set ptr_now to begin */
  3887. self->content_offset_now = 0;
  3888. uint16_t offset_out = 65535;
  3889. if (self->arg_buff == NULL) {
  3890. goto __exit;
  3891. }
  3892. while (1) {
  3893. if (NULL == constPool_getNext(self)) {
  3894. goto __exit;
  3895. }
  3896. if (strEqu(data, constPool_getNow(self))) {
  3897. offset_out = self->content_offset_now;
  3898. goto __exit;
  3899. }
  3900. }
  3901. __exit:
  3902. /* retore ptr_now */
  3903. self->content_offset_now = ptr_befor;
  3904. return offset_out;
  3905. }
  3906. char* constPool_getNext(ConstPool* self) {
  3907. self->content_offset_now += strGetSize(constPool_getNow(self)) + 1;
  3908. return constPool_getNow(self);
  3909. }
  3910. char* constPool_getByIndex(ConstPool* self, uint16_t index) {
  3911. uint16_t ptr_befor = self->content_offset_now;
  3912. /* set ptr_now to begin */
  3913. self->content_offset_now = 0;
  3914. for (uint16_t i = 0; i < index; i++) {
  3915. constPool_getNext(self);
  3916. }
  3917. char* res = constPool_getNow(self);
  3918. /* retore ptr_now */
  3919. self->content_offset_now = ptr_befor;
  3920. return res;
  3921. }
  3922. void constPool_print(ConstPool* self) {
  3923. uint16_t ptr_befor = self->content_offset_now;
  3924. /* set ptr_now to begin */
  3925. self->content_offset_now = 0;
  3926. while (1) {
  3927. if (NULL == constPool_getNext(self)) {
  3928. goto __exit;
  3929. }
  3930. uint16_t offset = self->content_offset_now;
  3931. pika_platform_printf("%d: %s\r\n", offset, constPool_getNow(self));
  3932. }
  3933. __exit:
  3934. /* retore ptr_now */
  3935. self->content_offset_now = ptr_befor;
  3936. return;
  3937. }
  3938. void byteCodeFrame_init(ByteCodeFrame* self) {
  3939. /* init to support append,
  3940. if only load static bytecode,
  3941. can not init */
  3942. constPool_init(&(self->const_pool));
  3943. instructArray_init(&(self->instruct_array));
  3944. self->name = NULL;
  3945. self->label_pc = -1;
  3946. }
  3947. extern const char magic_code_pyo[4];
  3948. void _do_byteCodeFrame_loadByteCode(ByteCodeFrame* self,
  3949. uint8_t* bytes,
  3950. char* name,
  3951. pika_bool is_const) {
  3952. if (bytes[0] == magic_code_pyo[0] && bytes[1] == magic_code_pyo[1] &&
  3953. bytes[2] == magic_code_pyo[2] && bytes[3] == magic_code_pyo[3]) {
  3954. /* load from file, found magic code, skip head */
  3955. bytes = bytes + sizeof(magic_code_pyo) + sizeof(uint32_t);
  3956. }
  3957. uint32_t* ins_size_p = (uint32_t*)bytes;
  3958. void* ins_start_p = (uint32_t*)((uintptr_t)bytes + sizeof(*ins_size_p));
  3959. uint32_t* const_size_p =
  3960. (uint32_t*)((uintptr_t)ins_start_p + (uintptr_t)(*ins_size_p));
  3961. self->instruct_array.size = *ins_size_p;
  3962. self->instruct_array.content_start = ins_start_p;
  3963. self->const_pool.size = *const_size_p;
  3964. self->const_pool.content_start =
  3965. (char*)((uintptr_t)const_size_p + sizeof(*const_size_p));
  3966. byteCodeFrame_setName(self, name);
  3967. if (!is_const) {
  3968. pika_assert(NULL == self->instruct_array.arg_buff);
  3969. pika_assert(NULL == self->instruct_array.arg_buff);
  3970. self->instruct_array.arg_buff = arg_newBytes(ins_start_p, *ins_size_p);
  3971. self->const_pool.arg_buff =
  3972. arg_newBytes(self->const_pool.content_start, *const_size_p);
  3973. self->instruct_array.content_start =
  3974. arg_getBytes(self->instruct_array.arg_buff);
  3975. self->const_pool.content_start =
  3976. arg_getBytes(self->const_pool.arg_buff);
  3977. }
  3978. pika_assert(NULL != self->const_pool.content_start);
  3979. }
  3980. void byteCodeFrame_setName(ByteCodeFrame* self, char* name) {
  3981. if (name != NULL && self->name == NULL) {
  3982. self->name = pika_platform_malloc(strGetSize(name) + 1);
  3983. pika_platform_memcpy(self->name, name, strGetSize(name) + 1);
  3984. }
  3985. }
  3986. void byteCodeFrame_loadByteCode(ByteCodeFrame* self, uint8_t* bytes) {
  3987. _do_byteCodeFrame_loadByteCode(self, bytes, NULL, pika_true);
  3988. }
  3989. void byteCodeFrame_deinit(ByteCodeFrame* self) {
  3990. constPool_deinit(&(self->const_pool));
  3991. instructArray_deinit(&(self->instruct_array));
  3992. if (NULL != self->name) {
  3993. pika_platform_free(self->name);
  3994. }
  3995. }
  3996. void instructArray_init(InstructArray* self) {
  3997. self->arg_buff = NULL;
  3998. self->content_start = NULL;
  3999. self->size = 0;
  4000. self->content_offset_now = 0;
  4001. self->output_redirect_fun = NULL;
  4002. self->output_f = NULL;
  4003. }
  4004. void instructArray_deinit(InstructArray* self) {
  4005. if (NULL != self->arg_buff) {
  4006. arg_deinit(self->arg_buff);
  4007. }
  4008. }
  4009. void instructArray_append(InstructArray* self, InstructUnit* ins_unit) {
  4010. if (NULL == self->arg_buff) {
  4011. self->arg_buff = arg_newNone();
  4012. }
  4013. if (NULL == self->output_redirect_fun) {
  4014. self->arg_buff =
  4015. arg_append(self->arg_buff, ins_unit, instructUnit_getSize());
  4016. } else {
  4017. self->output_redirect_fun(self, ins_unit);
  4018. };
  4019. instructArray_update(self);
  4020. self->size += instructUnit_getSize();
  4021. }
  4022. void instructUnit_init(InstructUnit* ins_unit) {
  4023. ins_unit->deepth = 0;
  4024. ins_unit->const_pool_index = 0;
  4025. ins_unit->isNewLine_instruct = 0;
  4026. }
  4027. void instructArray_update(InstructArray* self) {
  4028. self->content_start = (void*)arg_getContent(self->arg_buff);
  4029. }
  4030. InstructUnit* instructArray_getNow(InstructArray* self) {
  4031. if (self->content_offset_now >= self->size) {
  4032. /* is the end */
  4033. return NULL;
  4034. }
  4035. return (InstructUnit*)((uintptr_t)instructArray_getStart(self) +
  4036. (uintptr_t)(self->content_offset_now));
  4037. }
  4038. InstructUnit* instructArray_getNext(InstructArray* self) {
  4039. self->content_offset_now += instructUnit_getSize();
  4040. return instructArray_getNow(self);
  4041. }
  4042. #if PIKA_INSTRUCT_EXTENSION_ENABLE
  4043. static const char* __find_ins_str_in_ins_set(enum InstructIndex op_idx,
  4044. const VMInstructionSet* set) {
  4045. const VMInstruction* ins = set->instructions;
  4046. uint_fast16_t count = set->count;
  4047. do {
  4048. if (ins->op_idx == op_idx) {
  4049. return ins->op_str;
  4050. }
  4051. ins++;
  4052. } while (--count);
  4053. return NULL;
  4054. }
  4055. static char* instructUnit_getInstructStr(InstructUnit* self) {
  4056. enum InstructIndex op_idx = instructUnit_getInstructIndex(self);
  4057. const char* ins_str =
  4058. __find_ins_str_in_ins_set(op_idx, g_PikaVMInsSet.recent->ins_set);
  4059. if (NULL != ins_str) {
  4060. return (char*)ins_str;
  4061. }
  4062. VMInstructionSetItem* item = g_PikaVMInsSet.list;
  4063. do {
  4064. ins_str = __find_ins_str_in_ins_set(op_idx, item->ins_set);
  4065. if (NULL != ins_str) {
  4066. g_PikaVMInsSet.recent = item;
  4067. return (char*)ins_str;
  4068. }
  4069. item = item->next;
  4070. } while (NULL != item->next);
  4071. return "NON";
  4072. }
  4073. #else
  4074. static char* instructUnit_getInstructStr(InstructUnit* self) {
  4075. #define __INS_GET_INS_STR
  4076. #include "__instruction_table.h"
  4077. return "NON";
  4078. }
  4079. #endif
  4080. void instructUnit_print(InstructUnit* self) {
  4081. if (instructUnit_getIsNewLine(self)) {
  4082. pika_platform_printf("B%d\r\n", instructUnit_getBlockDeepth(self));
  4083. }
  4084. pika_platform_printf("%d %s #%d\r\n", instructUnit_getInvokeDeepth(self),
  4085. instructUnit_getInstructStr(self),
  4086. self->const_pool_index);
  4087. }
  4088. static void instructUnit_printWithConst(InstructUnit* self,
  4089. ConstPool* const_pool) {
  4090. // if (instructUnit_getIsNewLine(self)) {
  4091. // pika_platform_printf("B%d\r\n",
  4092. // instructUnit_getBlockDeepth(self));
  4093. // }
  4094. pika_platform_printf(
  4095. "%s %s \t\t(#%d)\r\n", instructUnit_getInstructStr(self),
  4096. constPool_getByOffset(const_pool, self->const_pool_index),
  4097. self->const_pool_index);
  4098. }
  4099. void instructArray_printWithConst(InstructArray* self, ConstPool* const_pool) {
  4100. uint16_t offset_befor = self->content_offset_now;
  4101. self->content_offset_now = 0;
  4102. while (1) {
  4103. InstructUnit* ins_unit = instructArray_getNow(self);
  4104. if (NULL == ins_unit) {
  4105. goto __exit;
  4106. }
  4107. instructUnit_printWithConst(ins_unit, const_pool);
  4108. instructArray_getNext(self);
  4109. }
  4110. __exit:
  4111. self->content_offset_now = offset_befor;
  4112. return;
  4113. }
  4114. void instructArray_print(InstructArray* self) {
  4115. uint16_t offset_befor = self->content_offset_now;
  4116. self->content_offset_now = 0;
  4117. while (1) {
  4118. InstructUnit* ins_unit = instructArray_getNow(self);
  4119. if (NULL == ins_unit) {
  4120. goto __exit;
  4121. }
  4122. instructUnit_print(ins_unit);
  4123. instructArray_getNext(self);
  4124. }
  4125. __exit:
  4126. self->content_offset_now = offset_befor;
  4127. return;
  4128. }
  4129. void instructArray_printAsArray(InstructArray* self) {
  4130. uint16_t offset_befor = self->content_offset_now;
  4131. self->content_offset_now = 0;
  4132. uint8_t line_num = 12;
  4133. uint16_t g_i = 0;
  4134. uint8_t* ins_size_p = (uint8_t*)&self->size;
  4135. pika_platform_printf("0x%02x, ", *(ins_size_p));
  4136. pika_platform_printf("0x%02x, ", *(ins_size_p + (uintptr_t)1));
  4137. pika_platform_printf("0x%02x, ", *(ins_size_p + (uintptr_t)2));
  4138. pika_platform_printf("0x%02x, ", *(ins_size_p + (uintptr_t)3));
  4139. pika_platform_printf("/* instruct array size */\n");
  4140. while (1) {
  4141. InstructUnit* ins_unit = instructArray_getNow(self);
  4142. if (NULL == ins_unit) {
  4143. goto __exit;
  4144. }
  4145. for (int i = 0; i < (int)instructUnit_getSize(); i++) {
  4146. g_i++;
  4147. pika_platform_printf("0x%02x, ",
  4148. *((uint8_t*)ins_unit + (uintptr_t)i));
  4149. if (g_i % line_num == 0) {
  4150. pika_platform_printf("\n");
  4151. }
  4152. }
  4153. instructArray_getNext(self);
  4154. }
  4155. __exit:
  4156. pika_platform_printf("/* instruct array */\n");
  4157. self->content_offset_now = offset_befor;
  4158. return;
  4159. }
  4160. size_t byteCodeFrame_getSize(ByteCodeFrame* bf) {
  4161. return bf->const_pool.size + bf->instruct_array.size;
  4162. }
  4163. void byteCodeFrame_print(ByteCodeFrame* self) {
  4164. constPool_print(&(self->const_pool));
  4165. instructArray_printWithConst(&(self->instruct_array), &(self->const_pool));
  4166. pika_platform_printf("---------------\r\n");
  4167. pika_platform_printf("byte code size: %d\r\n",
  4168. self->const_pool.size + self->instruct_array.size);
  4169. }
  4170. PIKA_WEAK void pika_hook_unused_stack_arg(PikaVMFrame* vm, Arg* arg) {
  4171. if (vm->in_repl) {
  4172. arg_print(arg, pika_true, "\r\n");
  4173. }
  4174. }
  4175. void PikaVMFrame_solveUnusedStack(PikaVMFrame* vm) {
  4176. uint8_t top = stack_getTop(&(vm->stack));
  4177. for (int i = 0; i < top; i++) {
  4178. Arg* arg = stack_popArg_alloc(&(vm->stack));
  4179. ArgType type = arg_getType(arg);
  4180. if (type == ARG_TYPE_NONE) {
  4181. arg_deinit(arg);
  4182. continue;
  4183. }
  4184. if (vm->error.line_code != 0) {
  4185. arg_deinit(arg);
  4186. continue;
  4187. }
  4188. pika_hook_unused_stack_arg(vm, arg);
  4189. arg_deinit(arg);
  4190. }
  4191. }
  4192. PikaVMFrame* PikaVMFrame_create(VMParameters* locals,
  4193. VMParameters* globals,
  4194. ByteCodeFrame* bytecode_frame,
  4195. int32_t pc,
  4196. PikaVMThread* vm_thread) {
  4197. PikaVMFrame* vm = (PikaVMFrame*)pikaMalloc(sizeof(PikaVMFrame));
  4198. vm->bytecode_frame = bytecode_frame;
  4199. vm->locals = locals;
  4200. vm->globals = globals;
  4201. vm->pc = pc;
  4202. vm->vm_thread = vm_thread;
  4203. vm->jmp = 0;
  4204. vm->loop_deepth = 0;
  4205. pika_platform_memset(&vm->error, 0, sizeof(PikaVMError));
  4206. vm->ins_cnt = 0;
  4207. vm->in_super = pika_false;
  4208. vm->super_invoke_deepth = 0;
  4209. vm->in_repl = pika_false;
  4210. stack_init(&(vm->stack));
  4211. PikaVMFrame_initReg(vm);
  4212. return vm;
  4213. }
  4214. int PikaVMFrame_destroy(PikaVMFrame* vm) {
  4215. // PikaVMError* err = pikaVMThread_popError(vm->vm_thread);
  4216. // if (NULL != err) {
  4217. // pikaFree(err, sizeof(PikaVMError));
  4218. // }
  4219. stack_deinit(&(vm->stack));
  4220. pikaFree(vm, sizeof(PikaVMFrame));
  4221. return 0;
  4222. }
  4223. int pikaVMFrame_checkErrorCode(PikaVMFrame* state) {
  4224. pika_assert(NULL != state);
  4225. return state->error.code;
  4226. }
  4227. int pikaVMFrame_checkErrorStack(PikaVMFrame* vm) {
  4228. pika_assert(NULL != vm);
  4229. PIKA_RES code = pikaVMFrame_checkErrorCode(vm);
  4230. if (code != PIKA_RES_OK) {
  4231. return code;
  4232. }
  4233. if (NULL == vm->vm_thread->error_stack) {
  4234. return 0;
  4235. }
  4236. for (PikaVMError* current = vm->vm_thread->error_stack; current != NULL;
  4237. current = current->next) {
  4238. if (0 != current->code) {
  4239. return current->code;
  4240. }
  4241. }
  4242. return 0;
  4243. }
  4244. int pikaVMFrame_checkExceptionStack(PikaVMFrame* vm) {
  4245. pika_assert(NULL != vm);
  4246. if (NULL == vm->vm_thread->exception_stack) {
  4247. return 0;
  4248. }
  4249. for (PikaVMError* current = vm->vm_thread->exception_stack; current != NULL;
  4250. current = current->next) {
  4251. if (0 != current->code) {
  4252. return current->code;
  4253. }
  4254. }
  4255. return 0;
  4256. }
  4257. int pikaVMThread_pushError(PikaVMThread* vmThread, PikaVMError* error) {
  4258. pika_assert(NULL != vmThread);
  4259. pika_assert(NULL != error);
  4260. for (PikaVMError* current = vmThread->error_stack; current != NULL;
  4261. current = current->next) {
  4262. if (current == error) {
  4263. return 0;
  4264. }
  4265. }
  4266. PikaVMError* error_new = (PikaVMError*)pikaMalloc(sizeof(PikaVMError));
  4267. if (error_new == NULL) {
  4268. return -1;
  4269. }
  4270. pika_platform_memcpy(error_new, error, sizeof(PikaVMError));
  4271. error_new->next = vmThread->error_stack;
  4272. vmThread->error_stack = error_new;
  4273. vmThread->error_stack_deepth++;
  4274. if (vmThread->error_stack_deepth > vmThread->error_stack_deepth_max) {
  4275. vmThread->error_stack_deepth_max = vmThread->error_stack_deepth;
  4276. }
  4277. return 0;
  4278. }
  4279. PikaVMError* pikaVMThread_popError(PikaVMThread* vmThread) {
  4280. pika_assert(NULL != vmThread);
  4281. PikaVMError* error = vmThread->error_stack;
  4282. if (error != NULL) {
  4283. vmThread->error_stack = error->next;
  4284. vmThread->error_stack_deepth--;
  4285. }
  4286. return error;
  4287. }
  4288. PikaVMError* pikaVMThread_getErrorCurrent(PikaVMThread* vmThread) {
  4289. pika_assert(NULL != vmThread);
  4290. return vmThread->error_stack;
  4291. }
  4292. int pikaVMThread_clearErrorStack(PikaVMThread* vmThread) {
  4293. pika_assert(NULL != vmThread);
  4294. PikaVMError* current = vmThread->error_stack;
  4295. while (current != NULL) {
  4296. PikaVMError* next = current->next;
  4297. pikaFree(current, sizeof(PikaVMError));
  4298. vmThread->error_stack_deepth--;
  4299. current = next;
  4300. }
  4301. pika_assert(vmThread->error_stack_deepth == 0);
  4302. vmThread->error_stack = NULL;
  4303. return 0;
  4304. }
  4305. int pikaVMThread_clearExceptionStack(PikaVMThread* vmThread) {
  4306. pika_assert(NULL != vmThread);
  4307. PikaVMError* current = vmThread->exception_stack;
  4308. while (current != NULL) {
  4309. PikaVMError* next = current->next;
  4310. pikaFree(current, sizeof(PikaVMError));
  4311. current = next;
  4312. }
  4313. vmThread->exception_stack = NULL;
  4314. return 0;
  4315. }
  4316. int pikaVMThread_convertExceptionStack(PikaVMThread* vmThread) {
  4317. // Convert error stack to exception stack
  4318. pika_assert(NULL != vmThread);
  4319. if (NULL != vmThread->error_stack) {
  4320. vmThread->exception_stack = vmThread->error_stack;
  4321. }
  4322. vmThread->error_stack_deepth = 0;
  4323. vmThread->error_stack = NULL;
  4324. return 0;
  4325. }
  4326. static VMParameters* __pikaVM_runByteCodeFrameWithState(
  4327. PikaObj* self,
  4328. VMParameters* locals,
  4329. VMParameters* globals,
  4330. ByteCodeFrame* bytecode_frame,
  4331. uint16_t pc,
  4332. PikaVMThread* vm_thread,
  4333. pika_bool in_repl) {
  4334. pika_assert(NULL != vm_thread);
  4335. int size = bytecode_frame->instruct_array.size;
  4336. /* locals is the local scope */
  4337. if (g_PikaVMState.vm_cnt == 0) {
  4338. pika_vmSignal_setCtrlClear();
  4339. }
  4340. PikaVMFrame* vm =
  4341. PikaVMFrame_create(locals, globals, bytecode_frame, pc, vm_thread);
  4342. vm->in_repl = in_repl;
  4343. vm_thread->invoke_deepth++;
  4344. g_PikaVMState.vm_cnt++;
  4345. while (vm->pc < size) {
  4346. if (vm->pc == VM_PC_EXIT) {
  4347. break;
  4348. }
  4349. InstructUnit* this_ins_unit = PikaVMFrame_getInstructNow(vm);
  4350. uint8_t is_new_line = instructUnit_getIsNewLine(this_ins_unit);
  4351. if (is_new_line) {
  4352. PikaVMFrame_solveUnusedStack(vm);
  4353. stack_reset(&(vm->stack));
  4354. vm->error.code = 0;
  4355. vm->error.line_code = 0;
  4356. }
  4357. self->vmFrame = vm;
  4358. vm->pc = pikaVM_runInstructUnit(self, vm, this_ins_unit);
  4359. vm->ins_cnt++;
  4360. #if PIKA_INSTRUCT_HOOK_ENABLE
  4361. if (vm->ins_cnt % PIKA_INSTRUCT_HOOK_PERIOD == 0) {
  4362. pika_hook_instruct();
  4363. }
  4364. #endif
  4365. if (vm->ins_cnt % PIKA_INSTRUCT_YIELD_PERIOD == 0) {
  4366. _pikaVM_yield();
  4367. }
  4368. // push vm frame error to thread error stack
  4369. if (pikaVMFrame_checkErrorCode(vm) != PIKA_RES_OK) {
  4370. pikaVMThread_pushError(vm->vm_thread, &(vm->error));
  4371. }
  4372. // handle error
  4373. if (pikaVMFrame_checkErrorStack(vm) != PIKA_RES_OK) {
  4374. vm->error.line_code = vm->error.code;
  4375. InstructUnit* head_ins_unit = this_ins_unit;
  4376. /* get first ins of a line */
  4377. while (1) {
  4378. if (instructUnit_getIsNewLine(head_ins_unit)) {
  4379. break;
  4380. }
  4381. head_ins_unit--;
  4382. }
  4383. if (vm->vm_thread->try_state == TRY_STATE_NONE) {
  4384. while (1) {
  4385. if (head_ins_unit != this_ins_unit) {
  4386. pika_platform_printf(" ");
  4387. } else {
  4388. pika_platform_printf(" -> ");
  4389. }
  4390. instructUnit_printWithConst(head_ins_unit,
  4391. &(bytecode_frame->const_pool));
  4392. head_ins_unit++;
  4393. if (head_ins_unit > this_ins_unit) {
  4394. break;
  4395. }
  4396. }
  4397. }
  4398. pika_platform_error_handle();
  4399. }
  4400. }
  4401. PikaVMFrame_solveUnusedStack(vm);
  4402. PikaVMFrame_destroy(vm);
  4403. self->vmFrame = NULL;
  4404. VMParameters* result = locals;
  4405. pika_assert(vm_thread->invoke_deepth > 0);
  4406. vm_thread->invoke_deepth--;
  4407. uint8_t vm_thread_deepth = vm_thread->invoke_deepth;
  4408. uint8_t vm_thread_is_sub_thread = vm_thread->is_sub_thread;
  4409. if (vm_thread_deepth == 0) {
  4410. pikaVMThread_delete();
  4411. }
  4412. g_PikaVMState.vm_cnt--;
  4413. if ((vm_thread_deepth == 0) && (!vm_thread_is_sub_thread)) {
  4414. if (VMSignal_getCtrl() == VM_SIGNAL_CTRL_EXIT) {
  4415. // wait other sub thread to exit
  4416. while (_VMEvent_getVMCnt() > 0) {
  4417. pika_GIL_EXIT();
  4418. pika_platform_thread_yield();
  4419. pika_GIL_ENTER();
  4420. }
  4421. }
  4422. }
  4423. return result;
  4424. }
  4425. pika_bool pika_debug_check_break(char* module_name, int pc_break) {
  4426. Hash h = hash_time33(module_name);
  4427. for (int i = 0; i < g_PikaVMState.break_point_cnt; i++) {
  4428. if (g_PikaVMState.break_module_hash[i] == h &&
  4429. g_PikaVMState.break_point_pc[i] == pc_break) {
  4430. return pika_true;
  4431. }
  4432. }
  4433. return pika_false;
  4434. }
  4435. pika_bool pika_debug_check_break_hash(Hash module_hash, int pc_break) {
  4436. for (int i = 0; i < g_PikaVMState.break_point_cnt; i++) {
  4437. if (g_PikaVMState.break_module_hash[i] == module_hash &&
  4438. g_PikaVMState.break_point_pc[i] == pc_break) {
  4439. return pika_true;
  4440. }
  4441. }
  4442. return pika_false;
  4443. }
  4444. PIKA_RES pika_debug_set_break(char* module_name, int pc_break) {
  4445. if (pika_debug_check_break(module_name, pc_break)) {
  4446. return PIKA_RES_OK;
  4447. }
  4448. if (g_PikaVMState.break_point_cnt >= PIKA_DEBUG_BREAK_POINT_MAX) {
  4449. return PIKA_RES_ERR_RUNTIME_ERROR;
  4450. }
  4451. Hash h = hash_time33(module_name);
  4452. g_PikaVMState.break_module_hash[g_PikaVMState.break_point_cnt] = h;
  4453. g_PikaVMState.break_point_pc[g_PikaVMState.break_point_cnt] = pc_break;
  4454. g_PikaVMState.break_point_cnt++;
  4455. return PIKA_RES_OK;
  4456. }
  4457. PIKA_RES pika_debug_reset_break(char* module_name, int pc_break) {
  4458. if (!pika_debug_check_break(module_name, pc_break)) {
  4459. return PIKA_RES_OK;
  4460. }
  4461. Hash h = hash_time33(module_name);
  4462. for (int i = 0; i < g_PikaVMState.break_point_cnt; i++) {
  4463. if (g_PikaVMState.break_module_hash[i] == h &&
  4464. g_PikaVMState.break_point_pc[i] == pc_break) {
  4465. // Move subsequent break points one position forward
  4466. for (int j = i; j < g_PikaVMState.break_point_cnt - 1; j++) {
  4467. g_PikaVMState.break_module_hash[j] =
  4468. g_PikaVMState.break_module_hash[j + 1];
  4469. g_PikaVMState.break_point_pc[j] =
  4470. g_PikaVMState.break_point_pc[j + 1];
  4471. }
  4472. // Decrease the count of break points
  4473. g_PikaVMState.break_point_cnt--;
  4474. return PIKA_RES_OK;
  4475. }
  4476. }
  4477. return PIKA_RES_ERR_RUNTIME_ERROR;
  4478. }
  4479. static VMParameters* _pikaVM_runByteCodeFrameWithState(
  4480. PikaObj* self,
  4481. VMParameters* locals,
  4482. VMParameters* globals,
  4483. ByteCodeFrame* bytecode_frame,
  4484. uint16_t pc,
  4485. PikaVMThread* vm_thread) {
  4486. return __pikaVM_runByteCodeFrameWithState(
  4487. self, locals, globals, bytecode_frame, pc, vm_thread, pika_false);
  4488. }
  4489. static PikaVMThread* g_pika_vm_state_head = NULL;
  4490. int pikaVMThread_init(PikaVMThread* vmThread, uint64_t thread_id) {
  4491. vmThread->thread_id = thread_id;
  4492. vmThread->invoke_deepth = 0;
  4493. vmThread->error_stack = NULL;
  4494. vmThread->exception_stack = NULL;
  4495. vmThread->error_stack_deepth = 0;
  4496. vmThread->error_stack_deepth_max = 0;
  4497. pika_platform_memset(&vmThread->try_state, 0, sizeof(TRY_STATE));
  4498. pika_platform_memset(&vmThread->try_result, 0, sizeof(TRY_RESULT));
  4499. vmThread->next = NULL;
  4500. vmThread->is_sub_thread = 0;
  4501. return 0;
  4502. }
  4503. PikaVMThread* pikaVMThread_create(uint64_t thread_id) {
  4504. PikaVMThread* vm_state = (PikaVMThread*)pikaMalloc(sizeof(PikaVMThread));
  4505. if (vm_state == NULL) {
  4506. return NULL;
  4507. }
  4508. pikaVMThread_init(vm_state, thread_id);
  4509. return vm_state;
  4510. }
  4511. void pikaVMThread_destroy(PikaVMThread* state) {
  4512. pikaVMThread_clearErrorStack(state);
  4513. pikaVMThread_clearExceptionStack(state);
  4514. if (state != NULL) {
  4515. pikaFree(state, sizeof(PikaVMThread));
  4516. }
  4517. }
  4518. PikaVMThread* pikaVMThread_find_node_by_thread_id(uint64_t thread_id) {
  4519. PikaVMThread* current = g_pika_vm_state_head;
  4520. while (current != NULL) {
  4521. if (current->thread_id == thread_id) {
  4522. return current;
  4523. }
  4524. current = current->next;
  4525. }
  4526. return NULL;
  4527. }
  4528. PikaVMThread* pikaVMThread_require(void) {
  4529. uint64_t current_thread_id = pika_platform_thread_self();
  4530. PikaVMThread* state =
  4531. pikaVMThread_find_node_by_thread_id(current_thread_id);
  4532. if (state != NULL) {
  4533. return state;
  4534. }
  4535. PikaVMThread* new_state = pikaVMThread_create(current_thread_id);
  4536. if (new_state == NULL) {
  4537. return NULL;
  4538. }
  4539. new_state->next = g_pika_vm_state_head;
  4540. g_pika_vm_state_head = new_state;
  4541. return new_state;
  4542. }
  4543. void pikaVMThread_delete(void) {
  4544. uint64_t current_thread_id = pika_platform_thread_self();
  4545. PikaVMThread* current = g_pika_vm_state_head;
  4546. PikaVMThread* previous = NULL;
  4547. while (current != NULL) {
  4548. if (current->thread_id == current_thread_id) {
  4549. if (previous == NULL) {
  4550. g_pika_vm_state_head = current->next;
  4551. } else {
  4552. previous->next = current->next;
  4553. }
  4554. pikaVMThread_destroy(current);
  4555. return;
  4556. }
  4557. previous = current;
  4558. current = current->next;
  4559. }
  4560. }
  4561. VMParameters* _pikaVM_runByteCodeFrame(PikaObj* self,
  4562. ByteCodeFrame* byteCode_frame,
  4563. pika_bool in_repl) {
  4564. PikaVMThread* vm_thread = pikaVMThread_require();
  4565. return __pikaVM_runByteCodeFrameWithState(self, self, self, byteCode_frame,
  4566. 0, vm_thread, in_repl);
  4567. }
  4568. VMParameters* _pikaVM_runByteCodeFrameGlobals(PikaObj* self,
  4569. PikaObj* globals,
  4570. ByteCodeFrame* byteCode_frame,
  4571. pika_bool in_repl) {
  4572. PikaVMThread* vm_thread = pikaVMThread_require();
  4573. return __pikaVM_runByteCodeFrameWithState(
  4574. self, self, globals, byteCode_frame, 0, vm_thread, in_repl);
  4575. }
  4576. VMParameters* pikaVM_runByteCodeFrame(PikaObj* self,
  4577. ByteCodeFrame* byteCode_frame) {
  4578. return _pikaVM_runByteCodeFrame(self, byteCode_frame, pika_false);
  4579. }
  4580. void constPool_printAsArray(ConstPool* self) {
  4581. uint8_t* const_size_str = (uint8_t*)&(self->size);
  4582. pika_platform_printf("0x%02x, ", *(const_size_str));
  4583. pika_platform_printf("0x%02x, ", *(const_size_str + (uintptr_t)1));
  4584. pika_platform_printf("0x%02x, ", *(const_size_str + (uintptr_t)2));
  4585. pika_platform_printf("0x%02x, ", *(const_size_str + (uintptr_t)3));
  4586. pika_platform_printf("/* const pool size */\n");
  4587. uint16_t ptr_befor = self->content_offset_now;
  4588. uint8_t line_num = 12;
  4589. uint16_t g_i = 0;
  4590. /* set ptr_now to begin */
  4591. self->content_offset_now = 0;
  4592. pika_platform_printf("0x00, ");
  4593. while (1) {
  4594. if (NULL == constPool_getNext(self)) {
  4595. goto __exit;
  4596. }
  4597. char* data_each = constPool_getNow(self);
  4598. /* todo start */
  4599. size_t len = strlen(data_each);
  4600. for (uint32_t i = 0; i < len + 1; i++) {
  4601. pika_platform_printf("0x%02x, ", *(data_each + (uintptr_t)i));
  4602. g_i++;
  4603. if (g_i % line_num == 0) {
  4604. pika_platform_printf("\n");
  4605. }
  4606. }
  4607. /* todo end */
  4608. }
  4609. __exit:
  4610. /* retore ptr_now */
  4611. pika_platform_printf("/* const pool */\n");
  4612. self->content_offset_now = ptr_befor;
  4613. return;
  4614. }
  4615. void byteCodeFrame_printAsArray(ByteCodeFrame* self) {
  4616. pika_platform_printf("const uint8_t bytes[] = {\n");
  4617. instructArray_printAsArray(&(self->instruct_array));
  4618. constPool_printAsArray(&(self->const_pool));
  4619. pika_platform_printf("};\n");
  4620. pika_platform_printf("pikaVM_runByteCode(self, (uint8_t*)bytes);\n");
  4621. }
  4622. PikaObj* pikaVM_runFile(PikaObj* self, char* file_name) {
  4623. Args buffs = {0};
  4624. char* module_name = strsPathGetFileName(&buffs, file_name);
  4625. strPopLastToken(module_name, '.');
  4626. char* pwd = strsPathGetFolder(&buffs, file_name);
  4627. pika_platform_printf("(pikascript) pika compiler:\r\n");
  4628. PikaMaker* maker = New_PikaMaker();
  4629. pikaMaker_setPWD(maker, pwd);
  4630. pikaMaker_compileModuleWithDepends(maker, module_name);
  4631. _do_pikaMaker_linkCompiledModules(maker, "pikaModules_cache.py.a",
  4632. pika_false);
  4633. pikaMaker_deinit(maker);
  4634. pika_platform_printf("(pikascript) all succeed.\r\n\r\n");
  4635. pikaMemMaxReset();
  4636. char* libfile_path =
  4637. strsPathJoin(&buffs, pwd, "pikascript-api/pikaModules_cache.py.a");
  4638. if (PIKA_RES_OK == obj_linkLibraryFile(self, libfile_path)) {
  4639. obj_runModule(self, module_name);
  4640. }
  4641. strsDeinit(&buffs);
  4642. return self;
  4643. }
  4644. void _pikaVM_yield(void) {
  4645. #if PIKA_EVENT_ENABLE
  4646. if (!pika_GIL_isInit()) {
  4647. _VMEvent_pickupEvent();
  4648. }
  4649. #endif
  4650. /*
  4651. * [Warning!] Can not use pika_GIL_ENTER() and pika_GIL_EXIT() here,
  4652. * because yield() is called not atomically, and it will cause data
  4653. * race.
  4654. */
  4655. // pika_GIL_EXIT();
  4656. // pika_GIL_ENTER();
  4657. }