as_scriptengine.cpp 159 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2013 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. //
  24. // as_scriptengine.cpp
  25. //
  26. // The implementation of the script engine interface
  27. //
  28. #include <stdlib.h>
  29. #include "as_config.h"
  30. #include "as_scriptengine.h"
  31. #include "as_builder.h"
  32. #include "as_context.h"
  33. #include "as_string_util.h"
  34. #include "as_tokenizer.h"
  35. #include "as_texts.h"
  36. #include "as_module.h"
  37. #include "as_callfunc.h"
  38. #include "as_generic.h"
  39. #include "as_scriptobject.h"
  40. #include "as_compiler.h"
  41. #include "as_bytecode.h"
  42. #include "as_debug.h"
  43. BEGIN_AS_NAMESPACE
  44. #ifdef AS_PROFILE
  45. // Instanciate the profiler once
  46. CProfiler g_profiler;
  47. #endif
  48. extern "C"
  49. {
  50. AS_API const char * asGetLibraryVersion()
  51. {
  52. #ifdef _DEBUG
  53. return ANGELSCRIPT_VERSION_STRING " DEBUG";
  54. #else
  55. return ANGELSCRIPT_VERSION_STRING;
  56. #endif
  57. }
  58. AS_API const char * asGetLibraryOptions()
  59. {
  60. const char *string = " "
  61. // Options
  62. #ifdef AS_MAX_PORTABILITY
  63. "AS_MAX_PORTABILITY "
  64. #endif
  65. #ifdef AS_DEBUG
  66. "AS_DEBUG "
  67. #endif
  68. #ifdef AS_NO_CLASS_METHODS
  69. "AS_NO_CLASS_METHODS "
  70. #endif
  71. #ifdef AS_USE_DOUBLE_AS_FLOAT
  72. "AS_USE_DOUBLE_AS_FLOAT "
  73. #endif
  74. #ifdef AS_64BIT_PTR
  75. "AS_64BIT_PTR "
  76. #endif
  77. #ifdef AS_NO_THREADS
  78. "AS_NO_THREADS "
  79. #endif
  80. #ifdef AS_NO_ATOMIC
  81. "AS_NO_ATOMIC "
  82. #endif
  83. #ifdef AS_NO_COMPILER
  84. "AS_NO_COMPILER "
  85. #endif
  86. #ifdef AS_NO_MEMBER_INIT
  87. "AS_NO_MEMBER_INIT "
  88. #endif
  89. // Target system
  90. #ifdef AS_WIN
  91. "AS_WIN "
  92. #endif
  93. #ifdef AS_LINUX
  94. "AS_LINUX "
  95. #endif
  96. #ifdef AS_MAC
  97. "AS_MAC "
  98. #endif
  99. #ifdef AS_BSD
  100. "AS_BSD "
  101. #endif
  102. #ifdef AS_XBOX
  103. "AS_XBOX "
  104. #endif
  105. #ifdef AS_XBOX360
  106. "AS_XBOX360 "
  107. #endif
  108. #ifdef AS_PSP
  109. "AS_PSP "
  110. #endif
  111. #ifdef AS_PS2
  112. "AS_PS2 "
  113. #endif
  114. #ifdef AS_PS3
  115. "AS_PS3 "
  116. #endif
  117. #ifdef AS_DC
  118. "AS_DC "
  119. #endif
  120. #ifdef AS_GC
  121. "AS_GC "
  122. #endif
  123. #ifdef AS_WII
  124. "AS_WII "
  125. #endif
  126. #ifdef AS_WIIU
  127. "AS_WIIU "
  128. #endif
  129. #ifdef AS_IPHONE
  130. "AS_IPHONE "
  131. #endif
  132. #ifdef AS_ANDROID
  133. "AS_ANDROID "
  134. #endif
  135. #ifdef AS_HAIKU
  136. "AS_HAIKU "
  137. #endif
  138. #ifdef AS_ILLUMOS
  139. "AS_ILLUMOS "
  140. #endif
  141. #ifdef AS_MARMALADE
  142. "AS_MARMALADE "
  143. #endif
  144. // CPU family
  145. #ifdef AS_PPC
  146. "AS_PPC "
  147. #endif
  148. #ifdef AS_PPC_64
  149. "AS_PPC_64 "
  150. #endif
  151. #ifdef AS_X86
  152. "AS_X86 "
  153. #endif
  154. #ifdef AS_MIPS
  155. "AS_MIPS "
  156. #endif
  157. #ifdef AS_SH4
  158. "AS_SH4 "
  159. #endif
  160. #ifdef AS_XENON
  161. "AS_XENON "
  162. #endif
  163. #ifdef AS_ARM
  164. "AS_ARM "
  165. #endif
  166. #ifdef AS_X64_GCC
  167. "AS_X64_GCC "
  168. #endif
  169. #ifdef AS_X64_MSVC
  170. "AS_X64_MSVC "
  171. #endif
  172. ;
  173. return string;
  174. }
  175. AS_API asIScriptEngine *asCreateScriptEngine(asDWORD version)
  176. {
  177. // Verify the version that the application expects
  178. if( (version/10000) != (ANGELSCRIPT_VERSION/10000) )
  179. return 0;
  180. if( (version/100)%100 != (ANGELSCRIPT_VERSION/100)%100 )
  181. return 0;
  182. if( (version%100) > (ANGELSCRIPT_VERSION%100) )
  183. return 0;
  184. // Verify the size of the types
  185. asASSERT( sizeof(asBYTE) == 1 );
  186. asASSERT( sizeof(asWORD) == 2 );
  187. asASSERT( sizeof(asDWORD) == 4 );
  188. asASSERT( sizeof(asQWORD) == 8 );
  189. asASSERT( sizeof(asPWORD) == sizeof(void*) );
  190. // Verify the boolean type
  191. asASSERT( sizeof(bool) == AS_SIZEOF_BOOL );
  192. asASSERT( true == VALUE_OF_BOOLEAN_TRUE );
  193. // Verify endianess
  194. #ifdef AS_BIG_ENDIAN
  195. asASSERT( *(asDWORD*)"\x00\x01\x02\x03" == 0x00010203 );
  196. asASSERT( *(asQWORD*)"\x00\x01\x02\x03\x04\x05\x06\x07" == ((asQWORD(0x00010203)<<32)|asQWORD(0x04050607)) );
  197. #else
  198. asASSERT( *(asDWORD*)"\x00\x01\x02\x03" == 0x03020100 );
  199. // C++ didn't have a standard way of declaring 64bit literal constants until C++11, so
  200. // I'm forced to do it like this to avoid compilers warnings when compiling with the full
  201. // C++ compliance.
  202. asASSERT( *(asQWORD*)"\x00\x01\x02\x03\x04\x05\x06\x07" == ((asQWORD(0x07060504)<<32)|asQWORD(0x03020100)) );
  203. #endif
  204. return asNEW(asCScriptEngine)();
  205. }
  206. } // extern "C"
  207. // interface
  208. int asCScriptEngine::SetEngineProperty(asEEngineProp property, asPWORD value)
  209. {
  210. switch( property )
  211. {
  212. case asEP_ALLOW_UNSAFE_REFERENCES:
  213. ep.allowUnsafeReferences = value ? true : false;
  214. break;
  215. case asEP_OPTIMIZE_BYTECODE:
  216. ep.optimizeByteCode = value ? true : false;
  217. break;
  218. case asEP_COPY_SCRIPT_SECTIONS:
  219. ep.copyScriptSections = value ? true : false;
  220. break;
  221. case asEP_MAX_STACK_SIZE:
  222. if( value == 0 )
  223. {
  224. // Restore default: no limit and initially size 4KB
  225. ep.maximumContextStackSize = 0;
  226. initialContextStackSize = 1024;
  227. }
  228. else
  229. {
  230. // The size is given in bytes, but we only store dwords
  231. ep.maximumContextStackSize = (asUINT)value/4;
  232. if( initialContextStackSize > ep.maximumContextStackSize )
  233. {
  234. initialContextStackSize = ep.maximumContextStackSize;
  235. if( initialContextStackSize == 0 )
  236. initialContextStackSize = 1;
  237. }
  238. }
  239. break;
  240. case asEP_USE_CHARACTER_LITERALS:
  241. ep.useCharacterLiterals = value ? true : false;
  242. break;
  243. case asEP_ALLOW_MULTILINE_STRINGS:
  244. ep.allowMultilineStrings = value ? true : false;
  245. break;
  246. case asEP_ALLOW_IMPLICIT_HANDLE_TYPES:
  247. ep.allowImplicitHandleTypes = value ? true : false;
  248. break;
  249. case asEP_BUILD_WITHOUT_LINE_CUES:
  250. ep.buildWithoutLineCues = value ? true : false;
  251. break;
  252. case asEP_INIT_GLOBAL_VARS_AFTER_BUILD:
  253. ep.initGlobalVarsAfterBuild = value ? true : false;
  254. break;
  255. case asEP_REQUIRE_ENUM_SCOPE:
  256. ep.requireEnumScope = value ? true : false;
  257. break;
  258. case asEP_SCRIPT_SCANNER:
  259. if( value <= 1 )
  260. ep.scanner = (int)value;
  261. else
  262. return asINVALID_ARG;
  263. break;
  264. case asEP_INCLUDE_JIT_INSTRUCTIONS:
  265. ep.includeJitInstructions = value ? true : false;
  266. break;
  267. case asEP_STRING_ENCODING:
  268. if( value <= 1 )
  269. ep.stringEncoding = (int)value;
  270. else
  271. return asINVALID_ARG;
  272. break;
  273. case asEP_PROPERTY_ACCESSOR_MODE:
  274. if( value <= 2 )
  275. ep.propertyAccessorMode = (int)value;
  276. else
  277. return asINVALID_ARG;
  278. break;
  279. case asEP_EXPAND_DEF_ARRAY_TO_TMPL:
  280. ep.expandDefaultArrayToTemplate = value ? true : false;
  281. break;
  282. case asEP_AUTO_GARBAGE_COLLECT:
  283. ep.autoGarbageCollect = value ? true : false;
  284. break;
  285. case asEP_DISALLOW_GLOBAL_VARS:
  286. ep.disallowGlobalVars = value ? true : false;
  287. break;
  288. case asEP_ALWAYS_IMPL_DEFAULT_CONSTRUCT:
  289. ep.alwaysImplDefaultConstruct = value ? true : false;
  290. break;
  291. case asEP_COMPILER_WARNINGS:
  292. if( value <= 2 )
  293. ep.compilerWarnings = (int)value;
  294. else
  295. return asINVALID_ARG;
  296. break;
  297. case asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE:
  298. ep.disallowValueAssignForRefType = value ? true : false;
  299. break;
  300. default:
  301. return asINVALID_ARG;
  302. }
  303. return asSUCCESS;
  304. }
  305. // interface
  306. asPWORD asCScriptEngine::GetEngineProperty(asEEngineProp property) const
  307. {
  308. switch( property )
  309. {
  310. case asEP_ALLOW_UNSAFE_REFERENCES:
  311. return ep.allowUnsafeReferences;
  312. case asEP_OPTIMIZE_BYTECODE:
  313. return ep.optimizeByteCode;
  314. case asEP_COPY_SCRIPT_SECTIONS:
  315. return ep.copyScriptSections;
  316. case asEP_MAX_STACK_SIZE:
  317. return ep.maximumContextStackSize*4;
  318. case asEP_USE_CHARACTER_LITERALS:
  319. return ep.useCharacterLiterals;
  320. case asEP_ALLOW_MULTILINE_STRINGS:
  321. return ep.allowMultilineStrings;
  322. case asEP_ALLOW_IMPLICIT_HANDLE_TYPES:
  323. return ep.allowImplicitHandleTypes;
  324. case asEP_BUILD_WITHOUT_LINE_CUES:
  325. return ep.buildWithoutLineCues;
  326. case asEP_INIT_GLOBAL_VARS_AFTER_BUILD:
  327. return ep.initGlobalVarsAfterBuild;
  328. case asEP_REQUIRE_ENUM_SCOPE:
  329. return ep.requireEnumScope;
  330. case asEP_SCRIPT_SCANNER:
  331. return ep.scanner;
  332. case asEP_INCLUDE_JIT_INSTRUCTIONS:
  333. return ep.includeJitInstructions;
  334. case asEP_STRING_ENCODING:
  335. return ep.stringEncoding;
  336. case asEP_PROPERTY_ACCESSOR_MODE:
  337. return ep.propertyAccessorMode;
  338. case asEP_EXPAND_DEF_ARRAY_TO_TMPL:
  339. return ep.expandDefaultArrayToTemplate;
  340. case asEP_AUTO_GARBAGE_COLLECT:
  341. return ep.autoGarbageCollect;
  342. case asEP_DISALLOW_GLOBAL_VARS:
  343. return ep.disallowGlobalVars;
  344. case asEP_ALWAYS_IMPL_DEFAULT_CONSTRUCT:
  345. return ep.alwaysImplDefaultConstruct;
  346. case asEP_COMPILER_WARNINGS:
  347. return ep.compilerWarnings;
  348. case asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE:
  349. return ep.disallowValueAssignForRefType;
  350. }
  351. return 0;
  352. }
  353. // interface
  354. asIScriptFunction *asCScriptEngine::CreateDelegate(asIScriptFunction *func, void *obj)
  355. {
  356. if( func == 0 || obj == 0 )
  357. return 0;
  358. // The function must be a class method
  359. asIObjectType *type = func->GetObjectType();
  360. if( type == 0 )
  361. return 0;
  362. // The object type must allow handles
  363. if( (type->GetFlags() & asOBJ_REF) == 0 || (type->GetFlags() & (asOBJ_SCOPED | asOBJ_NOHANDLE)) )
  364. return 0;
  365. // Create the delegate the same way it would be created by the scripts
  366. return AS_NAMESPACE_QUALIFIER CreateDelegate(reinterpret_cast<asCScriptFunction*>(func), obj);
  367. }
  368. asCScriptEngine::asCScriptEngine()
  369. {
  370. asCThreadManager::Prepare(0);
  371. shuttingDown = false;
  372. // Engine properties
  373. {
  374. ep.allowUnsafeReferences = false;
  375. ep.optimizeByteCode = true;
  376. ep.copyScriptSections = true;
  377. ep.maximumContextStackSize = 0; // no limit
  378. ep.useCharacterLiterals = false;
  379. ep.allowMultilineStrings = false;
  380. ep.allowImplicitHandleTypes = false;
  381. // TODO: optimize: Maybe this should be turned off by default? If a debugger is not used
  382. // then this is just slowing down the execution.
  383. ep.buildWithoutLineCues = false;
  384. ep.initGlobalVarsAfterBuild = true;
  385. ep.requireEnumScope = false;
  386. ep.scanner = 1; // utf8. 0 = ascii
  387. ep.includeJitInstructions = false;
  388. ep.stringEncoding = 0; // utf8. 1 = utf16
  389. ep.propertyAccessorMode = 2; // 0 = disable, 1 = app registered only, 2 = app and script created
  390. ep.expandDefaultArrayToTemplate = false;
  391. ep.autoGarbageCollect = true;
  392. ep.disallowGlobalVars = false;
  393. ep.alwaysImplDefaultConstruct = false;
  394. ep.compilerWarnings = 1; // 0 = no warnings, 1 = warning, 2 = treat as error
  395. // TODO: 3.0.0: disallowValueAssignForRefType should be true by default
  396. ep.disallowValueAssignForRefType = false;
  397. }
  398. gc.engine = this;
  399. tok.engine = this;
  400. refCount.set(1);
  401. stringFactory = 0;
  402. configFailed = false;
  403. isPrepared = false;
  404. isBuilding = false;
  405. deferValidationOfTemplateTypes = false;
  406. lastModule = 0;
  407. // User data
  408. cleanModuleFunc = 0;
  409. cleanContextFunc = 0;
  410. cleanFunctionFunc = 0;
  411. initialContextStackSize = 1024; // 4 KB (1024 * sizeof(asDWORD)
  412. typeIdSeqNbr = 0;
  413. currentGroup = &defaultGroup;
  414. defaultAccessMask = 1;
  415. msgCallback = 0;
  416. jitCompiler = 0;
  417. // Create the global namespace
  418. defaultNamespace = AddNameSpace("");
  419. // We must set the namespace in the built-in types explicitly as
  420. // this wasn't done by the default constructor. If we do not do
  421. // this we will get null pointer access in other parts of the code
  422. scriptTypeBehaviours.nameSpace = defaultNamespace;
  423. functionBehaviours.nameSpace = defaultNamespace;
  424. objectTypeBehaviours.nameSpace = defaultNamespace;
  425. globalPropertyBehaviours.nameSpace = defaultNamespace;
  426. // Reserve function id 0 for no function
  427. scriptFunctions.PushLast(0);
  428. // Make sure typeId for the built-in primitives are defined according to asETypeIdFlags
  429. int id = 0;
  430. UNUSED_VAR(id); // It is only used in debug mode
  431. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttVoid, false)); asASSERT( id == asTYPEID_VOID );
  432. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttBool, false)); asASSERT( id == asTYPEID_BOOL );
  433. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt8, false)); asASSERT( id == asTYPEID_INT8 );
  434. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt16, false)); asASSERT( id == asTYPEID_INT16 );
  435. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt, false)); asASSERT( id == asTYPEID_INT32 );
  436. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt64, false)); asASSERT( id == asTYPEID_INT64 );
  437. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt8, false)); asASSERT( id == asTYPEID_UINT8 );
  438. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt16, false)); asASSERT( id == asTYPEID_UINT16 );
  439. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt, false)); asASSERT( id == asTYPEID_UINT32 );
  440. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt64, false)); asASSERT( id == asTYPEID_UINT64 );
  441. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttFloat, false)); asASSERT( id == asTYPEID_FLOAT );
  442. id = GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttDouble, false)); asASSERT( id == asTYPEID_DOUBLE );
  443. defaultArrayObjectType = 0;
  444. RegisterScriptObject(this);
  445. RegisterScriptFunction(this);
  446. RegisterObjectTypeGCBehaviours(this);
  447. asCGlobalProperty::RegisterGCBehaviours(this);
  448. }
  449. asCScriptEngine::~asCScriptEngine()
  450. {
  451. shuttingDown = true;
  452. asASSERT(refCount.get() == 0);
  453. asUINT n;
  454. // The modules must be deleted first, as they may use
  455. // object types from the config groups
  456. for( n = (asUINT)scriptModules.GetLength(); n-- > 0; )
  457. if( scriptModules[n] )
  458. scriptModules[n]->Discard();
  459. scriptModules.SetLength(0);
  460. GarbageCollect();
  461. // Delete the functions for template types that may references object types
  462. for( n = 0; n < templateTypes.GetLength(); n++ )
  463. {
  464. if( templateTypes[n] )
  465. {
  466. asUINT f;
  467. // Delete the factory stubs first
  468. for( f = 0; f < templateTypes[n]->beh.factories.GetLength(); f++ )
  469. scriptFunctions[templateTypes[n]->beh.factories[f]]->Release();
  470. templateTypes[n]->beh.factories.Allocate(0, false);
  471. // The list factory is not stored in the list with the rest of the factories
  472. if( templateTypes[n]->beh.listFactory )
  473. {
  474. scriptFunctions[templateTypes[n]->beh.listFactory]->Release();
  475. templateTypes[n]->beh.listFactory = 0;
  476. }
  477. // Delete the specialized functions
  478. for( f = 1; f < templateTypes[n]->beh.operators.GetLength(); f += 2 )
  479. {
  480. if( scriptFunctions[templateTypes[n]->beh.operators[f]]->objectType == templateTypes[n] )
  481. {
  482. scriptFunctions[templateTypes[n]->beh.operators[f]]->Release();
  483. templateTypes[n]->beh.operators[f] = 0;
  484. }
  485. }
  486. for( f = 0; f < templateTypes[n]->methods.GetLength(); f++ )
  487. {
  488. if( scriptFunctions[templateTypes[n]->methods[f]]->objectType == templateTypes[n] )
  489. {
  490. scriptFunctions[templateTypes[n]->methods[f]]->Release();
  491. templateTypes[n]->methods[f] = 0;
  492. }
  493. }
  494. }
  495. }
  496. // Do one more garbage collect to free gc objects that were global variables
  497. GarbageCollect();
  498. FreeUnusedGlobalProperties();
  499. ClearUnusedTypes();
  500. // Break all relationship between remaining class types and functions
  501. for( n = 0; n < classTypes.GetLength(); n++ )
  502. {
  503. if( classTypes[n] )
  504. classTypes[n]->ReleaseAllFunctions();
  505. if( classTypes[n]->derivedFrom )
  506. {
  507. classTypes[n]->derivedFrom->Release();
  508. classTypes[n]->derivedFrom = 0;
  509. }
  510. }
  511. GarbageCollect(asGC_FULL_CYCLE);
  512. FreeUnusedGlobalProperties();
  513. ClearUnusedTypes();
  514. // Destroy internals of script functions that may still be kept alive outside of engine
  515. for( n = 0; n < scriptFunctions.GetLength(); n++ )
  516. if( scriptFunctions[n] && scriptFunctions[n]->funcType == asFUNC_SCRIPT )
  517. scriptFunctions[n]->DestroyInternal();
  518. // There may be instances where one more gc cycle must be run
  519. GarbageCollect(asGC_FULL_CYCLE);
  520. ClearUnusedTypes();
  521. // If the application hasn't registered GC behaviours for all types
  522. // that can form circular references with script types, then there
  523. // may still be objects in the GC.
  524. if( gc.ReportAndReleaseUndestroyedObjects() > 0 )
  525. {
  526. // Some items cannot be destroyed because the application is still holding on to them
  527. // Make sure the script functions won't attempt to access the engine if they are destroyed later on
  528. for( n = 0; n < scriptFunctions.GetLength(); n++ )
  529. if( scriptFunctions[n] && scriptFunctions[n]->funcType == asFUNC_SCRIPT )
  530. scriptFunctions[n]->engine = 0;
  531. }
  532. asSMapNode<int,asCDataType*> *cursor = 0;
  533. while( mapTypeIdToDataType.MoveFirst(&cursor) )
  534. {
  535. asDELETE(mapTypeIdToDataType.GetValue(cursor),asCDataType);
  536. mapTypeIdToDataType.Erase(cursor);
  537. }
  538. // First remove what is not used, so that other groups can be deleted safely
  539. defaultGroup.RemoveConfiguration(this, true);
  540. while( configGroups.GetLength() )
  541. {
  542. // Delete config groups in the right order
  543. asCConfigGroup *grp = configGroups.PopLast();
  544. if( grp )
  545. {
  546. grp->RemoveConfiguration(this);
  547. asDELETE(grp,asCConfigGroup);
  548. }
  549. }
  550. // Remove what is remaining
  551. defaultGroup.RemoveConfiguration(this);
  552. asCSymbolTable<asCGlobalProperty>::iterator it = registeredGlobalProps.List();
  553. for( ; it; it++ )
  554. (*it)->Release();
  555. registeredGlobalProps.Clear();
  556. FreeUnusedGlobalProperties();
  557. for( n = 0; n < templateTypes.GetLength(); n++ )
  558. {
  559. if( templateTypes[n] )
  560. {
  561. // Clear the sub types before deleting the template type so that the sub types aren't freed to soon
  562. templateTypes[n]->templateSubTypes.SetLength(0);
  563. asDELETE(templateTypes[n],asCObjectType);
  564. }
  565. }
  566. templateTypes.SetLength(0);
  567. for( n = 0; n < objectTypes.GetLength(); n++ )
  568. {
  569. if( objectTypes[n] )
  570. {
  571. // Clear the sub types before deleting the template type so that the sub types aren't freed to soon
  572. objectTypes[n]->templateSubTypes.SetLength(0);
  573. asDELETE(objectTypes[n],asCObjectType);
  574. }
  575. }
  576. objectTypes.SetLength(0);
  577. for( n = 0; n < templateSubTypes.GetLength(); n++ )
  578. {
  579. if( templateSubTypes[n] )
  580. asDELETE(templateSubTypes[n], asCObjectType);
  581. }
  582. templateSubTypes.SetLength(0);
  583. registeredTypeDefs.SetLength(0);
  584. registeredEnums.SetLength(0);
  585. registeredObjTypes.SetLength(0);
  586. for( n = 0; n < registeredGlobalFuncs.GetLength(); n++ )
  587. {
  588. if( registeredGlobalFuncs[n] )
  589. registeredGlobalFuncs[n]->Release();
  590. }
  591. registeredGlobalFuncs.SetLength(0);
  592. scriptTypeBehaviours.ReleaseAllFunctions();
  593. functionBehaviours.ReleaseAllFunctions();
  594. objectTypeBehaviours.ReleaseAllFunctions();
  595. globalPropertyBehaviours.ReleaseAllFunctions();
  596. // Destroy the funcdefs
  597. // As funcdefs are shared between modules it shouldn't be a problem to keep the objects until the engine is released
  598. // TODO: refactor: This really should be done by ClearUnusedTypes() as soon as the funcdef is no longer is use.
  599. // Perhaps to make it easier to manage the memory for funcdefs each function definition should
  600. // have it's own object type. That would make the funcdef much more similar to the other types
  601. // and could then be handled in much the same way. When this is done the funcdef should also be
  602. // changed so that it doesn't take up a function id, i.e. don't keep a reference to it in scriptFunctions.
  603. for( n = 0; n < funcDefs.GetLength(); n++ )
  604. if( funcDefs[n] )
  605. {
  606. asASSERT( funcDefs[n]->GetRefCount() == 0 );
  607. asDELETE(funcDefs[n], asCScriptFunction);
  608. }
  609. funcDefs.SetLength(0);
  610. // Free string constants
  611. for( n = 0; n < stringConstants.GetLength(); n++ )
  612. asDELETE(stringConstants[n],asCString);
  613. stringConstants.SetLength(0);
  614. stringToIdMap.EraseAll();
  615. // Free the script section names
  616. for( n = 0; n < scriptSectionNames.GetLength(); n++ )
  617. asDELETE(scriptSectionNames[n],asCString);
  618. scriptSectionNames.SetLength(0);
  619. // Clean the user data
  620. for( n = 0; n < userData.GetLength(); n += 2 )
  621. {
  622. if( userData[n+1] )
  623. {
  624. for( asUINT c = 0; c < cleanEngineFuncs.GetLength(); c++ )
  625. if( cleanEngineFuncs[c].type == userData[n] )
  626. cleanEngineFuncs[c].cleanFunc(this);
  627. }
  628. }
  629. // Free namespaces
  630. for( n = 0; n < nameSpaces.GetLength(); n++ )
  631. asDELETE(nameSpaces[n], asSNameSpace);
  632. nameSpaces.SetLength(0);
  633. asCThreadManager::Unprepare();
  634. }
  635. // internal
  636. void asCScriptEngine::CleanupAfterDiscardModule()
  637. {
  638. // Skip this when shutting down as it will be done anyway by the engine destructor
  639. if( shuttingDown ) return;
  640. if( ep.autoGarbageCollect )
  641. GarbageCollect();
  642. FreeUnusedGlobalProperties();
  643. ClearUnusedTypes();
  644. }
  645. // interface
  646. int asCScriptEngine::AddRef() const
  647. {
  648. return refCount.atomicInc();
  649. }
  650. // interface
  651. int asCScriptEngine::Release() const
  652. {
  653. int r = refCount.atomicDec();
  654. if( r == 0 )
  655. {
  656. asDELETE(const_cast<asCScriptEngine*>(this),asCScriptEngine);
  657. return 0;
  658. }
  659. return r;
  660. }
  661. // internal
  662. asSNameSpace *asCScriptEngine::AddNameSpace(const char *name)
  663. {
  664. // First check if it doesn't exist already
  665. asSNameSpace *ns = FindNameSpace(name);
  666. if( ns ) return ns;
  667. ns = asNEW(asSNameSpace);
  668. if( ns == 0 )
  669. {
  670. // Out of memory
  671. return 0;
  672. }
  673. ns->name = name;
  674. nameSpaces.PushLast(ns);
  675. return ns;
  676. }
  677. // internal
  678. asSNameSpace *asCScriptEngine::FindNameSpace(const char *name)
  679. {
  680. // TODO: optimize: Improve linear search
  681. for( asUINT n = 0; n < nameSpaces.GetLength(); n++ )
  682. if( nameSpaces[n]->name == name )
  683. return nameSpaces[n];
  684. return 0;
  685. }
  686. // interface
  687. const char *asCScriptEngine::GetDefaultNamespace() const
  688. {
  689. return defaultNamespace->name.AddressOf();
  690. }
  691. // interface
  692. int asCScriptEngine::SetDefaultNamespace(const char *nameSpace)
  693. {
  694. if( nameSpace == 0 )
  695. return ConfigError(asINVALID_ARG, "SetDefaultNamespace", nameSpace, 0);
  696. asCString ns = nameSpace;
  697. if( ns != "" )
  698. {
  699. // Make sure the namespace is composed of alternating identifier and ::
  700. size_t pos = 0;
  701. bool expectIdentifier = true;
  702. size_t len;
  703. eTokenType t = ttIdentifier;
  704. for( ; pos < ns.GetLength(); pos += len)
  705. {
  706. t = tok.GetToken(ns.AddressOf() + pos, ns.GetLength() - pos, &len);
  707. if( (expectIdentifier && t != ttIdentifier) || (!expectIdentifier && t != ttScope) )
  708. return ConfigError(asINVALID_DECLARATION, "SetDefaultNamespace", nameSpace, 0);
  709. expectIdentifier = !expectIdentifier;
  710. }
  711. // If the namespace ends with :: then strip it off
  712. if( t == ttScope )
  713. ns.SetLength(ns.GetLength()-2);
  714. }
  715. defaultNamespace = AddNameSpace(ns.AddressOf());
  716. return 0;
  717. }
  718. // interface
  719. void *asCScriptEngine::SetUserData(void *data, asPWORD type)
  720. {
  721. // As a thread might add a new new user data at the same time as another
  722. // it is necessary to protect both read and write access to the userData member
  723. ACQUIREEXCLUSIVE(engineRWLock);
  724. // It is not intended to store a lot of different types of userdata,
  725. // so a more complex structure like a associative map would just have
  726. // more overhead than a simple array.
  727. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  728. {
  729. if( userData[n] == type )
  730. {
  731. void *oldData = reinterpret_cast<void*>(userData[n+1]);
  732. userData[n+1] = reinterpret_cast<asPWORD>(data);
  733. RELEASEEXCLUSIVE(engineRWLock);
  734. return oldData;
  735. }
  736. }
  737. userData.PushLast(type);
  738. userData.PushLast(reinterpret_cast<asPWORD>(data));
  739. RELEASEEXCLUSIVE(engineRWLock);
  740. return 0;
  741. }
  742. // interface
  743. void *asCScriptEngine::GetUserData(asPWORD type) const
  744. {
  745. // There may be multiple threads reading, but when
  746. // setting the user data nobody must be reading.
  747. ACQUIRESHARED(engineRWLock);
  748. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  749. {
  750. if( userData[n] == type )
  751. {
  752. RELEASESHARED(engineRWLock);
  753. return reinterpret_cast<void*>(userData[n+1]);
  754. }
  755. }
  756. RELEASESHARED(engineRWLock);
  757. return 0;
  758. }
  759. // interface
  760. int asCScriptEngine::SetMessageCallback(const asSFuncPtr &callback, void *obj, asDWORD callConv)
  761. {
  762. msgCallback = true;
  763. msgCallbackObj = obj;
  764. bool isObj = false;
  765. if( (unsigned)callConv == asCALL_GENERIC )
  766. {
  767. msgCallback = false;
  768. return asNOT_SUPPORTED;
  769. }
  770. if( (unsigned)callConv >= asCALL_THISCALL )
  771. {
  772. isObj = true;
  773. if( obj == 0 )
  774. {
  775. msgCallback = false;
  776. return asINVALID_ARG;
  777. }
  778. }
  779. int r = DetectCallingConvention(isObj, callback, callConv, 0, &msgCallbackFunc);
  780. if( r < 0 ) msgCallback = false;
  781. return r;
  782. }
  783. // interface
  784. int asCScriptEngine::ClearMessageCallback()
  785. {
  786. msgCallback = false;
  787. return 0;
  788. }
  789. // interface
  790. int asCScriptEngine::WriteMessage(const char *section, int row, int col, asEMsgType type, const char *message)
  791. {
  792. // Validate input parameters
  793. if( section == 0 ||
  794. message == 0 )
  795. return asINVALID_ARG;
  796. // If there is no callback then there's nothing to do
  797. if( !msgCallback )
  798. return 0;
  799. asSMessageInfo msg;
  800. msg.section = section;
  801. msg.row = row;
  802. msg.col = col;
  803. msg.type = type;
  804. msg.message = message;
  805. if( msgCallbackFunc.callConv < ICC_THISCALL )
  806. CallGlobalFunction(&msg, msgCallbackObj, &msgCallbackFunc, 0);
  807. else
  808. CallObjectMethod(msgCallbackObj, &msg, &msgCallbackFunc, 0);
  809. return 0;
  810. }
  811. int asCScriptEngine::SetJITCompiler(asIJITCompiler *compiler)
  812. {
  813. jitCompiler = compiler;
  814. return asSUCCESS;
  815. }
  816. asIJITCompiler *asCScriptEngine::GetJITCompiler() const
  817. {
  818. return jitCompiler;
  819. }
  820. // interface
  821. asETokenClass asCScriptEngine::ParseToken(const char *string, size_t stringLength, int *tokenLength) const
  822. {
  823. if( stringLength == 0 )
  824. stringLength = strlen(string);
  825. size_t len;
  826. asETokenClass tc;
  827. tok.GetToken(string, stringLength, &len, &tc);
  828. if( tokenLength )
  829. *tokenLength = (int)len;
  830. return tc;
  831. }
  832. // interface
  833. asIScriptModule *asCScriptEngine::GetModule(const char *module, asEGMFlags flag)
  834. {
  835. asCModule *mod = GetModule(module, false);
  836. if( flag == asGM_ALWAYS_CREATE )
  837. {
  838. if( mod != 0 )
  839. mod->Discard();
  840. return GetModule(module, true);
  841. }
  842. if( mod == 0 && flag == asGM_CREATE_IF_NOT_EXISTS )
  843. return GetModule(module, true);
  844. return mod;
  845. }
  846. // interface
  847. int asCScriptEngine::DiscardModule(const char *module)
  848. {
  849. asCModule *mod = GetModule(module, false);
  850. if( mod == 0 ) return asNO_MODULE;
  851. mod->Discard();
  852. return 0;
  853. }
  854. // internal
  855. int asCScriptEngine::ClearUnusedTypes()
  856. {
  857. int clearCount = 0;
  858. // Build a list of all types to check for
  859. asCArray<asCObjectType*> types;
  860. types = classTypes;
  861. types.Concatenate(templateInstanceTypes);
  862. // Go through all modules
  863. asUINT n;
  864. for( n = 0; n < scriptModules.GetLength() && types.GetLength(); n++ )
  865. {
  866. asCModule *mod = scriptModules[n];
  867. if( mod )
  868. {
  869. // Functions/Methods/Globals are handled after this
  870. // Go through all type declarations
  871. asUINT m;
  872. for( m = 0; m < mod->classTypes.GetLength() && types.GetLength(); m++ )
  873. RemoveTypeAndRelatedFromList(types, mod->classTypes[m]);
  874. for( m = 0; m < mod->enumTypes.GetLength() && types.GetLength(); m++ )
  875. RemoveTypeAndRelatedFromList(types, mod->enumTypes[m]);
  876. for( m = 0; m < mod->typeDefs.GetLength() && types.GetLength(); m++ )
  877. RemoveTypeAndRelatedFromList(types, mod->typeDefs[m]);
  878. }
  879. }
  880. // Go through all function parameters and remove used types
  881. for( n = 0; n < scriptFunctions.GetLength() && types.GetLength(); n++ )
  882. {
  883. asCScriptFunction *func = scriptFunctions[n];
  884. if( func )
  885. {
  886. // Ignore factory stubs
  887. if( func->name == "factstub" )
  888. continue;
  889. // Ignore funcdefs because these will only be destroyed when the engine is released
  890. if( func->funcType == asFUNC_FUNCDEF )
  891. continue;
  892. asCObjectType *ot = func->returnType.GetObjectType();
  893. if( ot != 0 && ot != func->objectType )
  894. if( func->name != ot->name )
  895. RemoveTypeAndRelatedFromList(types, ot);
  896. for( asUINT p = 0; p < func->parameterTypes.GetLength(); p++ )
  897. {
  898. ot = func->parameterTypes[p].GetObjectType();
  899. if( ot != 0 && ot != func->objectType )
  900. if( func->name != ot->name )
  901. RemoveTypeAndRelatedFromList(types, ot);
  902. }
  903. }
  904. }
  905. // Go through all global properties
  906. for( n = 0; n < globalProperties.GetLength() && types.GetLength(); n++ )
  907. {
  908. if( globalProperties[n] && globalProperties[n]->type.GetObjectType() )
  909. RemoveTypeAndRelatedFromList(types, globalProperties[n]->type.GetObjectType());
  910. }
  911. // All that remains in the list after this can be discarded, since they are no longer used
  912. for(;;)
  913. {
  914. bool didClearTemplateInstanceType = false;
  915. for( n = 0; n < types.GetLength(); n++ )
  916. {
  917. int refCount = 0;
  918. asCObjectType *type = types[n];
  919. // Template types and script classes will have two references for each factory stub
  920. if( (type->flags & asOBJ_TEMPLATE) )
  921. {
  922. refCount = 2*(int)type->beh.factories.GetLength();
  923. if( type->beh.listFactory )
  924. refCount += 2;
  925. }
  926. if( type->GetRefCount() == refCount )
  927. {
  928. if( type->flags & asOBJ_TEMPLATE )
  929. {
  930. didClearTemplateInstanceType = true;
  931. RemoveTemplateInstanceType(type);
  932. clearCount++;
  933. }
  934. else
  935. {
  936. RemoveFromTypeIdMap(type);
  937. asDELETE(type,asCObjectType);
  938. clearCount++;
  939. classTypes.RemoveIndexUnordered(classTypes.IndexOf(type));
  940. }
  941. // Remove the type from the array
  942. types.RemoveIndexUnordered(n);
  943. n--;
  944. }
  945. }
  946. if( didClearTemplateInstanceType == false )
  947. break;
  948. }
  949. return clearCount;
  950. }
  951. // internal
  952. void asCScriptEngine::RemoveTypeAndRelatedFromList(asCArray<asCObjectType*> &types, asCObjectType *ot)
  953. {
  954. // Remove the type from the list
  955. int i = types.IndexOf(ot);
  956. if( i == -1 ) return;
  957. types.RemoveIndexUnordered(i);
  958. // If the type is an template type then remove all sub types as well
  959. for( asUINT n = 0; n < ot->templateSubTypes.GetLength(); n++ )
  960. {
  961. if( ot->templateSubTypes[n].GetObjectType() )
  962. RemoveTypeAndRelatedFromList(types, ot->templateSubTypes[n].GetObjectType());
  963. }
  964. // If the type is a class then remove all properties types as well
  965. if( ot->properties.GetLength() )
  966. {
  967. for( asUINT n = 0; n < ot->properties.GetLength(); n++ )
  968. RemoveTypeAndRelatedFromList(types, ot->properties[n]->type.GetObjectType());
  969. }
  970. }
  971. // internal
  972. int asCScriptEngine::GetFactoryIdByDecl(const asCObjectType *ot, const char *decl)
  973. {
  974. asCModule *mod = 0;
  975. // Is this a script class?
  976. if( ot->flags & asOBJ_SCRIPT_OBJECT && ot->size > 0 )
  977. mod = scriptFunctions[ot->beh.factories[0]]->module;
  978. asCBuilder bld(this, mod);
  979. asCScriptFunction func(this, mod, asFUNC_DUMMY);
  980. int r = bld.ParseFunctionDeclaration(0, decl, &func, false, 0, 0, defaultNamespace);
  981. if( r < 0 )
  982. return asINVALID_DECLARATION;
  983. // Search for matching factory function
  984. int id = -1;
  985. for( size_t n = 0; n < ot->beh.factories.GetLength(); n++ )
  986. {
  987. asCScriptFunction *f = scriptFunctions[ot->beh.factories[n]];
  988. if( f->IsSignatureEqual(&func) )
  989. {
  990. id = ot->beh.factories[n];
  991. break;
  992. }
  993. }
  994. if( id == -1 ) return asNO_FUNCTION;
  995. return id;
  996. }
  997. // internal
  998. int asCScriptEngine::GetMethodIdByDecl(const asCObjectType *ot, const char *decl, asCModule *mod)
  999. {
  1000. asCBuilder bld(this, mod);
  1001. asCScriptFunction func(this, mod, asFUNC_DUMMY);
  1002. // Set the object type so that the signature can be properly compared
  1003. // This cast is OK, it will only be used for comparison
  1004. func.objectType = const_cast<asCObjectType*>(ot);
  1005. int r = bld.ParseFunctionDeclaration(func.objectType, decl, &func, false);
  1006. if( r < 0 )
  1007. return asINVALID_DECLARATION;
  1008. // Search script functions for matching interface
  1009. int id = -1;
  1010. for( size_t n = 0; n < ot->methods.GetLength(); ++n )
  1011. {
  1012. if( func.IsSignatureEqual(scriptFunctions[ot->methods[n]]) )
  1013. {
  1014. if( id == -1 )
  1015. id = ot->methods[n];
  1016. else
  1017. return asMULTIPLE_FUNCTIONS;
  1018. }
  1019. }
  1020. if( id == -1 ) return asNO_FUNCTION;
  1021. return id;
  1022. }
  1023. // internal
  1024. asCString asCScriptEngine::GetFunctionDeclaration(int funcId)
  1025. {
  1026. asCString str;
  1027. asCScriptFunction *func = GetScriptFunction(funcId);
  1028. if( func )
  1029. str = func->GetDeclarationStr();
  1030. return str;
  1031. }
  1032. // internal
  1033. asCScriptFunction *asCScriptEngine::GetScriptFunction(int funcId) const
  1034. {
  1035. if( funcId < 0 || funcId >= (int)scriptFunctions.GetLength() )
  1036. return 0;
  1037. return scriptFunctions[funcId];
  1038. }
  1039. // interface
  1040. asIScriptContext *asCScriptEngine::CreateContext()
  1041. {
  1042. asIScriptContext *ctx = 0;
  1043. CreateContext(&ctx, false);
  1044. return ctx;
  1045. }
  1046. // internal
  1047. int asCScriptEngine::CreateContext(asIScriptContext **context, bool isInternal)
  1048. {
  1049. *context = asNEW(asCContext)(this, !isInternal);
  1050. if( *context == 0 )
  1051. return asOUT_OF_MEMORY;
  1052. // We need to make sure the engine has been
  1053. // prepared before any context is executed
  1054. PrepareEngine();
  1055. return 0;
  1056. }
  1057. // interface
  1058. int asCScriptEngine::RegisterObjectProperty(const char *obj, const char *declaration, int byteOffset)
  1059. {
  1060. int r;
  1061. asCDataType dt;
  1062. asCBuilder bld(this, 0);
  1063. r = bld.ParseDataType(obj, &dt, defaultNamespace);
  1064. if( r < 0 )
  1065. return ConfigError(r, "RegisterObjectProperty", obj, declaration);
  1066. // Verify that the correct config group is used
  1067. if( currentGroup->FindType(dt.GetObjectType()->name.AddressOf()) == 0 )
  1068. return ConfigError(asWRONG_CONFIG_GROUP, "RegisterObjectProperty", obj, declaration);
  1069. asCDataType type;
  1070. asCString name;
  1071. if( (r = bld.VerifyProperty(&dt, declaration, name, type, 0)) < 0 )
  1072. return ConfigError(r, "RegisterObjectProperty", obj, declaration);
  1073. // Store the property info
  1074. if( dt.GetObjectType() == 0 )
  1075. return ConfigError(asINVALID_OBJECT, "RegisterObjectProperty", obj, declaration);
  1076. // The VM currently only supports 16bit offsets
  1077. // TODO: The VM needs to have support for 32bit offsets. Probably with a second ADDSi instruction
  1078. // However, when implementing this it is necessary for the bytecode serialization to support
  1079. // the switch between the instructions upon loading bytecode as the offset may not be the
  1080. // same on all platforms
  1081. if( byteOffset > 32767 || byteOffset < -32768 )
  1082. return ConfigError(asINVALID_ARG, "RegisterObjectProperty", obj, declaration);
  1083. asCObjectProperty *prop = asNEW(asCObjectProperty);
  1084. if( prop == 0 )
  1085. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectProperty", obj, declaration);
  1086. prop->name = name;
  1087. prop->type = type;
  1088. prop->byteOffset = byteOffset;
  1089. prop->isPrivate = false;
  1090. prop->accessMask = defaultAccessMask;
  1091. dt.GetObjectType()->properties.PushLast(prop);
  1092. currentGroup->RefConfigGroup(FindConfigGroupForObjectType(type.GetObjectType()));
  1093. return asSUCCESS;
  1094. }
  1095. // interface
  1096. int asCScriptEngine::RegisterInterface(const char *name)
  1097. {
  1098. if( name == 0 ) return ConfigError(asINVALID_NAME, "RegisterInterface", 0, 0);
  1099. // Verify if the name has been registered as a type already
  1100. asUINT n;
  1101. for( n = 0; n < objectTypes.GetLength(); n++ )
  1102. {
  1103. if( objectTypes[n] && objectTypes[n]->name == name && objectTypes[n]->nameSpace == defaultNamespace )
  1104. return asALREADY_REGISTERED;
  1105. }
  1106. // Use builder to parse the datatype
  1107. asCDataType dt;
  1108. asCBuilder bld(this, 0);
  1109. bool oldMsgCallback = msgCallback; msgCallback = false;
  1110. int r = bld.ParseDataType(name, &dt, defaultNamespace);
  1111. msgCallback = oldMsgCallback;
  1112. if( r >= 0 ) return ConfigError(asERROR, "RegisterInterface", name, 0);
  1113. // Make sure the name is not a reserved keyword
  1114. size_t tokenLen;
  1115. int token = tok.GetToken(name, strlen(name), &tokenLen);
  1116. if( token != ttIdentifier || strlen(name) != tokenLen )
  1117. return ConfigError(asINVALID_NAME, "RegisterInterface", name, 0);
  1118. r = bld.CheckNameConflict(name, 0, 0, defaultNamespace);
  1119. if( r < 0 )
  1120. return ConfigError(asNAME_TAKEN, "RegisterInterface", name, 0);
  1121. // Don't have to check against members of object
  1122. // types as they are allowed to use the names
  1123. // Register the object type for the interface
  1124. asCObjectType *st = asNEW(asCObjectType)(this);
  1125. if( st == 0 )
  1126. return ConfigError(asOUT_OF_MEMORY, "RegisterInterface", name, 0);
  1127. st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT | asOBJ_SHARED;
  1128. st->size = 0; // Cannot be instanciated
  1129. st->name = name;
  1130. st->nameSpace = defaultNamespace;
  1131. // Use the default script class behaviours
  1132. st->beh.factory = 0;
  1133. st->beh.addref = scriptTypeBehaviours.beh.addref;
  1134. scriptFunctions[st->beh.addref]->AddRef();
  1135. st->beh.release = scriptTypeBehaviours.beh.release;
  1136. scriptFunctions[st->beh.release]->AddRef();
  1137. st->beh.copy = 0;
  1138. objectTypes.PushLast(st);
  1139. registeredObjTypes.PushLast(st);
  1140. currentGroup->objTypes.PushLast(st);
  1141. return asSUCCESS;
  1142. }
  1143. // interface
  1144. int asCScriptEngine::RegisterInterfaceMethod(const char *intf, const char *declaration)
  1145. {
  1146. // Verify that the correct config group is set.
  1147. if( currentGroup->FindType(intf) == 0 )
  1148. return ConfigError(asWRONG_CONFIG_GROUP, "RegisterInterfaceMethod", intf, declaration);
  1149. asCDataType dt;
  1150. asCBuilder bld(this, 0);
  1151. int r = bld.ParseDataType(intf, &dt, defaultNamespace);
  1152. if( r < 0 )
  1153. return ConfigError(r, "RegisterInterfaceMethod", intf, declaration);
  1154. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_INTERFACE);
  1155. if( func == 0 )
  1156. return ConfigError(asOUT_OF_MEMORY, "RegisterInterfaceMethod", intf, declaration);
  1157. func->objectType = dt.GetObjectType();
  1158. r = bld.ParseFunctionDeclaration(func->objectType, declaration, func, false);
  1159. if( r < 0 )
  1160. {
  1161. asDELETE(func,asCScriptFunction);
  1162. return ConfigError(asINVALID_DECLARATION, "RegisterInterfaceMethod", intf, declaration);
  1163. }
  1164. // Check name conflicts
  1165. r = bld.CheckNameConflictMember(dt.GetObjectType(), func->name.AddressOf(), 0, 0, false);
  1166. if( r < 0 )
  1167. {
  1168. asDELETE(func,asCScriptFunction);
  1169. return ConfigError(asNAME_TAKEN, "RegisterInterfaceMethod", intf, declaration);
  1170. }
  1171. func->id = GetNextScriptFunctionId();
  1172. SetScriptFunction(func);
  1173. func->objectType->methods.PushLast(func->id);
  1174. // The refCount was already set to 1
  1175. func->ComputeSignatureId();
  1176. // If parameter type from other groups are used, add references
  1177. // TODO: The code for adding references to config groups is repeated in a lot of places
  1178. if( func->returnType.GetObjectType() )
  1179. {
  1180. asCConfigGroup *group = FindConfigGroupForObjectType(func->returnType.GetObjectType());
  1181. currentGroup->RefConfigGroup(group);
  1182. }
  1183. for( asUINT n = 0; n < func->parameterTypes.GetLength(); n++ )
  1184. {
  1185. if( func->parameterTypes[n].GetObjectType() )
  1186. {
  1187. asCConfigGroup *group = FindConfigGroupForObjectType(func->parameterTypes[n].GetObjectType());
  1188. currentGroup->RefConfigGroup(group);
  1189. }
  1190. }
  1191. // Return function id as success
  1192. return func->id;
  1193. }
  1194. int asCScriptEngine::RegisterObjectType(const char *name, int byteSize, asDWORD flags)
  1195. {
  1196. int r;
  1197. isPrepared = false;
  1198. // Verify flags
  1199. // Must have either asOBJ_REF or asOBJ_VALUE
  1200. if( flags & asOBJ_REF )
  1201. {
  1202. // Can optionally have the asOBJ_GC, asOBJ_NOHANDLE, asOBJ_SCOPED, or asOBJ_TEMPLATE flag set, but nothing else
  1203. if( flags & ~(asOBJ_REF | asOBJ_GC | asOBJ_NOHANDLE | asOBJ_SCOPED | asOBJ_TEMPLATE | asOBJ_NOCOUNT) )
  1204. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1205. // flags are exclusive
  1206. if( (flags & asOBJ_GC) && (flags & (asOBJ_NOHANDLE|asOBJ_SCOPED|asOBJ_NOCOUNT)) )
  1207. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1208. if( (flags & asOBJ_NOHANDLE) && (flags & (asOBJ_GC|asOBJ_SCOPED|asOBJ_NOCOUNT)) )
  1209. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1210. if( (flags & asOBJ_SCOPED) && (flags & (asOBJ_GC|asOBJ_NOHANDLE|asOBJ_NOCOUNT)) )
  1211. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1212. if( (flags & asOBJ_NOCOUNT) && (flags & (asOBJ_GC|asOBJ_NOHANDLE|asOBJ_SCOPED)) )
  1213. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1214. }
  1215. else if( flags & asOBJ_VALUE )
  1216. {
  1217. // Cannot use reference flags
  1218. // TODO: template: Should be possible to register a value type as template type
  1219. if( flags & (asOBJ_REF | asOBJ_GC | asOBJ_NOHANDLE | asOBJ_SCOPED | asOBJ_TEMPLATE | asOBJ_NOCOUNT) )
  1220. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1221. // flags are exclusive
  1222. if( (flags & asOBJ_POD) && (flags & asOBJ_ASHANDLE) )
  1223. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1224. // If the app type is given, we must validate the flags
  1225. if( flags & asOBJ_APP_CLASS )
  1226. {
  1227. // Must not set the primitive or float flag
  1228. if( flags & (asOBJ_APP_PRIMITIVE | asOBJ_APP_FLOAT) )
  1229. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1230. }
  1231. else if( flags & asOBJ_APP_PRIMITIVE )
  1232. {
  1233. // Must not set the class flags nor the float flag
  1234. if( flags & (asOBJ_APP_CLASS |
  1235. asOBJ_APP_CLASS_CONSTRUCTOR |
  1236. asOBJ_APP_CLASS_DESTRUCTOR |
  1237. asOBJ_APP_CLASS_ASSIGNMENT |
  1238. asOBJ_APP_CLASS_COPY_CONSTRUCTOR |
  1239. asOBJ_APP_FLOAT |
  1240. asOBJ_APP_CLASS_ALLINTS |
  1241. asOBJ_APP_CLASS_ALLFLOATS) )
  1242. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1243. }
  1244. else if( flags & asOBJ_APP_FLOAT )
  1245. {
  1246. // Must not set the class flags nor the primitive flag
  1247. if( flags & (asOBJ_APP_CLASS |
  1248. asOBJ_APP_CLASS_CONSTRUCTOR |
  1249. asOBJ_APP_CLASS_DESTRUCTOR |
  1250. asOBJ_APP_CLASS_ASSIGNMENT |
  1251. asOBJ_APP_CLASS_COPY_CONSTRUCTOR |
  1252. asOBJ_APP_PRIMITIVE |
  1253. asOBJ_APP_CLASS_ALLINTS |
  1254. asOBJ_APP_CLASS_ALLFLOATS) )
  1255. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1256. }
  1257. else if( flags & (asOBJ_APP_CLASS_CONSTRUCTOR |
  1258. asOBJ_APP_CLASS_DESTRUCTOR |
  1259. asOBJ_APP_CLASS_ASSIGNMENT |
  1260. asOBJ_APP_CLASS_COPY_CONSTRUCTOR |
  1261. asOBJ_APP_CLASS_ALLINTS |
  1262. asOBJ_APP_CLASS_ALLFLOATS) )
  1263. {
  1264. // Must not set the class properties, without the class flag
  1265. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1266. }
  1267. }
  1268. else
  1269. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1270. // Don't allow anything else than the defined flags
  1271. if( flags - (flags & asOBJ_MASK_VALID_FLAGS) )
  1272. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1273. // Value types must have a defined size
  1274. if( (flags & asOBJ_VALUE) && byteSize == 0 )
  1275. {
  1276. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_VALUE_TYPE_MUST_HAVE_SIZE);
  1277. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1278. }
  1279. // Verify type name
  1280. if( name == 0 )
  1281. return ConfigError(asINVALID_NAME, "RegisterObjectType", name, 0);
  1282. asCString typeName;
  1283. asCBuilder bld(this, 0);
  1284. if( flags & asOBJ_TEMPLATE )
  1285. {
  1286. asCArray<asCString> subtypeNames;
  1287. r = bld.ParseTemplateDecl(name, &typeName, subtypeNames);
  1288. if( r < 0 )
  1289. return ConfigError(r, "RegisterObjectType", name, 0);
  1290. // Verify that the template name hasn't been registered as a type already
  1291. asUINT n;
  1292. for( n = 0; n < objectTypes.GetLength(); n++ )
  1293. {
  1294. if( objectTypes[n] && objectTypes[n]->name == typeName && objectTypes[n]->nameSpace == defaultNamespace )
  1295. // This is not an irrepairable error, as it may just be that the same type is registered twice
  1296. return asALREADY_REGISTERED;
  1297. }
  1298. asCObjectType *type = asNEW(asCObjectType)(this);
  1299. if( type == 0 )
  1300. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
  1301. type->name = typeName;
  1302. type->nameSpace = defaultNamespace;
  1303. type->size = byteSize;
  1304. type->flags = flags;
  1305. type->accessMask = defaultAccessMask;
  1306. // Store it in the object types
  1307. objectTypes.PushLast(type);
  1308. currentGroup->objTypes.PushLast(type);
  1309. registeredObjTypes.PushLast(type);
  1310. // Define the template subtypes
  1311. for( asUINT subTypeIdx = 0; subTypeIdx < subtypeNames.GetLength(); subTypeIdx++ )
  1312. {
  1313. asCObjectType *subtype = 0;
  1314. for( n = 0; n < templateSubTypes.GetLength(); n++ )
  1315. {
  1316. if( templateSubTypes[n]->name == subtypeNames[subTypeIdx] )
  1317. {
  1318. subtype = templateSubTypes[n];
  1319. break;
  1320. }
  1321. }
  1322. if( subtype == 0 )
  1323. {
  1324. // Create the new subtype if not already existing
  1325. subtype = asNEW(asCObjectType)(this);
  1326. if( subtype == 0 )
  1327. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
  1328. subtype->name = subtypeNames[subTypeIdx];
  1329. subtype->size = 0;
  1330. subtype->flags = asOBJ_TEMPLATE_SUBTYPE;
  1331. templateSubTypes.PushLast(subtype);
  1332. subtype->AddRef();
  1333. }
  1334. type->templateSubTypes.PushLast(asCDataType::CreateObject(subtype, false));
  1335. subtype->AddRef();
  1336. }
  1337. }
  1338. else
  1339. {
  1340. typeName = name;
  1341. // Verify if the name has been registered as a type already
  1342. asUINT n;
  1343. for( n = 0; n < objectTypes.GetLength(); n++ )
  1344. {
  1345. if( objectTypes[n] &&
  1346. objectTypes[n]->name == typeName &&
  1347. objectTypes[n]->nameSpace == defaultNamespace )
  1348. // This is not an irrepairable error, as it may just be that the same type is registered twice
  1349. return asALREADY_REGISTERED;
  1350. }
  1351. for( n = 0; n < templateTypes.GetLength(); n++ )
  1352. {
  1353. if( templateTypes[n] &&
  1354. templateTypes[n]->name == typeName &&
  1355. templateTypes[n]->nameSpace == defaultNamespace )
  1356. // This is not an irrepairable error, as it may just be that the same type is registered twice
  1357. return asALREADY_REGISTERED;
  1358. }
  1359. // Verify the most recently created template instance type
  1360. asCObjectType *mostRecentTemplateInstanceType = 0;
  1361. if( templateInstanceTypes.GetLength() )
  1362. mostRecentTemplateInstanceType = templateInstanceTypes[templateInstanceTypes.GetLength()-1];
  1363. // Use builder to parse the datatype
  1364. asCDataType dt;
  1365. bool oldMsgCallback = msgCallback; msgCallback = false;
  1366. r = bld.ParseDataType(name, &dt, defaultNamespace);
  1367. msgCallback = oldMsgCallback;
  1368. // If the builder fails or the namespace is different than the default
  1369. // namespace, then the type name is new and it should be registered
  1370. if( r < 0 || dt.GetObjectType()->nameSpace != defaultNamespace )
  1371. {
  1372. // Make sure the name is not a reserved keyword
  1373. size_t tokenLen;
  1374. int token = tok.GetToken(name, typeName.GetLength(), &tokenLen);
  1375. if( token != ttIdentifier || typeName.GetLength() != tokenLen )
  1376. return ConfigError(asINVALID_NAME, "RegisterObjectType", name, 0);
  1377. int r = bld.CheckNameConflict(name, 0, 0, defaultNamespace);
  1378. if( r < 0 )
  1379. return ConfigError(asNAME_TAKEN, "RegisterObjectType", name, 0);
  1380. // Don't have to check against members of object
  1381. // types as they are allowed to use the names
  1382. // Put the data type in the list
  1383. asCObjectType *type = asNEW(asCObjectType)(this);
  1384. if( type == 0 )
  1385. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
  1386. type->name = typeName;
  1387. type->nameSpace = defaultNamespace;
  1388. type->size = byteSize;
  1389. type->flags = flags;
  1390. type->accessMask = defaultAccessMask;
  1391. objectTypes.PushLast(type);
  1392. registeredObjTypes.PushLast(type);
  1393. currentGroup->objTypes.PushLast(type);
  1394. }
  1395. else
  1396. {
  1397. // The application is registering a template specialization so we
  1398. // need to replace the template instance type with the new type.
  1399. // TODO: Template: We don't require the lower dimensions to be registered first for registered template types
  1400. // int[][] must not be allowed to be registered
  1401. // if int[] hasn't been registered first
  1402. if( dt.GetSubType().IsTemplate() )
  1403. return ConfigError(asLOWER_ARRAY_DIMENSION_NOT_REGISTERED, "RegisterObjectType", name, 0);
  1404. if( dt.IsReadOnly() ||
  1405. dt.IsReference() )
  1406. return ConfigError(asINVALID_TYPE, "RegisterObjectType", name, 0);
  1407. // Was the template instance type created before?
  1408. if( templateInstanceTypes[templateInstanceTypes.GetLength()-1] == mostRecentTemplateInstanceType ||
  1409. mostRecentTemplateInstanceType == dt.GetObjectType() )
  1410. // TODO: Should have a better error message
  1411. return ConfigError(asNOT_SUPPORTED, "RegisterObjectType", name, 0);
  1412. // TODO: Add this again. The type is used by the factory stubs so we need to discount that
  1413. // Is the template instance type already being used?
  1414. // if( dt.GetObjectType()->GetRefCount() > 1 )
  1415. // return ConfigError(asNOT_SUPPORTED, "RegisterObjectType", name, 0);
  1416. // Put the data type in the list
  1417. asCObjectType *type = asNEW(asCObjectType)(this);
  1418. if( type == 0 )
  1419. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
  1420. type->name = dt.GetObjectType()->name;
  1421. // The namespace will be the same as the original template type
  1422. type->nameSpace = dt.GetObjectType()->nameSpace;
  1423. // TODO: template: Support multiple subtypes
  1424. type->templateSubTypes.PushLast(dt.GetSubType());
  1425. if( type->templateSubTypes[0].GetObjectType() ) type->templateSubTypes[0].GetObjectType()->AddRef();
  1426. type->size = byteSize;
  1427. type->flags = flags;
  1428. type->accessMask = defaultAccessMask;
  1429. templateTypes.PushLast(type);
  1430. currentGroup->objTypes.PushLast(type);
  1431. // Remove the template instance type, which will no longer be used.
  1432. RemoveTemplateInstanceType(dt.GetObjectType());
  1433. }
  1434. }
  1435. // Return the type id as the success (except for template types)
  1436. if( flags & asOBJ_TEMPLATE )
  1437. return asSUCCESS;
  1438. return GetTypeIdByDecl(name);
  1439. }
  1440. // interface
  1441. int asCScriptEngine::RegisterObjectBehaviour(const char *datatype, asEBehaviours behaviour, const char *decl, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall)
  1442. {
  1443. if( datatype == 0 ) return ConfigError(asINVALID_ARG, "RegisterObjectBehaviour", datatype, decl);
  1444. // Determine the object type
  1445. asCBuilder bld(this, 0);
  1446. asCDataType type;
  1447. int r = bld.ParseDataType(datatype, &type, defaultNamespace);
  1448. if( r < 0 )
  1449. return ConfigError(r, "RegisterObjectBehaviour", datatype, decl);
  1450. if( type.GetObjectType() == 0 )
  1451. return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
  1452. // Don't allow application to modify built-in types
  1453. if( type.GetObjectType() == &functionBehaviours ||
  1454. type.GetObjectType() == &objectTypeBehaviours ||
  1455. type.GetObjectType() == &globalPropertyBehaviours ||
  1456. type.GetObjectType() == &scriptTypeBehaviours )
  1457. return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
  1458. if( type.IsReadOnly() || type.IsReference() )
  1459. return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
  1460. return RegisterBehaviourToObjectType(type.GetObjectType(), behaviour, decl, funcPointer, callConv, objForThiscall);
  1461. }
  1462. // internal
  1463. int asCScriptEngine::RegisterBehaviourToObjectType(asCObjectType *objectType, asEBehaviours behaviour, const char *decl, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall)
  1464. {
  1465. asSSystemFunctionInterface internal;
  1466. if( behaviour == asBEHAVE_FACTORY ||
  1467. behaviour == asBEHAVE_LIST_FACTORY ||
  1468. behaviour == asBEHAVE_TEMPLATE_CALLBACK )
  1469. {
  1470. #ifdef AS_MAX_PORTABILITY
  1471. if( callConv != asCALL_GENERIC )
  1472. return ConfigError(asNOT_SUPPORTED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1473. #endif
  1474. int r = DetectCallingConvention(false, funcPointer, callConv, objForThiscall, &internal);
  1475. if( r < 0 )
  1476. return ConfigError(r, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1477. }
  1478. else
  1479. {
  1480. #ifdef AS_MAX_PORTABILITY
  1481. if( callConv != asCALL_GENERIC )
  1482. return ConfigError(asNOT_SUPPORTED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1483. #else
  1484. if( callConv != asCALL_THISCALL &&
  1485. callConv != asCALL_CDECL_OBJLAST &&
  1486. callConv != asCALL_CDECL_OBJFIRST &&
  1487. callConv != asCALL_GENERIC )
  1488. return ConfigError(asNOT_SUPPORTED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1489. #endif
  1490. int r = DetectCallingConvention(true, funcPointer, callConv, objForThiscall, &internal);
  1491. if( r < 0 )
  1492. return ConfigError(r, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1493. }
  1494. isPrepared = false;
  1495. asSTypeBehaviour *beh = &objectType->beh;
  1496. // Verify function declaration
  1497. asCScriptFunction func(this, 0, asFUNC_DUMMY);
  1498. asCBuilder bld(this, 0);
  1499. int r = bld.ParseFunctionDeclaration(objectType, decl, &func, true, &internal.paramAutoHandles, &internal.returnAutoHandle);
  1500. if( r < 0 )
  1501. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1502. func.name.Format("_beh_%d_", behaviour);
  1503. if( behaviour != asBEHAVE_FACTORY && behaviour != asBEHAVE_LIST_FACTORY )
  1504. func.objectType = objectType;
  1505. // Check if the method restricts that use of the template to value types or reference types
  1506. if( objectType->flags & asOBJ_TEMPLATE )
  1507. {
  1508. for( asUINT subTypeIdx = 0; subTypeIdx < objectType->templateSubTypes.GetLength(); subTypeIdx++ )
  1509. {
  1510. if( func.returnType.GetObjectType() == objectType->templateSubTypes[subTypeIdx].GetObjectType() )
  1511. {
  1512. if( func.returnType.IsObjectHandle() )
  1513. objectType->acceptValueSubType = false;
  1514. else if( !func.returnType.IsReference() )
  1515. objectType->acceptRefSubType = false;
  1516. }
  1517. for( asUINT n = 0; n < func.parameterTypes.GetLength(); n++ )
  1518. {
  1519. if( func.parameterTypes[n].GetObjectType() == objectType->templateSubTypes[subTypeIdx].GetObjectType() )
  1520. {
  1521. // TODO: If unsafe references are allowed, then inout references allow value types
  1522. if( func.parameterTypes[n].IsObjectHandle() || (func.parameterTypes[n].IsReference() && func.inOutFlags[n] == asTM_INOUTREF) )
  1523. objectType->acceptValueSubType = false;
  1524. else if( !func.parameterTypes[n].IsReference() )
  1525. objectType->acceptRefSubType = false;
  1526. }
  1527. }
  1528. }
  1529. }
  1530. if( behaviour == asBEHAVE_CONSTRUCT )
  1531. {
  1532. // TODO: Add asBEHAVE_IMPLICIT_CONSTRUCT
  1533. // Verify that the return type is void
  1534. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1535. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1536. if( objectType->flags & asOBJ_SCRIPT_OBJECT )
  1537. {
  1538. // The script object is a special case
  1539. asASSERT(func.parameterTypes.GetLength() == 1);
  1540. beh->construct = AddBehaviourFunction(func, internal);
  1541. beh->factory = beh->construct;
  1542. scriptFunctions[beh->factory]->AddRef();
  1543. beh->constructors.PushLast(beh->construct);
  1544. beh->factories.PushLast(beh->factory);
  1545. func.id = beh->construct;
  1546. }
  1547. else
  1548. {
  1549. // Verify that it is a value type
  1550. if( !(func.objectType->flags & asOBJ_VALUE) )
  1551. {
  1552. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1553. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1554. }
  1555. // TODO: Add support for implicit constructors
  1556. // TODO: Verify that the same constructor hasn't been registered already
  1557. // Store all constructors in a list
  1558. func.id = AddBehaviourFunction(func, internal);
  1559. beh->constructors.PushLast(func.id);
  1560. if( func.parameterTypes.GetLength() == 0 )
  1561. {
  1562. beh->construct = func.id;
  1563. }
  1564. else if( func.parameterTypes.GetLength() == 1 )
  1565. {
  1566. // Is this the copy constructor?
  1567. asCDataType paramType = func.parameterTypes[0];
  1568. // If the parameter is object, and const reference for input or inout,
  1569. // and same type as this class, then this is a copy constructor.
  1570. if( paramType.IsObject() && paramType.IsReference() && paramType.IsReadOnly() &&
  1571. (func.inOutFlags[0] & asTM_INREF) && paramType.GetObjectType() == objectType )
  1572. beh->copyconstruct = func.id;
  1573. }
  1574. }
  1575. }
  1576. else if( behaviour == asBEHAVE_DESTRUCT )
  1577. {
  1578. // Must be a value type
  1579. if( !(func.objectType->flags & asOBJ_VALUE) )
  1580. {
  1581. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1582. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1583. }
  1584. if( beh->destruct )
  1585. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1586. // Verify that the return type is void
  1587. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1588. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1589. // Verify that there are no parameters
  1590. if( func.parameterTypes.GetLength() > 0 )
  1591. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1592. func.id = beh->destruct = AddBehaviourFunction(func, internal);
  1593. }
  1594. else if( behaviour == asBEHAVE_FACTORY || behaviour == asBEHAVE_LIST_FACTORY )
  1595. {
  1596. // Must be a ref type and must not have asOBJ_NOHANDLE
  1597. if( !(objectType->flags & asOBJ_REF) || (objectType->flags & asOBJ_NOHANDLE) )
  1598. {
  1599. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1600. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1601. }
  1602. // Verify that the return type is a handle to the type
  1603. if( func.returnType != asCDataType::CreateObjectHandle(objectType, false) )
  1604. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1605. // TODO: Add support for implicit factories
  1606. // TODO: Verify that the same factory function hasn't been registered already
  1607. // The templates take a hidden parameter with the object type
  1608. if( (objectType->flags & asOBJ_TEMPLATE) &&
  1609. (func.parameterTypes.GetLength() == 0 ||
  1610. !func.parameterTypes[0].IsReference()) )
  1611. {
  1612. // TODO: Give proper error message that explain that the first parameter is expected to be a reference
  1613. // The library should try to avoid having to read the manual as much as possible.
  1614. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1615. }
  1616. // Store all factory functions in a list
  1617. func.id = AddBehaviourFunction(func, internal);
  1618. // The list factory is a special factory and isn't stored together with the rest
  1619. if( behaviour != asBEHAVE_LIST_FACTORY )
  1620. beh->factories.PushLast(func.id);
  1621. if( (func.parameterTypes.GetLength() == 0) ||
  1622. (func.parameterTypes.GetLength() == 1 && (objectType->flags & asOBJ_TEMPLATE)) )
  1623. {
  1624. beh->factory = func.id;
  1625. }
  1626. else if( (func.parameterTypes.GetLength() == 1) ||
  1627. (func.parameterTypes.GetLength() == 2 && (objectType->flags & asOBJ_TEMPLATE)) )
  1628. {
  1629. if( behaviour == asBEHAVE_LIST_FACTORY )
  1630. beh->listFactory = func.id;
  1631. else
  1632. {
  1633. // Is this the copy factory?
  1634. asCDataType paramType = func.parameterTypes[func.parameterTypes.GetLength()-1];
  1635. // If the parameter is object, and const reference for input,
  1636. // and same type as this class, then this is a copy constructor.
  1637. if( paramType.IsObject() && paramType.IsReference() && paramType.IsReadOnly() && func.inOutFlags[func.parameterTypes.GetLength()-1] == asTM_INREF && paramType.GetObjectType() == objectType )
  1638. beh->copyfactory = func.id;
  1639. }
  1640. }
  1641. }
  1642. else if( behaviour == asBEHAVE_ADDREF )
  1643. {
  1644. // Must be a ref type and must not have asOBJ_NOHANDLE, nor asOBJ_SCOPED
  1645. if( !(func.objectType->flags & asOBJ_REF) ||
  1646. (func.objectType->flags & asOBJ_NOHANDLE) ||
  1647. (func.objectType->flags & asOBJ_SCOPED) ||
  1648. (func.objectType->flags & asOBJ_NOCOUNT) )
  1649. {
  1650. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1651. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1652. }
  1653. if( beh->addref )
  1654. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1655. // Verify that the return type is void
  1656. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1657. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1658. // Verify that there are no parameters
  1659. if( func.parameterTypes.GetLength() > 0 )
  1660. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1661. func.id = beh->addref = AddBehaviourFunction(func, internal);
  1662. }
  1663. else if( behaviour == asBEHAVE_RELEASE )
  1664. {
  1665. // Must be a ref type and must not have asOBJ_NOHANDLE
  1666. if( !(func.objectType->flags & asOBJ_REF) ||
  1667. (func.objectType->flags & asOBJ_NOHANDLE) ||
  1668. (func.objectType->flags & asOBJ_NOCOUNT) )
  1669. {
  1670. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1671. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1672. }
  1673. if( beh->release )
  1674. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1675. // Verify that the return type is void
  1676. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1677. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1678. // Verify that there are no parameters
  1679. if( func.parameterTypes.GetLength() > 0 )
  1680. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1681. func.id = beh->release = AddBehaviourFunction(func, internal);
  1682. }
  1683. else if( behaviour == asBEHAVE_TEMPLATE_CALLBACK )
  1684. {
  1685. // Must be a template type
  1686. if( !(func.objectType->flags & asOBJ_TEMPLATE) )
  1687. {
  1688. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1689. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1690. }
  1691. if( beh->templateCallback )
  1692. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1693. // Verify that the return type is bool
  1694. if( func.returnType != asCDataType::CreatePrimitive(ttBool, false) )
  1695. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1696. // Verify that there are two parameters
  1697. if( func.parameterTypes.GetLength() != 2 )
  1698. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1699. // The first parameter must be an inref (to receive the object type), and
  1700. // the second must be a bool out ref (to return if the type should or shouldn't be garbage collected)
  1701. if( func.inOutFlags[0] != asTM_INREF || func.inOutFlags[1] != asTM_OUTREF || !func.parameterTypes[1].IsEqualExceptRef(asCDataType::CreatePrimitive(ttBool, false)) )
  1702. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1703. func.id = beh->templateCallback = AddBehaviourFunction(func, internal);
  1704. }
  1705. else if( behaviour >= asBEHAVE_FIRST_GC &&
  1706. behaviour <= asBEHAVE_LAST_GC )
  1707. {
  1708. // Only allow GC behaviours for types registered to be garbage collected
  1709. if( !(func.objectType->flags & asOBJ_GC) )
  1710. {
  1711. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1712. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1713. }
  1714. // Verify parameter count
  1715. if( (behaviour == asBEHAVE_GETREFCOUNT ||
  1716. behaviour == asBEHAVE_SETGCFLAG ||
  1717. behaviour == asBEHAVE_GETGCFLAG) &&
  1718. func.parameterTypes.GetLength() != 0 )
  1719. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1720. if( (behaviour == asBEHAVE_ENUMREFS ||
  1721. behaviour == asBEHAVE_RELEASEREFS) &&
  1722. func.parameterTypes.GetLength() != 1 )
  1723. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1724. // Verify return type
  1725. if( behaviour == asBEHAVE_GETREFCOUNT &&
  1726. func.returnType != asCDataType::CreatePrimitive(ttInt, false) )
  1727. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1728. if( behaviour == asBEHAVE_GETGCFLAG &&
  1729. func.returnType != asCDataType::CreatePrimitive(ttBool, false) )
  1730. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1731. if( (behaviour == asBEHAVE_SETGCFLAG ||
  1732. behaviour == asBEHAVE_ENUMREFS ||
  1733. behaviour == asBEHAVE_RELEASEREFS) &&
  1734. func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1735. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1736. if( behaviour == asBEHAVE_GETREFCOUNT )
  1737. func.id = beh->gcGetRefCount = AddBehaviourFunction(func, internal);
  1738. else if( behaviour == asBEHAVE_SETGCFLAG )
  1739. func.id = beh->gcSetFlag = AddBehaviourFunction(func, internal);
  1740. else if( behaviour == asBEHAVE_GETGCFLAG )
  1741. func.id = beh->gcGetFlag = AddBehaviourFunction(func, internal);
  1742. else if( behaviour == asBEHAVE_ENUMREFS )
  1743. func.id = beh->gcEnumReferences = AddBehaviourFunction(func, internal);
  1744. else if( behaviour == asBEHAVE_RELEASEREFS )
  1745. func.id = beh->gcReleaseAllReferences = AddBehaviourFunction(func, internal);
  1746. }
  1747. else if( behaviour == asBEHAVE_IMPLICIT_VALUE_CAST ||
  1748. behaviour == asBEHAVE_VALUE_CAST )
  1749. {
  1750. // Verify parameter count
  1751. if( func.parameterTypes.GetLength() != 0 )
  1752. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1753. // Verify return type
  1754. if( func.returnType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, false)) )
  1755. return ConfigError(asNOT_SUPPORTED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1756. if( func.returnType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttVoid, false)) )
  1757. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1758. // TODO: verify that the same cast is not registered already (const or non-const is treated the same for the return type)
  1759. beh->operators.PushLast(behaviour);
  1760. func.id = AddBehaviourFunction(func, internal);
  1761. beh->operators.PushLast(func.id);
  1762. }
  1763. else if( behaviour == asBEHAVE_REF_CAST ||
  1764. behaviour == asBEHAVE_IMPLICIT_REF_CAST )
  1765. {
  1766. // There are two allowed signatures
  1767. // 1. obj @f()
  1768. // 2. void f(?&out)
  1769. if( !(func.parameterTypes.GetLength() == 0 && func.returnType.IsObjectHandle()) &&
  1770. !(func.parameterTypes.GetLength() == 1 && func.parameterTypes[0].GetTokenType() == ttQuestion && func.inOutFlags[0] == asTM_OUTREF && func.returnType.GetTokenType() == ttVoid) )
  1771. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1772. // Currently it is not supported to register const overloads for the ref cast behaviour
  1773. if( func.IsReadOnly() )
  1774. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1775. // Verify that the same cast is not registered already
  1776. // (const or non-const is treated the same for the return type)
  1777. if( func.parameterTypes.GetLength() == 1 )
  1778. {
  1779. // Check for existing behaviour with ?&out
  1780. for( asUINT n = 0; n < beh->operators.GetLength(); n+= 2 )
  1781. {
  1782. if( beh->operators[n] == asBEHAVE_REF_CAST ||
  1783. beh->operators[n] == asBEHAVE_IMPLICIT_REF_CAST )
  1784. {
  1785. asCScriptFunction *f = scriptFunctions[beh->operators[n+1]];
  1786. if( f->parameterTypes.GetLength() == 1 )
  1787. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1788. }
  1789. }
  1790. }
  1791. else
  1792. {
  1793. // Check for existing behaviour with same return type
  1794. for( asUINT n = 0; n < beh->operators.GetLength(); n+= 2 )
  1795. {
  1796. if( beh->operators[n] == asBEHAVE_REF_CAST ||
  1797. beh->operators[n] == asBEHAVE_IMPLICIT_REF_CAST )
  1798. {
  1799. asCScriptFunction *f = scriptFunctions[beh->operators[n+1]];
  1800. if( f->returnType.GetObjectType() == func.returnType.GetObjectType() )
  1801. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1802. }
  1803. }
  1804. }
  1805. beh->operators.PushLast(behaviour);
  1806. func.id = AddBehaviourFunction(func, internal);
  1807. beh->operators.PushLast(func.id);
  1808. }
  1809. else if ( behaviour == asBEHAVE_GET_WEAKREF_FLAG )
  1810. {
  1811. // This behaviour is only allowed for reference types
  1812. if( !(func.objectType->flags & asOBJ_REF) )
  1813. {
  1814. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1815. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1816. }
  1817. // Don't allow it if the type is registered with nohandle or scoped
  1818. if( func.objectType->flags & (asOBJ_NOHANDLE|asOBJ_SCOPED) )
  1819. {
  1820. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1821. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1822. }
  1823. // Verify that the return type is a reference since it needs to return a pointer to an asISharedBool
  1824. if( !func.returnType.IsReference() )
  1825. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1826. // Verify that there are no parameters
  1827. if( func.parameterTypes.GetLength() != 0 )
  1828. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1829. if( beh->getWeakRefFlag )
  1830. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1831. func.id = beh->getWeakRefFlag = AddBehaviourFunction(func, internal);
  1832. }
  1833. else
  1834. {
  1835. asASSERT(false);
  1836. return ConfigError(asINVALID_ARG, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1837. }
  1838. if( func.id < 0 )
  1839. return ConfigError(func.id, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1840. // Return function id as success
  1841. return func.id;
  1842. }
  1843. int asCScriptEngine::VerifyVarTypeNotInFunction(asCScriptFunction *func)
  1844. {
  1845. // Don't allow var type in this function
  1846. if( func->returnType.GetTokenType() == ttQuestion )
  1847. return asINVALID_DECLARATION;
  1848. for( unsigned int n = 0; n < func->parameterTypes.GetLength(); n++ )
  1849. if( func->parameterTypes[n].GetTokenType() == ttQuestion )
  1850. return asINVALID_DECLARATION;
  1851. return 0;
  1852. }
  1853. int asCScriptEngine::AddBehaviourFunction(asCScriptFunction &func, asSSystemFunctionInterface &internal)
  1854. {
  1855. asUINT n;
  1856. int id = GetNextScriptFunctionId();
  1857. asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
  1858. if( newInterface == 0 )
  1859. return asOUT_OF_MEMORY;
  1860. asCScriptFunction *f = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
  1861. if( f == 0 )
  1862. {
  1863. asDELETE(newInterface, asSSystemFunctionInterface);
  1864. return asOUT_OF_MEMORY;
  1865. }
  1866. asASSERT(func.name != "" && func.name != "f");
  1867. f->name = func.name;
  1868. f->sysFuncIntf = newInterface;
  1869. f->returnType = func.returnType;
  1870. f->objectType = func.objectType;
  1871. f->id = id;
  1872. f->isReadOnly = func.isReadOnly;
  1873. f->accessMask = defaultAccessMask;
  1874. f->parameterTypes = func.parameterTypes;
  1875. f->inOutFlags = func.inOutFlags;
  1876. for( n = 0; n < func.defaultArgs.GetLength(); n++ )
  1877. if( func.defaultArgs[n] )
  1878. f->defaultArgs.PushLast(asNEW(asCString)(*func.defaultArgs[n]));
  1879. else
  1880. f->defaultArgs.PushLast(0);
  1881. SetScriptFunction(f);
  1882. // If parameter type from other groups are used, add references
  1883. if( f->returnType.GetObjectType() )
  1884. {
  1885. asCConfigGroup *group = FindConfigGroupForObjectType(f->returnType.GetObjectType());
  1886. currentGroup->RefConfigGroup(group);
  1887. }
  1888. for( n = 0; n < f->parameterTypes.GetLength(); n++ )
  1889. {
  1890. if( f->parameterTypes[n].GetObjectType() )
  1891. {
  1892. asCConfigGroup *group = FindConfigGroupForObjectType(f->parameterTypes[n].GetObjectType());
  1893. currentGroup->RefConfigGroup(group);
  1894. }
  1895. }
  1896. return id;
  1897. }
  1898. // interface
  1899. int asCScriptEngine::RegisterGlobalProperty(const char *declaration, void *pointer)
  1900. {
  1901. // Don't accept a null pointer
  1902. if( pointer == 0 )
  1903. return ConfigError(asINVALID_ARG, "RegisterGlobalProperty", declaration, 0);
  1904. asCDataType type;
  1905. asCString name;
  1906. int r;
  1907. asCBuilder bld(this, 0);
  1908. if( (r = bld.VerifyProperty(0, declaration, name, type, defaultNamespace)) < 0 )
  1909. return ConfigError(r, "RegisterGlobalProperty", declaration, 0);
  1910. // Don't allow registering references as global properties
  1911. if( type.IsReference() )
  1912. return ConfigError(asINVALID_TYPE, "RegisterGlobalProperty", declaration, 0);
  1913. // Store the property info
  1914. asCGlobalProperty *prop = AllocateGlobalProperty();
  1915. prop->name = name;
  1916. prop->nameSpace = defaultNamespace;
  1917. prop->type = type;
  1918. prop->accessMask = defaultAccessMask;
  1919. prop->SetRegisteredAddress(pointer);
  1920. varAddressMap.Insert(prop->GetAddressOfValue(), prop);
  1921. registeredGlobalProps.Put(prop);
  1922. currentGroup->globalProps.PushLast(prop);
  1923. // If from another group add reference
  1924. if( type.GetObjectType() )
  1925. {
  1926. asCConfigGroup *group = FindConfigGroupForObjectType(type.GetObjectType());
  1927. currentGroup->RefConfigGroup(group);
  1928. }
  1929. return asSUCCESS;
  1930. }
  1931. // internal
  1932. asCGlobalProperty *asCScriptEngine::AllocateGlobalProperty()
  1933. {
  1934. asCGlobalProperty *prop = asNEW(asCGlobalProperty);
  1935. if( prop == 0 )
  1936. {
  1937. // Out of memory
  1938. return 0;
  1939. }
  1940. // First check the availability of a free slot
  1941. if( freeGlobalPropertyIds.GetLength() )
  1942. {
  1943. prop->id = freeGlobalPropertyIds.PopLast();
  1944. globalProperties[prop->id] = prop;
  1945. return prop;
  1946. }
  1947. prop->id = (asUINT)globalProperties.GetLength();
  1948. globalProperties.PushLast(prop);
  1949. return prop;
  1950. }
  1951. // internal
  1952. void asCScriptEngine::FreeUnusedGlobalProperties()
  1953. {
  1954. for( asUINT n = 0; n < globalProperties.GetLength(); n++ )
  1955. {
  1956. if( globalProperties[n] && globalProperties[n]->GetRefCount() == 0 )
  1957. {
  1958. freeGlobalPropertyIds.PushLast(n);
  1959. asSMapNode<void*, asCGlobalProperty*> *node;
  1960. varAddressMap.MoveTo(&node, globalProperties[n]->GetAddressOfValue());
  1961. asASSERT(node);
  1962. if( node )
  1963. varAddressMap.Erase(node);
  1964. asDELETE(globalProperties[n], asCGlobalProperty);
  1965. globalProperties[n] = 0;
  1966. }
  1967. }
  1968. }
  1969. // interface
  1970. asUINT asCScriptEngine::GetGlobalPropertyCount() const
  1971. {
  1972. return asUINT(registeredGlobalProps.GetSize());
  1973. }
  1974. // interface
  1975. // TODO: If the typeId ever encodes the const flag, then the isConst parameter should be removed
  1976. int asCScriptEngine::GetGlobalPropertyByIndex(asUINT index, const char **name, const char **nameSpace, int *typeId, bool *isConst, const char **configGroup, void **pointer, asDWORD *accessMask) const
  1977. {
  1978. const asCGlobalProperty *prop = registeredGlobalProps.Get(index);
  1979. if( !prop )
  1980. return asINVALID_ARG;
  1981. if( name ) *name = prop->name.AddressOf();
  1982. if( nameSpace ) *nameSpace = prop->nameSpace->name.AddressOf();
  1983. if( typeId ) *typeId = GetTypeIdFromDataType(prop->type);
  1984. if( isConst ) *isConst = prop->type.IsReadOnly();
  1985. if( pointer ) *pointer = prop->GetRegisteredAddress();
  1986. if( accessMask ) *accessMask = prop->accessMask;
  1987. if( configGroup )
  1988. {
  1989. asCConfigGroup *group = FindConfigGroupForGlobalVar(index);
  1990. if( group )
  1991. *configGroup = group->groupName.AddressOf();
  1992. else
  1993. *configGroup = 0;
  1994. }
  1995. return asSUCCESS;
  1996. }
  1997. // interface
  1998. int asCScriptEngine::GetGlobalPropertyIndexByName(const char *name) const
  1999. {
  2000. // Find the global var id
  2001. int id = registeredGlobalProps.GetFirstIndex(defaultNamespace, name);
  2002. if( id == -1 ) return asNO_GLOBAL_VAR;
  2003. return id;
  2004. }
  2005. // interface
  2006. int asCScriptEngine::GetGlobalPropertyIndexByDecl(const char *decl) const
  2007. {
  2008. // This const cast is OK. The builder won't modify the engine
  2009. asCBuilder bld(const_cast<asCScriptEngine*>(this), 0);
  2010. asCString name;
  2011. asSNameSpace *ns;
  2012. asCDataType dt;
  2013. int r = bld.ParseVariableDeclaration(decl, defaultNamespace, name, ns, dt);
  2014. if( r < 0 )
  2015. return r;
  2016. // Search for a match
  2017. int id = registeredGlobalProps.GetFirstIndex(ns, name, asCCompGlobPropType(dt));
  2018. if (id < 0)
  2019. return asNO_GLOBAL_VAR;
  2020. return id;
  2021. }
  2022. // interface
  2023. int asCScriptEngine::RegisterObjectMethod(const char *obj, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv)
  2024. {
  2025. if( obj == 0 )
  2026. return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
  2027. // Determine the object type
  2028. asCDataType dt;
  2029. asCBuilder bld(this, 0);
  2030. int r = bld.ParseDataType(obj, &dt, defaultNamespace);
  2031. if( r < 0 )
  2032. return ConfigError(r, "RegisterObjectMethod", obj, declaration);
  2033. if( dt.GetObjectType() == 0 )
  2034. return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
  2035. // Don't allow application to modify built-in types
  2036. if( dt.GetObjectType() == &functionBehaviours ||
  2037. dt.GetObjectType() == &objectTypeBehaviours ||
  2038. dt.GetObjectType() == &globalPropertyBehaviours ||
  2039. dt.GetObjectType() == &scriptTypeBehaviours )
  2040. return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
  2041. return RegisterMethodToObjectType(dt.GetObjectType(), declaration, funcPointer, callConv);
  2042. }
  2043. // internal
  2044. int asCScriptEngine::RegisterMethodToObjectType(asCObjectType *objectType, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv)
  2045. {
  2046. asSSystemFunctionInterface internal;
  2047. int r = DetectCallingConvention(true, funcPointer, callConv, 0, &internal);
  2048. if( r < 0 )
  2049. return ConfigError(r, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2050. // We only support these calling conventions for object methods
  2051. #ifdef AS_MAX_PORTABILITY
  2052. if( callConv != asCALL_GENERIC )
  2053. return ConfigError(asNOT_SUPPORTED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2054. #else
  2055. if( callConv != asCALL_THISCALL &&
  2056. callConv != asCALL_CDECL_OBJLAST &&
  2057. callConv != asCALL_CDECL_OBJFIRST &&
  2058. callConv != asCALL_GENERIC )
  2059. return ConfigError(asNOT_SUPPORTED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2060. #endif
  2061. isPrepared = false;
  2062. // Put the system function in the list of system functions
  2063. asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
  2064. if( newInterface == 0 )
  2065. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2066. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
  2067. if( func == 0 )
  2068. {
  2069. asDELETE(newInterface, asSSystemFunctionInterface);
  2070. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2071. }
  2072. func->sysFuncIntf = newInterface;
  2073. func->objectType = objectType;
  2074. asCBuilder bld(this, 0);
  2075. r = bld.ParseFunctionDeclaration(func->objectType, declaration, func, true, &newInterface->paramAutoHandles, &newInterface->returnAutoHandle);
  2076. if( r < 0 )
  2077. {
  2078. // Set as dummy function before deleting
  2079. func->funcType = asFUNC_DUMMY;
  2080. asDELETE(func,asCScriptFunction);
  2081. return ConfigError(asINVALID_DECLARATION, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2082. }
  2083. // Check name conflicts
  2084. r = bld.CheckNameConflictMember(objectType, func->name.AddressOf(), 0, 0, false);
  2085. if( r < 0 )
  2086. {
  2087. func->funcType = asFUNC_DUMMY;
  2088. asDELETE(func,asCScriptFunction);
  2089. return ConfigError(asNAME_TAKEN, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2090. }
  2091. // Check against duplicate methods
  2092. asUINT n;
  2093. for( n = 0; n < func->objectType->methods.GetLength(); n++ )
  2094. {
  2095. asCScriptFunction *f = scriptFunctions[func->objectType->methods[n]];
  2096. if( f->name == func->name &&
  2097. f->IsSignatureExceptNameAndReturnTypeEqual(func) )
  2098. {
  2099. func->funcType = asFUNC_DUMMY;
  2100. asDELETE(func,asCScriptFunction);
  2101. return ConfigError(asALREADY_REGISTERED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2102. }
  2103. }
  2104. func->id = GetNextScriptFunctionId();
  2105. func->objectType->methods.PushLast(func->id);
  2106. func->accessMask = defaultAccessMask;
  2107. SetScriptFunction(func);
  2108. // TODO: This code is repeated in many places
  2109. // If parameter type from other groups are used, add references
  2110. if( func->returnType.GetObjectType() )
  2111. {
  2112. asCConfigGroup *group = FindConfigGroupForObjectType(func->returnType.GetObjectType());
  2113. currentGroup->RefConfigGroup(group);
  2114. }
  2115. for( n = 0; n < func->parameterTypes.GetLength(); n++ )
  2116. {
  2117. if( func->parameterTypes[n].GetObjectType() )
  2118. {
  2119. asCConfigGroup *group = FindConfigGroupForObjectType(func->parameterTypes[n].GetObjectType());
  2120. currentGroup->RefConfigGroup(group);
  2121. }
  2122. }
  2123. // Check if the method restricts that use of the template to value types or reference types
  2124. if( func->objectType->flags & asOBJ_TEMPLATE )
  2125. {
  2126. for( asUINT subTypeIdx = 0; subTypeIdx < func->objectType->templateSubTypes.GetLength(); subTypeIdx++ )
  2127. {
  2128. if( func->returnType.GetObjectType() == func->objectType->templateSubTypes[subTypeIdx].GetObjectType() )
  2129. {
  2130. if( func->returnType.IsObjectHandle() )
  2131. func->objectType->acceptValueSubType = false;
  2132. else if( !func->returnType.IsReference() )
  2133. func->objectType->acceptRefSubType = false;
  2134. }
  2135. for( asUINT n = 0; n < func->parameterTypes.GetLength(); n++ )
  2136. {
  2137. if( func->parameterTypes[n].GetObjectType() == func->objectType->templateSubTypes[subTypeIdx].GetObjectType() )
  2138. {
  2139. // TODO: If unsafe references are allowed, then inout references allow value types
  2140. if( func->parameterTypes[n].IsObjectHandle() || (func->parameterTypes[n].IsReference() && func->inOutFlags[n] == asTM_INOUTREF) )
  2141. func->objectType->acceptValueSubType = false;
  2142. else if( !func->parameterTypes[n].IsReference() )
  2143. func->objectType->acceptRefSubType = false;
  2144. }
  2145. }
  2146. }
  2147. }
  2148. // TODO: beh.copy member will be removed, so this is not necessary
  2149. // Is this the default copy behaviour?
  2150. if( func->name == "opAssign" && func->parameterTypes.GetLength() == 1 && func->isReadOnly == false &&
  2151. (objectType->flags & asOBJ_SCRIPT_OBJECT || func->parameterTypes[0].IsEqualExceptRefAndConst(asCDataType::CreateObject(func->objectType, false))) )
  2152. {
  2153. func->objectType->beh.copy = func->id;
  2154. func->AddRef();
  2155. }
  2156. // Return the function id as success
  2157. return func->id;
  2158. }
  2159. // interface
  2160. int asCScriptEngine::RegisterGlobalFunction(const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall)
  2161. {
  2162. asSSystemFunctionInterface internal;
  2163. int r = DetectCallingConvention(false, funcPointer, callConv, objForThiscall, &internal);
  2164. if( r < 0 )
  2165. return ConfigError(r, "RegisterGlobalFunction", declaration, 0);
  2166. #ifdef AS_MAX_PORTABILITY
  2167. if( callConv != asCALL_GENERIC )
  2168. return ConfigError(asNOT_SUPPORTED, "RegisterGlobalFunction", declaration, 0);
  2169. #else
  2170. if( callConv != asCALL_CDECL &&
  2171. callConv != asCALL_STDCALL &&
  2172. callConv != asCALL_THISCALL_ASGLOBAL &&
  2173. callConv != asCALL_GENERIC )
  2174. return ConfigError(asNOT_SUPPORTED, "RegisterGlobalFunction", declaration, 0);
  2175. #endif
  2176. isPrepared = false;
  2177. // Put the system function in the list of system functions
  2178. asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
  2179. if( newInterface == 0 )
  2180. return ConfigError(asOUT_OF_MEMORY, "RegisterGlobalFunction", declaration, 0);
  2181. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
  2182. if( func == 0 )
  2183. {
  2184. asDELETE(newInterface, asSSystemFunctionInterface);
  2185. return ConfigError(asOUT_OF_MEMORY, "RegisterGlobalFunction", declaration, 0);
  2186. }
  2187. func->sysFuncIntf = newInterface;
  2188. asCBuilder bld(this, 0);
  2189. r = bld.ParseFunctionDeclaration(0, declaration, func, true, &newInterface->paramAutoHandles, &newInterface->returnAutoHandle, defaultNamespace);
  2190. if( r < 0 )
  2191. {
  2192. // Set as dummy function before deleting
  2193. func->funcType = asFUNC_DUMMY;
  2194. asDELETE(func,asCScriptFunction);
  2195. return ConfigError(asINVALID_DECLARATION, "RegisterGlobalFunction", declaration, 0);
  2196. }
  2197. // TODO: namespace: What if the declaration defined an explicit namespace?
  2198. func->nameSpace = defaultNamespace;
  2199. // Check name conflicts
  2200. r = bld.CheckNameConflict(func->name.AddressOf(), 0, 0, defaultNamespace);
  2201. if( r < 0 )
  2202. {
  2203. // Set as dummy function before deleting
  2204. func->funcType = asFUNC_DUMMY;
  2205. asDELETE(func,asCScriptFunction);
  2206. return ConfigError(asNAME_TAKEN, "RegisterGlobalFunction", declaration, 0);
  2207. }
  2208. // Make sure the function is not identical to a previously registered function
  2209. asUINT n;
  2210. for( n = 0; n < registeredGlobalFuncs.GetLength(); n++ )
  2211. {
  2212. asCScriptFunction *f = registeredGlobalFuncs[n];
  2213. if( f->name == func->name &&
  2214. f->nameSpace == func->nameSpace &&
  2215. f->IsSignatureExceptNameAndReturnTypeEqual(func) )
  2216. {
  2217. func->funcType = asFUNC_DUMMY;
  2218. asDELETE(func,asCScriptFunction);
  2219. return ConfigError(asALREADY_REGISTERED, "RegisterGlobalFunction", declaration, 0);
  2220. }
  2221. }
  2222. func->id = GetNextScriptFunctionId();
  2223. SetScriptFunction(func);
  2224. currentGroup->scriptFunctions.PushLast(func);
  2225. func->accessMask = defaultAccessMask;
  2226. registeredGlobalFuncs.PushLast(func);
  2227. // If parameter type from other groups are used, add references
  2228. if( func->returnType.GetObjectType() )
  2229. {
  2230. asCConfigGroup *group = FindConfigGroupForObjectType(func->returnType.GetObjectType());
  2231. currentGroup->RefConfigGroup(group);
  2232. }
  2233. for( n = 0; n < func->parameterTypes.GetLength(); n++ )
  2234. {
  2235. if( func->parameterTypes[n].GetObjectType() )
  2236. {
  2237. asCConfigGroup *group = FindConfigGroupForObjectType(func->parameterTypes[n].GetObjectType());
  2238. currentGroup->RefConfigGroup(group);
  2239. }
  2240. }
  2241. // Return the function id as success
  2242. return func->id;
  2243. }
  2244. // interface
  2245. asUINT asCScriptEngine::GetGlobalFunctionCount() const
  2246. {
  2247. // Don't count the builtin delegate factory
  2248. return asUINT(registeredGlobalFuncs.GetLength()-1);
  2249. }
  2250. // interface
  2251. asIScriptFunction *asCScriptEngine::GetGlobalFunctionByIndex(asUINT index) const
  2252. {
  2253. // Don't count the builtin delegate factory
  2254. index++;
  2255. if( index >= registeredGlobalFuncs.GetLength() )
  2256. return 0;
  2257. return registeredGlobalFuncs[index];
  2258. }
  2259. // interface
  2260. asIScriptFunction *asCScriptEngine::GetGlobalFunctionByDecl(const char *decl) const
  2261. {
  2262. asCBuilder bld(const_cast<asCScriptEngine*>(this), 0);
  2263. asCScriptFunction func(const_cast<asCScriptEngine*>(this), 0, asFUNC_DUMMY);
  2264. int r = bld.ParseFunctionDeclaration(0, decl, &func, false, 0, 0, defaultNamespace);
  2265. if( r < 0 )
  2266. return 0;
  2267. // TODO: optimize: Improve linear search
  2268. // Search registered functions for matching interface
  2269. int id = -1;
  2270. for( size_t n = 0; n < registeredGlobalFuncs.GetLength(); ++n )
  2271. {
  2272. if( registeredGlobalFuncs[n]->objectType == 0 &&
  2273. func.name == registeredGlobalFuncs[n]->name &&
  2274. func.returnType == registeredGlobalFuncs[n]->returnType &&
  2275. func.parameterTypes.GetLength() == registeredGlobalFuncs[n]->parameterTypes.GetLength() )
  2276. {
  2277. bool match = true;
  2278. for( size_t p = 0; p < func.parameterTypes.GetLength(); ++p )
  2279. {
  2280. if( func.parameterTypes[p] != registeredGlobalFuncs[n]->parameterTypes[p] )
  2281. {
  2282. match = false;
  2283. break;
  2284. }
  2285. }
  2286. if( match )
  2287. {
  2288. if( id == -1 )
  2289. id = registeredGlobalFuncs[n]->id;
  2290. else
  2291. return 0; // Multiple matches
  2292. }
  2293. }
  2294. }
  2295. if( id < 0 ) return 0; // No matches
  2296. return scriptFunctions[id];
  2297. }
  2298. asCObjectType *asCScriptEngine::GetObjectType(const char *type, asSNameSpace *ns)
  2299. {
  2300. // TODO: optimize: Improve linear search
  2301. for( asUINT n = 0; n < objectTypes.GetLength(); n++ )
  2302. if( objectTypes[n] &&
  2303. objectTypes[n]->name == type &&
  2304. objectTypes[n]->nameSpace == ns ) // TODO: template: Should we check the subtype in case of template instances?
  2305. return objectTypes[n];
  2306. return 0;
  2307. }
  2308. void asCScriptEngine::PrepareEngine()
  2309. {
  2310. if( isPrepared ) return;
  2311. if( configFailed ) return;
  2312. asUINT n;
  2313. for( n = 0; n < scriptFunctions.GetLength(); n++ )
  2314. {
  2315. // Determine the host application interface
  2316. if( scriptFunctions[n] && scriptFunctions[n]->funcType == asFUNC_SYSTEM )
  2317. {
  2318. if( scriptFunctions[n]->sysFuncIntf->callConv == ICC_GENERIC_FUNC ||
  2319. scriptFunctions[n]->sysFuncIntf->callConv == ICC_GENERIC_METHOD )
  2320. PrepareSystemFunctionGeneric(scriptFunctions[n], scriptFunctions[n]->sysFuncIntf, this);
  2321. else
  2322. PrepareSystemFunction(scriptFunctions[n], scriptFunctions[n]->sysFuncIntf, this);
  2323. }
  2324. }
  2325. // Validate object type registrations
  2326. for( n = 0; n < objectTypes.GetLength(); n++ )
  2327. {
  2328. if( objectTypes[n] && !(objectTypes[n]->flags & asOBJ_SCRIPT_OBJECT) )
  2329. {
  2330. bool missingBehaviour = false;
  2331. const char *infoMsg = 0;
  2332. // Verify that GC types have all behaviours
  2333. if( objectTypes[n]->flags & asOBJ_GC )
  2334. {
  2335. if( objectTypes[n]->beh.addref == 0 ||
  2336. objectTypes[n]->beh.release == 0 ||
  2337. objectTypes[n]->beh.gcGetRefCount == 0 ||
  2338. objectTypes[n]->beh.gcSetFlag == 0 ||
  2339. objectTypes[n]->beh.gcGetFlag == 0 ||
  2340. objectTypes[n]->beh.gcEnumReferences == 0 ||
  2341. objectTypes[n]->beh.gcReleaseAllReferences == 0 )
  2342. {
  2343. infoMsg = TXT_GC_REQUIRE_ADD_REL_GC_BEHAVIOUR;
  2344. missingBehaviour = true;
  2345. }
  2346. }
  2347. // Verify that scoped ref types have the release behaviour
  2348. else if( objectTypes[n]->flags & asOBJ_SCOPED )
  2349. {
  2350. if( objectTypes[n]->beh.release == 0 )
  2351. {
  2352. infoMsg = TXT_SCOPE_REQUIRE_REL_BEHAVIOUR;
  2353. missingBehaviour = true;
  2354. }
  2355. }
  2356. // Verify that ref types have add ref and release behaviours
  2357. else if( (objectTypes[n]->flags & asOBJ_REF) &&
  2358. !(objectTypes[n]->flags & asOBJ_NOHANDLE) &&
  2359. !(objectTypes[n]->flags & asOBJ_NOCOUNT) )
  2360. {
  2361. if( objectTypes[n]->beh.addref == 0 ||
  2362. objectTypes[n]->beh.release == 0 )
  2363. {
  2364. infoMsg = TXT_REF_REQUIRE_ADD_REL_BEHAVIOUR;
  2365. missingBehaviour = true;
  2366. }
  2367. }
  2368. // Verify that non-pod value types have the constructor and destructor registered
  2369. else if( (objectTypes[n]->flags & asOBJ_VALUE) &&
  2370. !(objectTypes[n]->flags & asOBJ_POD) )
  2371. {
  2372. if( objectTypes[n]->beh.construct == 0 ||
  2373. objectTypes[n]->beh.destruct == 0 )
  2374. {
  2375. infoMsg = TXT_NON_POD_REQUIRE_CONSTR_DESTR_BEHAVIOUR;
  2376. missingBehaviour = true;
  2377. }
  2378. }
  2379. if( missingBehaviour )
  2380. {
  2381. asCString str;
  2382. str.Format(TXT_TYPE_s_IS_MISSING_BEHAVIOURS, objectTypes[n]->name.AddressOf());
  2383. WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2384. WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, infoMsg);
  2385. ConfigError(asINVALID_CONFIGURATION, 0, 0, 0);
  2386. }
  2387. }
  2388. }
  2389. isPrepared = true;
  2390. }
  2391. int asCScriptEngine::ConfigError(int err, const char *funcName, const char *arg1, const char *arg2)
  2392. {
  2393. configFailed = true;
  2394. if( funcName )
  2395. {
  2396. asCString str;
  2397. if( arg1 )
  2398. {
  2399. if( arg2 )
  2400. str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_AND_s_d, funcName, arg1, arg2, err);
  2401. else
  2402. str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_d, funcName, arg1, err);
  2403. }
  2404. else
  2405. str.Format(TXT_FAILED_IN_FUNC_s_d, funcName, err);
  2406. WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2407. }
  2408. return err;
  2409. }
  2410. // interface
  2411. int asCScriptEngine::RegisterDefaultArrayType(const char *type)
  2412. {
  2413. asCBuilder bld(this, 0);
  2414. asCDataType dt;
  2415. int r = bld.ParseDataType(type, &dt, defaultNamespace);
  2416. if( r < 0 ) return r;
  2417. if( dt.GetObjectType() == 0 ||
  2418. !(dt.GetObjectType()->GetFlags() & asOBJ_TEMPLATE) )
  2419. return asINVALID_TYPE;
  2420. defaultArrayObjectType = dt.GetObjectType();
  2421. defaultArrayObjectType->AddRef();
  2422. return 0;
  2423. }
  2424. // interface
  2425. int asCScriptEngine::GetDefaultArrayTypeId() const
  2426. {
  2427. if( defaultArrayObjectType )
  2428. return GetTypeIdFromDataType(asCDataType::CreateObject(defaultArrayObjectType, false));
  2429. return asINVALID_TYPE;
  2430. }
  2431. // interface
  2432. int asCScriptEngine::RegisterStringFactory(const char *datatype, const asSFuncPtr &funcPointer, asDWORD callConv, void *objForThiscall)
  2433. {
  2434. asSSystemFunctionInterface internal;
  2435. int r = DetectCallingConvention(false, funcPointer, callConv, objForThiscall, &internal);
  2436. if( r < 0 )
  2437. return ConfigError(r, "RegisterStringFactory", datatype, 0);
  2438. #ifdef AS_MAX_PORTABILITY
  2439. if( callConv != asCALL_GENERIC )
  2440. return ConfigError(asNOT_SUPPORTED, "RegisterStringFactory", datatype, 0);
  2441. #else
  2442. if( callConv != asCALL_CDECL &&
  2443. callConv != asCALL_STDCALL &&
  2444. callConv != asCALL_THISCALL_ASGLOBAL &&
  2445. callConv != asCALL_GENERIC )
  2446. return ConfigError(asNOT_SUPPORTED, "RegisterStringFactory", datatype, 0);
  2447. #endif
  2448. // Put the system function in the list of system functions
  2449. asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
  2450. if( newInterface == 0 )
  2451. return ConfigError(asOUT_OF_MEMORY, "RegisterStringFactory", datatype, 0);
  2452. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
  2453. if( func == 0 )
  2454. {
  2455. asDELETE(newInterface, asSSystemFunctionInterface);
  2456. return ConfigError(asOUT_OF_MEMORY, "RegisterStringFactory", datatype, 0);
  2457. }
  2458. func->name = "_string_factory_";
  2459. func->sysFuncIntf = newInterface;
  2460. asCBuilder bld(this, 0);
  2461. asCDataType dt;
  2462. r = bld.ParseDataType(datatype, &dt, defaultNamespace, true);
  2463. if( r < 0 )
  2464. {
  2465. // Set as dummy before deleting
  2466. func->funcType = asFUNC_DUMMY;
  2467. asDELETE(func,asCScriptFunction);
  2468. return ConfigError(asINVALID_TYPE, "RegisterStringFactory", datatype, 0);
  2469. }
  2470. func->returnType = dt;
  2471. func->parameterTypes.PushLast(asCDataType::CreatePrimitive(ttInt, true));
  2472. asCDataType parm1 = asCDataType::CreatePrimitive(ttUInt8, true);
  2473. parm1.MakeReference(true);
  2474. func->parameterTypes.PushLast(parm1);
  2475. func->id = GetNextScriptFunctionId();
  2476. SetScriptFunction(func);
  2477. stringFactory = func;
  2478. if( func->returnType.GetObjectType() )
  2479. {
  2480. asCConfigGroup *group = FindConfigGroupForObjectType(func->returnType.GetObjectType());
  2481. if( group == 0 ) group = &defaultGroup;
  2482. group->scriptFunctions.PushLast(func);
  2483. }
  2484. // Register function id as success
  2485. return func->id;
  2486. }
  2487. // interface
  2488. int asCScriptEngine::GetStringFactoryReturnTypeId() const
  2489. {
  2490. if( stringFactory == 0 )
  2491. return asNO_FUNCTION;
  2492. return GetTypeIdFromDataType(stringFactory->returnType);
  2493. }
  2494. // interface
  2495. asCModule *asCScriptEngine::GetModule(const char *_name, bool create)
  2496. {
  2497. // Accept null as well as zero-length string
  2498. const char *name = "";
  2499. if( _name != 0 ) name = _name;
  2500. if( lastModule && lastModule->name == name )
  2501. return lastModule;
  2502. // TODO: optimize: Improve linear search
  2503. for( asUINT n = 0; n < scriptModules.GetLength(); ++n )
  2504. if( scriptModules[n] && scriptModules[n]->name == name )
  2505. {
  2506. lastModule = scriptModules[n];
  2507. return lastModule;
  2508. }
  2509. if( create )
  2510. {
  2511. asCModule *module = asNEW(asCModule)(name, this);
  2512. if( module == 0 )
  2513. {
  2514. // Out of memory
  2515. return 0;
  2516. }
  2517. scriptModules.PushLast(module);
  2518. lastModule = module;
  2519. return lastModule;
  2520. }
  2521. return 0;
  2522. }
  2523. asCModule *asCScriptEngine::GetModuleFromFuncId(int id)
  2524. {
  2525. if( id < 0 ) return 0;
  2526. if( id >= (int)scriptFunctions.GetLength() ) return 0;
  2527. asCScriptFunction *func = scriptFunctions[id];
  2528. if( func == 0 ) return 0;
  2529. return func->module;
  2530. }
  2531. // internal
  2532. int asCScriptEngine::RequestBuild()
  2533. {
  2534. ACQUIREEXCLUSIVE(engineRWLock);
  2535. if( isBuilding )
  2536. {
  2537. RELEASEEXCLUSIVE(engineRWLock);
  2538. return asBUILD_IN_PROGRESS;
  2539. }
  2540. isBuilding = true;
  2541. RELEASEEXCLUSIVE(engineRWLock);
  2542. return 0;
  2543. }
  2544. // internal
  2545. void asCScriptEngine::BuildCompleted()
  2546. {
  2547. // Always free up pooled memory after a completed build
  2548. memoryMgr.FreeUnusedMemory();
  2549. isBuilding = false;
  2550. }
  2551. void asCScriptEngine::RemoveTemplateInstanceType(asCObjectType *t)
  2552. {
  2553. int n;
  2554. // Destroy the factory stubs
  2555. for( n = 0; n < (int)t->beh.factories.GetLength(); n++ )
  2556. {
  2557. // Make sure the factory stub isn't referencing this object anymore
  2558. scriptFunctions[t->beh.factories[n]]->ReleaseAllHandles(this);
  2559. scriptFunctions[t->beh.factories[n]]->Release();
  2560. }
  2561. t->beh.factories.SetLength(0);
  2562. // Destroy the stub for the list factory too
  2563. if( t->beh.listFactory )
  2564. {
  2565. scriptFunctions[t->beh.listFactory]->ReleaseAllHandles(this);
  2566. scriptFunctions[t->beh.listFactory]->Release();
  2567. t->beh.listFactory = 0;
  2568. }
  2569. // Destroy the specialized functions
  2570. for( n = 1; n < (int)t->beh.operators.GetLength(); n += 2 )
  2571. {
  2572. if( t->beh.operators[n] && scriptFunctions[t->beh.operators[n]]->objectType == t )
  2573. {
  2574. scriptFunctions[t->beh.operators[n]]->Release();
  2575. }
  2576. }
  2577. t->beh.operators.SetLength(0);
  2578. // Start searching from the end of the list, as most of
  2579. // the time it will be the last two types
  2580. for( n = (int)templateTypes.GetLength()-1; n >= 0; n-- )
  2581. {
  2582. if( templateTypes[n] == t )
  2583. {
  2584. if( n == (signed)templateTypes.GetLength()-1 )
  2585. templateTypes.PopLast();
  2586. else
  2587. templateTypes[n] = templateTypes.PopLast();
  2588. }
  2589. }
  2590. for( n = (int)templateInstanceTypes.GetLength()-1; n >= 0; n-- )
  2591. {
  2592. if( templateInstanceTypes[n] == t )
  2593. {
  2594. if( n == (signed)templateInstanceTypes.GetLength()-1 )
  2595. templateInstanceTypes.PopLast();
  2596. else
  2597. templateInstanceTypes[n] = templateInstanceTypes.PopLast();
  2598. }
  2599. }
  2600. asDELETE(t,asCObjectType);
  2601. }
  2602. // internal
  2603. void asCScriptEngine::OrphanTemplateInstances(asCObjectType *subType)
  2604. {
  2605. for( asUINT n = 0; n < templateTypes.GetLength(); n++ )
  2606. {
  2607. if( templateTypes[n] == 0 )
  2608. continue;
  2609. // If the template type isn't owned by any module it can't be orphaned
  2610. if( templateTypes[n]->module == 0 )
  2611. continue;
  2612. for( asUINT subTypeIdx = 0; subTypeIdx < templateTypes[n]->templateSubTypes.GetLength(); subTypeIdx++ )
  2613. {
  2614. if( templateTypes[n]->templateSubTypes[subTypeIdx].GetObjectType() == subType )
  2615. {
  2616. // Tell the GC that the template type exists so it can resolve potential circular references
  2617. gc.AddScriptObjectToGC(templateTypes[n], &objectTypeBehaviours);
  2618. // Clear the module
  2619. templateTypes[n]->module = 0;
  2620. templateTypes[n]->Release();
  2621. // Do a recursive check for other template instances
  2622. OrphanTemplateInstances(templateTypes[n]);
  2623. // Break out so we don't add the same template to
  2624. // the gc again if another subtype matches this one
  2625. break;
  2626. }
  2627. }
  2628. }
  2629. }
  2630. // internal
  2631. asCObjectType *asCScriptEngine::GetTemplateInstanceType(asCObjectType *templateType, asCArray<asCDataType> &subTypes)
  2632. {
  2633. asUINT n;
  2634. // Is there any template instance type or template specialization already with this subtype?
  2635. for( n = 0; n < templateTypes.GetLength(); n++ )
  2636. {
  2637. if( templateTypes[n] &&
  2638. templateTypes[n]->name == templateType->name &&
  2639. templateTypes[n]->templateSubTypes == subTypes )
  2640. return templateTypes[n];
  2641. }
  2642. // No previous template instance exists
  2643. // Make sure this template supports the subtype
  2644. for( n = 0; n < subTypes.GetLength(); n++ )
  2645. {
  2646. if( !templateType->acceptValueSubType && (subTypes[n].IsPrimitive() || (subTypes[n].GetObjectType()->flags & asOBJ_VALUE)) )
  2647. return 0;
  2648. if( !templateType->acceptRefSubType && (subTypes[n].IsObject() && (subTypes[n].GetObjectType()->flags & asOBJ_REF)) )
  2649. return 0;
  2650. }
  2651. // Create a new template instance type based on the templateType
  2652. asCObjectType *ot = asNEW(asCObjectType)(this);
  2653. if( ot == 0 )
  2654. {
  2655. // Out of memory
  2656. return 0;
  2657. }
  2658. ot->templateSubTypes = subTypes;
  2659. ot->flags = templateType->flags;
  2660. ot->size = templateType->size;
  2661. ot->name = templateType->name;
  2662. // The template instance type will inherit the same module as the subType
  2663. // This will allow the module to orphan the template instance types afterwards
  2664. for( n = 0; n < subTypes.GetLength(); n++ )
  2665. {
  2666. if( subTypes[n].GetObjectType() )
  2667. {
  2668. ot->module = subTypes[n].GetObjectType()->module;
  2669. if( ot->module )
  2670. {
  2671. ot->AddRef();
  2672. break;
  2673. }
  2674. }
  2675. }
  2676. // Before filling in the methods, call the template instance callback behaviour to validate the type
  2677. if( templateType->beh.templateCallback )
  2678. {
  2679. bool dontGarbageCollect = false;
  2680. asCScriptFunction *callback = scriptFunctions[templateType->beh.templateCallback];
  2681. if( !CallGlobalFunctionRetBool(ot, &dontGarbageCollect, callback->sysFuncIntf, callback) )
  2682. {
  2683. // If the validation is deferred then the validation will be done later,
  2684. // so it is necessary to continue the preparation of the template instance type
  2685. if( !deferValidationOfTemplateTypes )
  2686. {
  2687. // The type cannot be instanciated
  2688. ot->templateSubTypes.SetLength(0);
  2689. asDELETE(ot, asCObjectType);
  2690. return 0;
  2691. }
  2692. }
  2693. // If the callback said this template instance won't be garbage collected then remove the flag
  2694. if( dontGarbageCollect )
  2695. ot->flags &= ~asOBJ_GC;
  2696. ot->beh.templateCallback = templateType->beh.templateCallback;
  2697. scriptFunctions[ot->beh.templateCallback]->AddRef();
  2698. }
  2699. ot->methods = templateType->methods;
  2700. for( n = 0; n < ot->methods.GetLength(); n++ )
  2701. scriptFunctions[ot->methods[n]]->AddRef();
  2702. // Store the real factory in the constructor. This is used by the CreateScriptObject function.
  2703. // Otherwise it wouldn't be necessary to store the real factory ids.
  2704. ot->beh.construct = templateType->beh.factory;
  2705. ot->beh.constructors = templateType->beh.factories;
  2706. for( n = 0; n < ot->beh.constructors.GetLength(); n++ )
  2707. scriptFunctions[ot->beh.constructors[n]]->AddRef();
  2708. ot->beh.factory = 0;
  2709. // Generate factory stubs for each of the factories
  2710. for( n = 0; n < templateType->beh.factories.GetLength(); n++ )
  2711. {
  2712. asCScriptFunction *func = GenerateTemplateFactoryStub(templateType, ot, templateType->beh.factories[n]);
  2713. // The function's refCount was already initialized to 1
  2714. ot->beh.factories.PushLast(func->id);
  2715. // Set the default factory as well
  2716. if( templateType->beh.factories[n] == templateType->beh.factory )
  2717. ot->beh.factory = func->id;
  2718. }
  2719. // Generate stub for the list factory as well
  2720. if( templateType->beh.listFactory )
  2721. {
  2722. asCScriptFunction *func = GenerateTemplateFactoryStub(templateType, ot, templateType->beh.listFactory);
  2723. // The function's refCount was already initialized to 1
  2724. ot->beh.listFactory = func->id;
  2725. }
  2726. ot->beh.addref = templateType->beh.addref;
  2727. if( scriptFunctions[ot->beh.addref] ) scriptFunctions[ot->beh.addref]->AddRef();
  2728. ot->beh.release = templateType->beh.release;
  2729. if( scriptFunctions[ot->beh.release] ) scriptFunctions[ot->beh.release]->AddRef();
  2730. ot->beh.copy = templateType->beh.copy;
  2731. if( scriptFunctions[ot->beh.copy] ) scriptFunctions[ot->beh.copy]->AddRef();
  2732. ot->beh.operators = templateType->beh.operators;
  2733. for( n = 1; n < ot->beh.operators.GetLength(); n += 2 )
  2734. scriptFunctions[ot->beh.operators[n]]->AddRef();
  2735. ot->beh.gcGetRefCount = templateType->beh.gcGetRefCount;
  2736. if( scriptFunctions[ot->beh.gcGetRefCount] ) scriptFunctions[ot->beh.gcGetRefCount]->AddRef();
  2737. ot->beh.gcSetFlag = templateType->beh.gcSetFlag;
  2738. if( scriptFunctions[ot->beh.gcSetFlag] ) scriptFunctions[ot->beh.gcSetFlag]->AddRef();
  2739. ot->beh.gcGetFlag = templateType->beh.gcGetFlag;
  2740. if( scriptFunctions[ot->beh.gcGetFlag] ) scriptFunctions[ot->beh.gcGetFlag]->AddRef();
  2741. ot->beh.gcEnumReferences = templateType->beh.gcEnumReferences;
  2742. if( scriptFunctions[ot->beh.gcEnumReferences] ) scriptFunctions[ot->beh.gcEnumReferences]->AddRef();
  2743. ot->beh.gcReleaseAllReferences = templateType->beh.gcReleaseAllReferences;
  2744. if( scriptFunctions[ot->beh.gcReleaseAllReferences] ) scriptFunctions[ot->beh.gcReleaseAllReferences]->AddRef();
  2745. ot->beh.getWeakRefFlag = templateType->beh.getWeakRefFlag;
  2746. if( scriptFunctions[ot->beh.getWeakRefFlag] ) scriptFunctions[ot->beh.getWeakRefFlag]->AddRef();
  2747. // As the new template type is instanciated the engine should
  2748. // generate new functions to substitute the ones with the template subtype.
  2749. for( n = 1; n < ot->beh.operators.GetLength(); n += 2 )
  2750. {
  2751. int funcId = ot->beh.operators[n];
  2752. asCScriptFunction *func = scriptFunctions[funcId];
  2753. if( GenerateNewTemplateFunction(templateType, ot, func, &func) )
  2754. {
  2755. // Release the old function, the new one already has its ref count set to 1
  2756. scriptFunctions[funcId]->Release();
  2757. ot->beh.operators[n] = func->id;
  2758. }
  2759. }
  2760. // As the new template type is instanciated, the engine should
  2761. // generate new functions to substitute the ones with the template subtype.
  2762. for( n = 0; n < ot->methods.GetLength(); n++ )
  2763. {
  2764. int funcId = ot->methods[n];
  2765. asCScriptFunction *func = scriptFunctions[funcId];
  2766. if( GenerateNewTemplateFunction(templateType, ot, func, &func) )
  2767. {
  2768. // Release the old function, the new one already has its ref count set to 1
  2769. scriptFunctions[funcId]->Release();
  2770. ot->methods[n] = func->id;
  2771. }
  2772. }
  2773. // Increase ref counter for sub type if it is an object type
  2774. for( n = 0; n < ot->templateSubTypes.GetLength(); n++ )
  2775. if( ot->templateSubTypes[n].GetObjectType() )
  2776. ot->templateSubTypes[n].GetObjectType()->AddRef();
  2777. templateTypes.PushLast(ot);
  2778. // We need to store the object type somewhere for clean-up later
  2779. // TODO: Why do we need both templateTypes and templateInstanceTypes? It is possible to differ between template instance and template specialization by checking for the asOBJ_TEMPLATE flag
  2780. templateInstanceTypes.PushLast(ot);
  2781. return ot;
  2782. }
  2783. // interface
  2784. asILockableSharedBool *asCScriptEngine::GetWeakRefFlagOfScriptObject(void *obj, const asIObjectType *type) const
  2785. {
  2786. // Make sure it is not a null pointer
  2787. if( obj == 0 || type == 0 ) return 0;
  2788. const asCObjectType *objType = static_cast<const asCObjectType *>(type);
  2789. asILockableSharedBool *dest = 0;
  2790. if( objType->beh.getWeakRefFlag )
  2791. {
  2792. // Call the getweakrefflag behaviour
  2793. dest = reinterpret_cast<asILockableSharedBool*>(CallObjectMethodRetPtr(obj, objType->beh.getWeakRefFlag));
  2794. }
  2795. return dest;
  2796. }
  2797. // internal
  2798. asCDataType asCScriptEngine::DetermineTypeForTemplate(const asCDataType &orig, asCObjectType *tmpl, asCObjectType *ot)
  2799. {
  2800. asCDataType dt;
  2801. if( orig.GetObjectType() && (orig.GetObjectType()->flags & asOBJ_TEMPLATE_SUBTYPE) )
  2802. {
  2803. bool found = false;
  2804. for( asUINT n = 0; n < tmpl->templateSubTypes.GetLength(); n++ )
  2805. {
  2806. if( orig.GetObjectType() == tmpl->templateSubTypes[n].GetObjectType() )
  2807. {
  2808. found = true;
  2809. dt = ot->templateSubTypes[n];
  2810. if( orig.IsObjectHandle() && !ot->templateSubTypes[n].IsObjectHandle() )
  2811. {
  2812. dt.MakeHandle(true, true);
  2813. if( orig.IsHandleToConst() )
  2814. dt.MakeHandleToConst(true);
  2815. dt.MakeReference(orig.IsReference());
  2816. dt.MakeReadOnly(orig.IsReadOnly());
  2817. }
  2818. else
  2819. {
  2820. dt.MakeReference(orig.IsReference());
  2821. dt.MakeReadOnly(ot->templateSubTypes[n].IsReadOnly() || orig.IsReadOnly());
  2822. }
  2823. break;
  2824. }
  2825. }
  2826. asASSERT( found );
  2827. UNUSED_VAR( found );
  2828. }
  2829. else if( orig.GetObjectType() == tmpl )
  2830. {
  2831. if( orig.IsObjectHandle() )
  2832. dt = asCDataType::CreateObjectHandle(ot, false);
  2833. else
  2834. dt = asCDataType::CreateObject(ot, false);
  2835. dt.MakeReference(orig.IsReference());
  2836. dt.MakeReadOnly(orig.IsReadOnly());
  2837. }
  2838. else
  2839. dt = orig;
  2840. return dt;
  2841. }
  2842. // internal
  2843. asCScriptFunction *asCScriptEngine::GenerateTemplateFactoryStub(asCObjectType *templateType, asCObjectType *ot, int factoryId)
  2844. {
  2845. asCScriptFunction *factory = scriptFunctions[factoryId];
  2846. // By first instantiating the function as a dummy and then changing it to be a script function
  2847. // I avoid having it added to the garbage collector. As it is known that this object will stay
  2848. // alive until the template instance is no longer used there is no need to have the GC check
  2849. // this function all the time.
  2850. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_DUMMY);
  2851. if( func == 0 )
  2852. {
  2853. // Out of memory
  2854. return 0;
  2855. }
  2856. func->funcType = asFUNC_SCRIPT;
  2857. func->name = "factstub";
  2858. func->id = GetNextScriptFunctionId();
  2859. func->returnType = asCDataType::CreateObjectHandle(ot, false);
  2860. func->isShared = true;
  2861. // Skip the first parameter as this is the object type pointer that the stub will add
  2862. func->parameterTypes.SetLength(factory->parameterTypes.GetLength()-1);
  2863. func->inOutFlags.SetLength(factory->inOutFlags.GetLength()-1);
  2864. for( asUINT p = 1; p < factory->parameterTypes.GetLength(); p++ )
  2865. {
  2866. func->parameterTypes[p-1] = DetermineTypeForTemplate(factory->parameterTypes[p], templateType, ot);
  2867. func->inOutFlags[p-1] = factory->inOutFlags[p];
  2868. }
  2869. func->objVariablesOnHeap = 0;
  2870. SetScriptFunction(func);
  2871. // Generate the bytecode for the factory stub
  2872. asUINT bcLength = asBCTypeSize[asBCInfo[asBC_OBJTYPE].type] +
  2873. asBCTypeSize[asBCInfo[asBC_CALLSYS].type] +
  2874. asBCTypeSize[asBCInfo[asBC_RET].type];
  2875. if( ep.includeJitInstructions )
  2876. bcLength += asBCTypeSize[asBCInfo[asBC_JitEntry].type];
  2877. func->byteCode.SetLength(bcLength);
  2878. asDWORD *bc = func->byteCode.AddressOf();
  2879. if( ep.includeJitInstructions )
  2880. {
  2881. *(asBYTE*)bc = asBC_JitEntry;
  2882. *(asPWORD*)(bc+1) = 0;
  2883. bc += asBCTypeSize[asBCInfo[asBC_JitEntry].type];
  2884. }
  2885. *(asBYTE*)bc = asBC_OBJTYPE;
  2886. *(asPWORD*)(bc+1) = (asPWORD)ot;
  2887. bc += asBCTypeSize[asBCInfo[asBC_OBJTYPE].type];
  2888. *(asBYTE*)bc = asBC_CALLSYS;
  2889. *(asDWORD*)(bc+1) = factoryId;
  2890. bc += asBCTypeSize[asBCInfo[asBC_CALLSYS].type];
  2891. *(asBYTE*)bc = asBC_RET;
  2892. *(((asWORD*)bc)+1) = (asWORD)func->GetSpaceNeededForArguments();
  2893. func->AddReferences();
  2894. func->stackNeeded = AS_PTR_SIZE;
  2895. // Tell the virtual machine not to clean up the object on exception
  2896. func->dontCleanUpOnException = true;
  2897. func->JITCompile();
  2898. return func;
  2899. }
  2900. bool asCScriptEngine::GenerateNewTemplateFunction(asCObjectType *templateType, asCObjectType *ot, asCScriptFunction *func, asCScriptFunction **newFunc)
  2901. {
  2902. bool needNewFunc = false;
  2903. if( (func->returnType.GetObjectType() && (func->returnType.GetObjectType()->flags & asOBJ_TEMPLATE_SUBTYPE)) ||
  2904. func->returnType.GetObjectType() == templateType )
  2905. needNewFunc = true;
  2906. else
  2907. {
  2908. for( asUINT p = 0; p < func->parameterTypes.GetLength(); p++ )
  2909. {
  2910. if( (func->parameterTypes[p].GetObjectType() && (func->parameterTypes[p].GetObjectType()->flags & asOBJ_TEMPLATE_SUBTYPE)) ||
  2911. func->parameterTypes[p].GetObjectType() == templateType )
  2912. {
  2913. needNewFunc = true;
  2914. break;
  2915. }
  2916. }
  2917. }
  2918. if( !needNewFunc )
  2919. return false;
  2920. asCScriptFunction *func2 = asNEW(asCScriptFunction)(this, 0, func->funcType);
  2921. if( func2 == 0 )
  2922. {
  2923. // Out of memory
  2924. return false;
  2925. }
  2926. func2->name = func->name;
  2927. func2->id = GetNextScriptFunctionId();
  2928. func2->returnType = DetermineTypeForTemplate(func->returnType, templateType, ot);
  2929. func2->parameterTypes.SetLength(func->parameterTypes.GetLength());
  2930. for( asUINT p = 0; p < func->parameterTypes.GetLength(); p++ )
  2931. func2->parameterTypes[p] = DetermineTypeForTemplate(func->parameterTypes[p], templateType, ot);
  2932. // TODO: template: Must be careful when instanciating templates for garbage collected types
  2933. // If the template hasn't been registered with the behaviours, it shouldn't
  2934. // permit instanciation of garbage collected types that in turn may refer to
  2935. // this instance.
  2936. func2->inOutFlags = func->inOutFlags;
  2937. func2->isReadOnly = func->isReadOnly;
  2938. func2->objectType = ot;
  2939. func2->stackNeeded = func->stackNeeded;
  2940. func2->sysFuncIntf = asNEW(asSSystemFunctionInterface)(*func->sysFuncIntf);
  2941. SetScriptFunction(func2);
  2942. // Return the new function
  2943. *newFunc = func2;
  2944. return true;
  2945. }
  2946. void asCScriptEngine::CallObjectMethod(void *obj, int func) const
  2947. {
  2948. asCScriptFunction *s = scriptFunctions[func];
  2949. asASSERT( s != 0 );
  2950. CallObjectMethod(obj, s->sysFuncIntf, s);
  2951. }
  2952. void asCScriptEngine::CallObjectMethod(void *obj, asSSystemFunctionInterface *i, asCScriptFunction *s) const
  2953. {
  2954. #ifdef __GNUC__
  2955. if( i->callConv == ICC_GENERIC_METHOD )
  2956. {
  2957. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  2958. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  2959. f(&gen);
  2960. }
  2961. else if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  2962. {
  2963. // For virtual thiscalls we must call the method as a true class method
  2964. // so that the compiler will lookup the function address in the vftable
  2965. union
  2966. {
  2967. asSIMPLEMETHOD_t mthd;
  2968. struct
  2969. {
  2970. asFUNCTION_t func;
  2971. asPWORD baseOffset; // Same size as the pointer
  2972. } f;
  2973. } p;
  2974. p.f.func = (void (*)())(i->func);
  2975. p.f.baseOffset = asPWORD(i->baseOffset);
  2976. void (asCSimpleDummy::*f)() = p.mthd;
  2977. (((asCSimpleDummy*)obj)->*f)();
  2978. }
  2979. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  2980. {
  2981. void (*f)(void *) = (void (*)(void *))(i->func);
  2982. f(obj);
  2983. }
  2984. #else
  2985. #ifndef AS_NO_CLASS_METHODS
  2986. if( i->callConv == ICC_THISCALL )
  2987. {
  2988. union
  2989. {
  2990. asSIMPLEMETHOD_t mthd;
  2991. asFUNCTION_t func;
  2992. } p;
  2993. p.func = (void (*)())(i->func);
  2994. void (asCSimpleDummy::*f)() = p.mthd;
  2995. obj = (void*)(asPWORD(obj) + i->baseOffset);
  2996. (((asCSimpleDummy*)obj)->*f)();
  2997. }
  2998. else
  2999. #endif
  3000. if( i->callConv == ICC_GENERIC_METHOD )
  3001. {
  3002. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3003. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3004. f(&gen);
  3005. }
  3006. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3007. {
  3008. void (*f)(void *) = (void (*)(void *))(i->func);
  3009. f(obj);
  3010. }
  3011. #endif
  3012. }
  3013. bool asCScriptEngine::CallObjectMethodRetBool(void *obj, int func) const
  3014. {
  3015. asCScriptFunction *s = scriptFunctions[func];
  3016. asASSERT( s != 0 );
  3017. asSSystemFunctionInterface *i = s->sysFuncIntf;
  3018. #ifdef __GNUC__
  3019. if( i->callConv == ICC_GENERIC_METHOD )
  3020. {
  3021. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3022. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3023. f(&gen);
  3024. return *(bool*)gen.GetReturnPointer();
  3025. }
  3026. else if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  3027. {
  3028. // For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
  3029. union
  3030. {
  3031. asSIMPLEMETHOD_t mthd;
  3032. struct
  3033. {
  3034. asFUNCTION_t func;
  3035. asPWORD baseOffset;
  3036. } f;
  3037. } p;
  3038. p.f.func = (void (*)())(i->func);
  3039. p.f.baseOffset = asPWORD(i->baseOffset);
  3040. bool (asCSimpleDummy::*f)() = (bool (asCSimpleDummy::*)())(p.mthd);
  3041. return (((asCSimpleDummy*)obj)->*f)();
  3042. }
  3043. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3044. {
  3045. bool (*f)(void *) = (bool (*)(void *))(i->func);
  3046. return f(obj);
  3047. }
  3048. #else
  3049. #ifndef AS_NO_CLASS_METHODS
  3050. if( i->callConv == ICC_THISCALL )
  3051. {
  3052. union
  3053. {
  3054. asSIMPLEMETHOD_t mthd;
  3055. asFUNCTION_t func;
  3056. } p;
  3057. p.func = (void (*)())(i->func);
  3058. bool (asCSimpleDummy::*f)() = (bool (asCSimpleDummy::*)())p.mthd;
  3059. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3060. return (((asCSimpleDummy*)obj)->*f)();
  3061. }
  3062. else
  3063. #endif
  3064. if( i->callConv == ICC_GENERIC_METHOD )
  3065. {
  3066. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3067. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3068. f(&gen);
  3069. return *(bool*)gen.GetReturnPointer();
  3070. }
  3071. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3072. {
  3073. bool (*f)(void *) = (bool (*)(void *))(i->func);
  3074. return f(obj);
  3075. }
  3076. #endif
  3077. }
  3078. int asCScriptEngine::CallObjectMethodRetInt(void *obj, int func) const
  3079. {
  3080. asCScriptFunction *s = scriptFunctions[func];
  3081. asASSERT( s != 0 );
  3082. asSSystemFunctionInterface *i = s->sysFuncIntf;
  3083. #ifdef __GNUC__
  3084. if( i->callConv == ICC_GENERIC_METHOD )
  3085. {
  3086. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3087. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3088. f(&gen);
  3089. return *(int*)gen.GetReturnPointer();
  3090. }
  3091. else if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  3092. {
  3093. // For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
  3094. union
  3095. {
  3096. asSIMPLEMETHOD_t mthd;
  3097. struct
  3098. {
  3099. asFUNCTION_t func;
  3100. asPWORD baseOffset;
  3101. } f;
  3102. } p;
  3103. p.f.func = (void (*)())(i->func);
  3104. p.f.baseOffset = asPWORD(i->baseOffset);
  3105. int (asCSimpleDummy::*f)() = (int (asCSimpleDummy::*)())(p.mthd);
  3106. return (((asCSimpleDummy*)obj)->*f)();
  3107. }
  3108. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3109. {
  3110. int (*f)(void *) = (int (*)(void *))(i->func);
  3111. return f(obj);
  3112. }
  3113. #else
  3114. #ifndef AS_NO_CLASS_METHODS
  3115. if( i->callConv == ICC_THISCALL )
  3116. {
  3117. union
  3118. {
  3119. asSIMPLEMETHOD_t mthd;
  3120. asFUNCTION_t func;
  3121. } p;
  3122. p.func = (void (*)())(i->func);
  3123. int (asCSimpleDummy::*f)() = (int (asCSimpleDummy::*)())p.mthd;
  3124. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3125. return (((asCSimpleDummy*)obj)->*f)();
  3126. }
  3127. else
  3128. #endif
  3129. if( i->callConv == ICC_GENERIC_METHOD )
  3130. {
  3131. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3132. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3133. f(&gen);
  3134. return *(int*)gen.GetReturnPointer();
  3135. }
  3136. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3137. {
  3138. int (*f)(void *) = (int (*)(void *))(i->func);
  3139. return f(obj);
  3140. }
  3141. #endif
  3142. }
  3143. void *asCScriptEngine::CallObjectMethodRetPtr(void *obj, int func) const
  3144. {
  3145. asCScriptFunction *s = scriptFunctions[func];
  3146. asASSERT( s != 0 );
  3147. asSSystemFunctionInterface *i = s->sysFuncIntf;
  3148. #ifdef __GNUC__
  3149. if( i->callConv == ICC_GENERIC_METHOD )
  3150. {
  3151. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3152. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3153. f(&gen);
  3154. return *(void**)gen.GetReturnPointer();
  3155. }
  3156. else if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  3157. {
  3158. // For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
  3159. union
  3160. {
  3161. asSIMPLEMETHOD_t mthd;
  3162. struct
  3163. {
  3164. asFUNCTION_t func;
  3165. asPWORD baseOffset;
  3166. } f;
  3167. } p;
  3168. p.f.func = (void (*)())(i->func);
  3169. p.f.baseOffset = asPWORD(i->baseOffset);
  3170. void *(asCSimpleDummy::*f)() = (void *(asCSimpleDummy::*)())(p.mthd);
  3171. return (((asCSimpleDummy*)obj)->*f)();
  3172. }
  3173. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3174. {
  3175. void *(*f)(void *) = (void *(*)(void *))(i->func);
  3176. return f(obj);
  3177. }
  3178. #else
  3179. #ifndef AS_NO_CLASS_METHODS
  3180. if( i->callConv == ICC_THISCALL )
  3181. {
  3182. union
  3183. {
  3184. asSIMPLEMETHOD_t mthd;
  3185. asFUNCTION_t func;
  3186. } p;
  3187. p.func = (void (*)())(i->func);
  3188. void *(asCSimpleDummy::*f)() = (void *(asCSimpleDummy::*)())p.mthd;
  3189. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3190. return (((asCSimpleDummy*)obj)->*f)();
  3191. }
  3192. else
  3193. #endif
  3194. if( i->callConv == ICC_GENERIC_METHOD )
  3195. {
  3196. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3197. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3198. f(&gen);
  3199. return *(void **)gen.GetReturnPointer();
  3200. }
  3201. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3202. {
  3203. void *(*f)(void *) = (void *(*)(void *))(i->func);
  3204. return f(obj);
  3205. }
  3206. #endif
  3207. }
  3208. void *asCScriptEngine::CallGlobalFunctionRetPtr(int func) const
  3209. {
  3210. asCScriptFunction *s = scriptFunctions[func];
  3211. asASSERT( s != 0 );
  3212. return CallGlobalFunctionRetPtr(s->sysFuncIntf, s);
  3213. }
  3214. void *asCScriptEngine::CallGlobalFunctionRetPtr(int func, void *param1) const
  3215. {
  3216. asCScriptFunction *s = scriptFunctions[func];
  3217. asASSERT( s != 0 );
  3218. return CallGlobalFunctionRetPtr(s->sysFuncIntf, s, param1);
  3219. }
  3220. void *asCScriptEngine::CallGlobalFunctionRetPtr(asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3221. {
  3222. if( i->callConv == ICC_CDECL )
  3223. {
  3224. void *(*f)() = (void *(*)())(i->func);
  3225. return f();
  3226. }
  3227. else if( i->callConv == ICC_STDCALL )
  3228. {
  3229. typedef void *(STDCALL *func_t)();
  3230. func_t f = (func_t)(i->func);
  3231. return f();
  3232. }
  3233. else
  3234. {
  3235. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, 0, 0);
  3236. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3237. f(&gen);
  3238. return *(void**)gen.GetReturnPointer();
  3239. }
  3240. }
  3241. void *asCScriptEngine::CallGlobalFunctionRetPtr(asSSystemFunctionInterface *i, asCScriptFunction *s, void *param1) const
  3242. {
  3243. if( i->callConv == ICC_CDECL )
  3244. {
  3245. void *(*f)(void *) = (void *(*)(void *))(i->func);
  3246. return f(param1);
  3247. }
  3248. else if( i->callConv == ICC_STDCALL )
  3249. {
  3250. typedef void *(STDCALL *func_t)(void *);
  3251. func_t f = (func_t)(i->func);
  3252. return f(param1);
  3253. }
  3254. else
  3255. {
  3256. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, 0, (asDWORD*)&param1);
  3257. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3258. f(&gen);
  3259. return *(void**)gen.GetReturnPointer();
  3260. }
  3261. }
  3262. void asCScriptEngine::CallObjectMethod(void *obj, void *param, int func) const
  3263. {
  3264. asCScriptFunction *s = scriptFunctions[func];
  3265. asASSERT( s != 0 );
  3266. CallObjectMethod(obj, param, s->sysFuncIntf, s);
  3267. }
  3268. void asCScriptEngine::CallObjectMethod(void *obj, void *param, asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3269. {
  3270. #ifdef __GNUC__
  3271. if( i->callConv == ICC_CDECL_OBJLAST )
  3272. {
  3273. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3274. f(param, obj);
  3275. }
  3276. else if( i->callConv == ICC_GENERIC_METHOD )
  3277. {
  3278. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, (asDWORD*)&param);
  3279. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3280. f(&gen);
  3281. }
  3282. else if( i->callConv == ICC_VIRTUAL_THISCALL || i->callConv == ICC_THISCALL )
  3283. {
  3284. // For virtual thiscalls we must call the method as a true class method
  3285. // so that the compiler will lookup the function address in the vftable
  3286. union
  3287. {
  3288. asSIMPLEMETHOD_t mthd;
  3289. struct
  3290. {
  3291. asFUNCTION_t func;
  3292. asPWORD baseOffset; // Same size as the pointer
  3293. } f;
  3294. } p;
  3295. p.f.func = (void (*)())(i->func);
  3296. p.f.baseOffset = asPWORD(i->baseOffset);
  3297. void (asCSimpleDummy::*f)(void*) = (void (asCSimpleDummy::*)(void*))(p.mthd);
  3298. (((asCSimpleDummy*)obj)->*f)(param);
  3299. }
  3300. else /*if( i->callConv == ICC_CDECL_OBJFIRST */
  3301. {
  3302. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3303. f(obj, param);
  3304. }
  3305. #else
  3306. #ifndef AS_NO_CLASS_METHODS
  3307. if( i->callConv == ICC_THISCALL )
  3308. {
  3309. union
  3310. {
  3311. asSIMPLEMETHOD_t mthd;
  3312. asFUNCTION_t func;
  3313. } p;
  3314. p.func = (void (*)())(i->func);
  3315. void (asCSimpleDummy::*f)(void *) = (void (asCSimpleDummy::*)(void *))(p.mthd);
  3316. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3317. (((asCSimpleDummy*)obj)->*f)(param);
  3318. }
  3319. else
  3320. #endif
  3321. if( i->callConv == ICC_CDECL_OBJLAST )
  3322. {
  3323. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3324. f(param, obj);
  3325. }
  3326. else if( i->callConv == ICC_GENERIC_METHOD )
  3327. {
  3328. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, (asDWORD*)&param);
  3329. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3330. f(&gen);
  3331. }
  3332. else /*if( i->callConv == ICC_CDECL_OBJFIRST )*/
  3333. {
  3334. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3335. f(obj, param);
  3336. }
  3337. #endif
  3338. }
  3339. void asCScriptEngine::CallGlobalFunction(void *param1, void *param2, asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3340. {
  3341. if( i->callConv == ICC_CDECL )
  3342. {
  3343. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3344. f(param1, param2);
  3345. }
  3346. else if( i->callConv == ICC_STDCALL )
  3347. {
  3348. typedef void (STDCALL *func_t)(void *, void *);
  3349. func_t f = (func_t)(i->func);
  3350. f(param1, param2);
  3351. }
  3352. else
  3353. {
  3354. // We must guarantee the order of the arguments which is why we copy them to this
  3355. // array. Otherwise the compiler may put them anywhere it likes, or even keep them
  3356. // in the registers which causes problem.
  3357. void *params[2] = {param1, param2};
  3358. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, 0, (asDWORD*)&params);
  3359. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3360. f(&gen);
  3361. }
  3362. }
  3363. bool asCScriptEngine::CallGlobalFunctionRetBool(void *param1, void *param2, asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3364. {
  3365. if( i->callConv == ICC_CDECL )
  3366. {
  3367. bool (*f)(void *, void *) = (bool (*)(void *, void *))(i->func);
  3368. return f(param1, param2);
  3369. }
  3370. else if( i->callConv == ICC_STDCALL )
  3371. {
  3372. typedef bool (STDCALL *func_t)(void *, void *);
  3373. func_t f = (func_t)(i->func);
  3374. return f(param1, param2);
  3375. }
  3376. else
  3377. {
  3378. // TODO: When simulating a 64bit environment by defining AS_64BIT_PTR on a 32bit platform this code
  3379. // fails, because the stack given to asCGeneric is not prepared with two 64bit arguments.
  3380. // We must guarantee the order of the arguments which is why we copy them to this
  3381. // array. Otherwise the compiler may put them anywhere it likes, or even keep them
  3382. // in the registers which causes problem.
  3383. void *params[2] = {param1, param2};
  3384. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, 0, (asDWORD*)params);
  3385. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3386. f(&gen);
  3387. return *(bool*)gen.GetReturnPointer();
  3388. }
  3389. }
  3390. void *asCScriptEngine::CallAlloc(asCObjectType *type) const
  3391. {
  3392. // Allocate 4 bytes as the smallest size. Otherwise CallSystemFunction may try to
  3393. // copy a DWORD onto a smaller memory block, in case the object type is return in registers.
  3394. // Pad to the next even 4 bytes to avoid asBC_CPY writing outside of allocated buffer for registered POD types
  3395. asUINT size = type->size;
  3396. if( size & 0x3 )
  3397. size += 4 - (size & 0x3);
  3398. #if defined(AS_DEBUG)
  3399. return ((asALLOCFUNCDEBUG_t)(userAlloc))(size, __FILE__, __LINE__);
  3400. #else
  3401. return userAlloc(size);
  3402. #endif
  3403. }
  3404. void asCScriptEngine::CallFree(void *obj) const
  3405. {
  3406. userFree(obj);
  3407. }
  3408. // interface
  3409. int asCScriptEngine::NotifyGarbageCollectorOfNewObject(void *obj, asIObjectType *type)
  3410. {
  3411. return gc.AddScriptObjectToGC(obj, static_cast<asCObjectType*>(type));
  3412. }
  3413. // interface
  3414. int asCScriptEngine::GetObjectInGC(asUINT idx, asUINT *seqNbr, void **obj, asIObjectType **type)
  3415. {
  3416. return gc.GetObjectInGC(idx, seqNbr, obj, type);
  3417. }
  3418. // interface
  3419. int asCScriptEngine::GarbageCollect(asDWORD flags)
  3420. {
  3421. return gc.GarbageCollect(flags);
  3422. }
  3423. // interface
  3424. void asCScriptEngine::GetGCStatistics(asUINT *currentSize, asUINT *totalDestroyed, asUINT *totalDetected, asUINT *newObjects, asUINT *totalNewDestroyed) const
  3425. {
  3426. gc.GetStatistics(currentSize, totalDestroyed, totalDetected, newObjects, totalNewDestroyed);
  3427. }
  3428. // interface
  3429. void asCScriptEngine::GCEnumCallback(void *reference)
  3430. {
  3431. gc.GCEnumCallback(reference);
  3432. }
  3433. // TODO: multithread: The mapTypeIdToDataType must be protected with critical sections in all functions that access it
  3434. int asCScriptEngine::GetTypeIdFromDataType(const asCDataType &dtIn) const
  3435. {
  3436. if( dtIn.IsNullHandle() ) return 0;
  3437. // Register the base form
  3438. asCDataType dt(dtIn);
  3439. if( dt.GetObjectType() )
  3440. dt.MakeHandle(false);
  3441. // Find the existing type id
  3442. asSMapNode<int,asCDataType*> *cursor = 0;
  3443. mapTypeIdToDataType.MoveFirst(&cursor);
  3444. while( cursor )
  3445. {
  3446. if( mapTypeIdToDataType.GetValue(cursor)->IsEqualExceptRefAndConst(dt) )
  3447. {
  3448. int typeId = mapTypeIdToDataType.GetKey(cursor);
  3449. if( dtIn.GetObjectType() && !(dtIn.GetObjectType()->flags & asOBJ_ASHANDLE) )
  3450. {
  3451. // The the ASHANDLE types behave like handles, but are really
  3452. // value types so the typeId is never returned as a handle
  3453. if( dtIn.IsObjectHandle() )
  3454. typeId |= asTYPEID_OBJHANDLE;
  3455. if( dtIn.IsHandleToConst() )
  3456. typeId |= asTYPEID_HANDLETOCONST;
  3457. }
  3458. return typeId;
  3459. }
  3460. mapTypeIdToDataType.MoveNext(&cursor, cursor);
  3461. }
  3462. // The type id doesn't exist, create it
  3463. // Setup the basic type id
  3464. int typeId = typeIdSeqNbr++;
  3465. if( dt.GetObjectType() )
  3466. {
  3467. if( dt.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT ) typeId |= asTYPEID_SCRIPTOBJECT;
  3468. else if( dt.GetObjectType()->flags & asOBJ_TEMPLATE ) typeId |= asTYPEID_TEMPLATE;
  3469. else if( dt.GetObjectType()->flags & asOBJ_ENUM ) {} // TODO: Should we have a specific bit for this?
  3470. else typeId |= asTYPEID_APPOBJECT;
  3471. }
  3472. // Insert the basic object type
  3473. asCDataType *newDt = asNEW(asCDataType)(dt);
  3474. if( newDt == 0 )
  3475. {
  3476. // Out of memory
  3477. return 0;
  3478. }
  3479. newDt->MakeReference(false);
  3480. newDt->MakeReadOnly(false);
  3481. newDt->MakeHandle(false);
  3482. mapTypeIdToDataType.Insert(typeId, newDt);
  3483. // Call recursively to get the correct typeId
  3484. return GetTypeIdFromDataType(dtIn);
  3485. }
  3486. asCDataType asCScriptEngine::GetDataTypeFromTypeId(int typeId) const
  3487. {
  3488. int baseId = typeId & (asTYPEID_MASK_OBJECT | asTYPEID_MASK_SEQNBR);
  3489. asSMapNode<int,asCDataType*> *cursor = 0;
  3490. if( mapTypeIdToDataType.MoveTo(&cursor, baseId) )
  3491. {
  3492. asCDataType dt(*mapTypeIdToDataType.GetValue(cursor));
  3493. if( typeId & asTYPEID_OBJHANDLE )
  3494. dt.MakeHandle(true, true);
  3495. if( typeId & asTYPEID_HANDLETOCONST )
  3496. dt.MakeHandleToConst(true);
  3497. return dt;
  3498. }
  3499. return asCDataType();
  3500. }
  3501. asCObjectType *asCScriptEngine::GetObjectTypeFromTypeId(int typeId) const
  3502. {
  3503. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3504. return dt.GetObjectType();
  3505. }
  3506. void asCScriptEngine::RemoveFromTypeIdMap(asCObjectType *type)
  3507. {
  3508. asSMapNode<int,asCDataType*> *cursor = 0;
  3509. mapTypeIdToDataType.MoveFirst(&cursor);
  3510. while( cursor )
  3511. {
  3512. asCDataType *dt = mapTypeIdToDataType.GetValue(cursor);
  3513. asSMapNode<int,asCDataType*> *old = cursor;
  3514. mapTypeIdToDataType.MoveNext(&cursor, cursor);
  3515. if( dt->GetObjectType() == type )
  3516. {
  3517. asDELETE(dt,asCDataType);
  3518. mapTypeIdToDataType.Erase(old);
  3519. }
  3520. }
  3521. }
  3522. // interface
  3523. int asCScriptEngine::GetTypeIdByDecl(const char *decl) const
  3524. {
  3525. asCDataType dt;
  3526. // This cast is ok, because we are not changing anything in the engine
  3527. asCBuilder bld(const_cast<asCScriptEngine*>(this), 0);
  3528. int r = bld.ParseDataType(decl, &dt, defaultNamespace);
  3529. if( r < 0 )
  3530. return asINVALID_TYPE;
  3531. return GetTypeIdFromDataType(dt);
  3532. }
  3533. // interface
  3534. const char *asCScriptEngine::GetTypeDeclaration(int typeId, bool includeNamespace) const
  3535. {
  3536. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3537. asCString *tempString = &asCThreadManager::GetLocalData()->string;
  3538. *tempString = dt.Format(includeNamespace);
  3539. return tempString->AddressOf();
  3540. }
  3541. // TODO: interface: Deprecate. This function is not necessary now that all primitive types have fixed typeIds
  3542. int asCScriptEngine::GetSizeOfPrimitiveType(int typeId) const
  3543. {
  3544. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3545. if( !dt.IsPrimitive() ) return 0;
  3546. return dt.GetSizeInMemoryBytes();
  3547. }
  3548. #ifdef AS_DEPRECATED
  3549. // Deprecated since 2.27.0, 2013-07-18
  3550. void *asCScriptEngine::CreateScriptObject(int typeId)
  3551. {
  3552. // Make sure the type id is for an object type, and not a primitive or a handle
  3553. if( (typeId & (asTYPEID_MASK_OBJECT | asTYPEID_MASK_SEQNBR)) != typeId ) return 0;
  3554. if( (typeId & asTYPEID_MASK_OBJECT) == 0 ) return 0;
  3555. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3556. // Is the type id valid?
  3557. if( !dt.IsValid() ) return 0;
  3558. asCObjectType *objType = dt.GetObjectType();
  3559. return CreateScriptObject(objType);
  3560. }
  3561. #endif
  3562. // interface
  3563. void *asCScriptEngine::CreateScriptObject(const asIObjectType *type)
  3564. {
  3565. if( type == 0 ) return 0;
  3566. asCObjectType *objType = const_cast<asCObjectType*>(reinterpret_cast<const asCObjectType *>(type));
  3567. void *ptr = 0;
  3568. // Check that there is a default factory for ref types
  3569. if( objType->beh.factory == 0 && (objType->flags & asOBJ_REF) )
  3570. {
  3571. asCString str;
  3572. str.Format(TXT_FAILED_IN_FUNC_s_d, "CreateScriptObject", asNO_FUNCTION);
  3573. WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  3574. return 0;
  3575. }
  3576. // Construct the object
  3577. if( objType->flags & asOBJ_SCRIPT_OBJECT )
  3578. {
  3579. // Call the script class' default factory with a context
  3580. ptr = ScriptObjectFactory(objType, this);
  3581. }
  3582. else if( objType->flags & asOBJ_TEMPLATE )
  3583. {
  3584. // The registered factory that takes the object type is moved
  3585. // to the construct behaviour when the type is instanciated
  3586. ptr = CallGlobalFunctionRetPtr(objType->beh.construct, objType);
  3587. }
  3588. else if( objType->flags & asOBJ_REF )
  3589. {
  3590. // Call the default factory directly
  3591. ptr = CallGlobalFunctionRetPtr(objType->beh.factory);
  3592. }
  3593. else
  3594. {
  3595. // TODO: Shouldn't support allocating object like this, because the
  3596. // caller cannot be certain how the memory was allocated.
  3597. // Make sure there is a default constructor or that it is a POD type
  3598. if( objType->beh.construct == 0 && !(objType->flags & asOBJ_POD) )
  3599. {
  3600. asCString str;
  3601. str.Format(TXT_FAILED_IN_FUNC_s_d, "CreateScriptObject", asNO_FUNCTION);
  3602. WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  3603. return 0;
  3604. }
  3605. // Manually allocate the memory, then call the default constructor
  3606. ptr = CallAlloc(objType);
  3607. int funcIndex = objType->beh.construct;
  3608. if( funcIndex )
  3609. CallObjectMethod(ptr, funcIndex);
  3610. }
  3611. return ptr;
  3612. }
  3613. #ifdef AS_DEPRECATED
  3614. // Deprecated since 2.27.0, 2013-07-18
  3615. // interface
  3616. void *asCScriptEngine::CreateUninitializedScriptObject(int typeId)
  3617. {
  3618. // Make sure the type id is for an object type, and not a primitive or a handle.
  3619. // This function only works for script classes. Registered types cannot be created this way.
  3620. if( (typeId & (asTYPEID_MASK_OBJECT | asTYPEID_MASK_SEQNBR)) != typeId ) return 0;
  3621. if( (typeId & asTYPEID_MASK_OBJECT) == 0 ) return 0;
  3622. if( (typeId & asTYPEID_SCRIPTOBJECT) == 0 ) return 0;
  3623. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3624. // Is the type id valid?
  3625. if( !dt.IsValid() ) return 0;
  3626. asCObjectType *objType = dt.GetObjectType();
  3627. return CreateUninitializedScriptObject(objType);
  3628. }
  3629. #endif
  3630. // interface
  3631. void *asCScriptEngine::CreateUninitializedScriptObject(const asIObjectType *type)
  3632. {
  3633. // This function only works for script classes. Registered types cannot be created this way.
  3634. if( type == 0 || !(type->GetFlags() & asOBJ_SCRIPT_OBJECT) )
  3635. return 0;
  3636. asCObjectType *objType = const_cast<asCObjectType*>(reinterpret_cast<const asCObjectType*>(type));
  3637. // Construct the object, but do not call the actual constructor that initializes the members
  3638. // The initialization will be done by the application afterwards, e.g. through serialization.
  3639. asCScriptObject *obj = reinterpret_cast<asCScriptObject*>(CallAlloc(objType));
  3640. // Pre-initialize the memory so there are no invalid pointers
  3641. ScriptObject_ConstructUnitialized(objType, obj);
  3642. return obj;
  3643. }
  3644. #ifdef AS_DEPRECATED
  3645. // Deprecated since 2.27.0, 2013-07-18
  3646. void *asCScriptEngine::CreateScriptObjectCopy(void *origObj, int typeId)
  3647. {
  3648. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3649. if( !dt.IsValid() ) return 0;
  3650. asCObjectType *objType = dt.GetObjectType();
  3651. void *newObj = CreateScriptObject(objType);
  3652. if( newObj == 0 ) return 0;
  3653. AssignScriptObject(newObj, origObj, typeId);
  3654. return newObj;
  3655. }
  3656. #endif
  3657. // interface
  3658. void *asCScriptEngine::CreateScriptObjectCopy(void *origObj, const asIObjectType *type)
  3659. {
  3660. // TODO: Should use the copy constructor if available
  3661. void *newObj = CreateScriptObject(type);
  3662. if( newObj == 0 ) return 0;
  3663. AssignScriptObject(newObj, origObj, type);
  3664. return newObj;
  3665. }
  3666. // internal
  3667. void asCScriptEngine::ConstructScriptObjectCopy(void *mem, void *obj, asCObjectType *type)
  3668. {
  3669. // This function is only meant to be used for value types
  3670. asASSERT( type->flags & asOBJ_VALUE );
  3671. // TODO: runtime optimize: Should use the copy constructor when available
  3672. int funcIndex = type->beh.construct;
  3673. if( funcIndex )
  3674. CallObjectMethod(mem, funcIndex);
  3675. AssignScriptObject(mem, obj, type);
  3676. }
  3677. #ifdef AS_DEPRECATED
  3678. // Deprecated since 2.27.0, 2013-07-18
  3679. void asCScriptEngine::AssignScriptObject(void *dstObj, void *srcObj, int typeId)
  3680. {
  3681. // Make sure the type id is for an object type, and not a primitive or a handle
  3682. if( (typeId & (asTYPEID_MASK_OBJECT | asTYPEID_MASK_SEQNBR)) != typeId ) return;
  3683. if( (typeId & asTYPEID_MASK_OBJECT) == 0 ) return;
  3684. // Copy the contents from the original object, using the assignment operator
  3685. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3686. // Is the type id valid?
  3687. if( !dt.IsValid() ) return;
  3688. asCObjectType *objType = dt.GetObjectType();
  3689. AssignScriptObject(dstObj, srcObj, objType);
  3690. }
  3691. #endif
  3692. // interface
  3693. void asCScriptEngine::AssignScriptObject(void *dstObj, void *srcObj, const asIObjectType *type)
  3694. {
  3695. if( type == 0 ) return;
  3696. const asCObjectType *objType = reinterpret_cast<const asCObjectType*>(type);
  3697. // If value assign for ref types has been disabled, then don't do anything if the type is a ref type
  3698. if( ep.disallowValueAssignForRefType && (objType->flags & asOBJ_REF) && !(objType->flags & asOBJ_SCOPED) )
  3699. return;
  3700. // Must not copy if the opAssign is not available and the object is not a POD object
  3701. if( objType->beh.copy )
  3702. {
  3703. asCScriptFunction *func = scriptFunctions[objType->beh.copy];
  3704. if( func->funcType == asFUNC_SYSTEM )
  3705. CallObjectMethod(dstObj, srcObj, objType->beh.copy);
  3706. else
  3707. {
  3708. // Call the script class' opAssign method
  3709. asASSERT( objType->flags & asOBJ_SCRIPT_OBJECT );
  3710. reinterpret_cast<asCScriptObject*>(dstObj)->CopyFrom(reinterpret_cast<asCScriptObject*>(srcObj));
  3711. }
  3712. }
  3713. else if( objType->size && (objType->flags & asOBJ_POD) )
  3714. {
  3715. memcpy(dstObj, srcObj, objType->size);
  3716. }
  3717. }
  3718. #ifdef AS_DEPRECATED
  3719. // Deprecated since 2.27.0, 2013-07-18
  3720. void asCScriptEngine::AddRefScriptObject(void *obj, int typeId)
  3721. {
  3722. // Make sure it is not a null pointer
  3723. if( obj == 0 ) return;
  3724. // Make sure the type id is for an object type or a handle
  3725. if( (typeId & asTYPEID_MASK_OBJECT) == 0 ) return;
  3726. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3727. // Is the type id valid?
  3728. if( !dt.IsValid() ) return;
  3729. asCObjectType *objType = dt.GetObjectType();
  3730. if( objType->beh.addref )
  3731. {
  3732. // Call the addref behaviour
  3733. CallObjectMethod(obj, objType->beh.addref);
  3734. }
  3735. }
  3736. #endif
  3737. // interface
  3738. void asCScriptEngine::AddRefScriptObject(void *obj, const asIObjectType *type)
  3739. {
  3740. // Make sure it is not a null pointer
  3741. if( obj == 0 ) return;
  3742. const asCObjectType *objType = static_cast<const asCObjectType *>(type);
  3743. if( objType->beh.addref )
  3744. {
  3745. // Call the addref behaviour
  3746. CallObjectMethod(obj, objType->beh.addref);
  3747. }
  3748. }
  3749. #ifdef AS_DEPRECATED
  3750. // Deprecated since 2.27.0, 2013-07-18
  3751. void asCScriptEngine::ReleaseScriptObject(void *obj, int typeId)
  3752. {
  3753. // Make sure it is not a null pointer
  3754. if( obj == 0 ) return;
  3755. // Make sure the type id is for an object type or a handle
  3756. if( (typeId & asTYPEID_MASK_OBJECT) == 0 ) return;
  3757. asCDataType dt = GetDataTypeFromTypeId(typeId);
  3758. // Is the type id valid?
  3759. if( !dt.IsValid() ) return;
  3760. asCObjectType *objType = dt.GetObjectType();
  3761. ReleaseScriptObject(obj, objType);
  3762. }
  3763. #endif
  3764. // interface
  3765. void asCScriptEngine::ReleaseScriptObject(void *obj, const asIObjectType *type)
  3766. {
  3767. // Make sure it is not a null pointer
  3768. if( obj == 0 ) return;
  3769. const asCObjectType *objType = static_cast<const asCObjectType *>(type);
  3770. if( objType->flags & asOBJ_REF )
  3771. {
  3772. asASSERT( (objType->flags & asOBJ_NOCOUNT) || objType->beh.release );
  3773. if( objType->beh.release )
  3774. {
  3775. // Call the release behaviour
  3776. CallObjectMethod(obj, objType->beh.release);
  3777. }
  3778. }
  3779. else
  3780. {
  3781. // TODO: interface: shouldn't work on non reference types
  3782. // Call the destructor
  3783. if( objType->beh.destruct )
  3784. CallObjectMethod(obj, objType->beh.destruct);
  3785. // Then free the memory
  3786. CallFree(obj);
  3787. }
  3788. }
  3789. // interface
  3790. bool asCScriptEngine::IsHandleCompatibleWithObject(void *obj, int objTypeId, int handleTypeId) const
  3791. {
  3792. // if equal, then it is obvious they are compatible
  3793. if( objTypeId == handleTypeId )
  3794. return true;
  3795. // Get the actual data types from the type ids
  3796. asCDataType objDt = GetDataTypeFromTypeId(objTypeId);
  3797. asCDataType hdlDt = GetDataTypeFromTypeId(handleTypeId);
  3798. // A handle to const cannot be passed to a handle that is not referencing a const object
  3799. if( objDt.IsHandleToConst() && !hdlDt.IsHandleToConst() )
  3800. return false;
  3801. if( objDt.GetObjectType() == hdlDt.GetObjectType() )
  3802. {
  3803. // The object type is equal
  3804. return true;
  3805. }
  3806. else if( objDt.IsScriptObject() && obj )
  3807. {
  3808. // Get the true type from the object instance
  3809. asCObjectType *objType = ((asCScriptObject*)obj)->objType;
  3810. // Check if the object implements the interface, or derives from the base class
  3811. // This will also return true, if the requested handle type is an exact match for the object type
  3812. if( objType->Implements(hdlDt.GetObjectType()) ||
  3813. objType->DerivesFrom(hdlDt.GetObjectType()) )
  3814. return true;
  3815. }
  3816. return false;
  3817. }
  3818. // interface
  3819. int asCScriptEngine::BeginConfigGroup(const char *groupName)
  3820. {
  3821. // Make sure the group name doesn't already exist
  3822. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  3823. {
  3824. if( configGroups[n]->groupName == groupName )
  3825. return asNAME_TAKEN;
  3826. }
  3827. if( currentGroup != &defaultGroup )
  3828. return asNOT_SUPPORTED;
  3829. asCConfigGroup *group = asNEW(asCConfigGroup)();
  3830. if( group == 0 )
  3831. return asOUT_OF_MEMORY;
  3832. group->groupName = groupName;
  3833. configGroups.PushLast(group);
  3834. currentGroup = group;
  3835. return 0;
  3836. }
  3837. // interface
  3838. int asCScriptEngine::EndConfigGroup()
  3839. {
  3840. // Raise error if trying to end the default config
  3841. if( currentGroup == &defaultGroup )
  3842. return asERROR;
  3843. currentGroup = &defaultGroup;
  3844. return 0;
  3845. }
  3846. // interface
  3847. int asCScriptEngine::RemoveConfigGroup(const char *groupName)
  3848. {
  3849. // It is not allowed to remove a group that is still in use.
  3850. // It would be possible to change the code in such a way that
  3851. // the group could be removed even though it was still in use,
  3852. // but that would cause severe negative impact on runtime
  3853. // performance, since the VM would then have to be able handle
  3854. // situations where the types, functions, and global variables
  3855. // can be removed at any time.
  3856. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  3857. {
  3858. if( configGroups[n]->groupName == groupName )
  3859. {
  3860. asCConfigGroup *group = configGroups[n];
  3861. // Make sure the group isn't referenced by anyone
  3862. if( group->refCount > 0 )
  3863. return asCONFIG_GROUP_IS_IN_USE;
  3864. // Verify if any objects registered in this group is still alive
  3865. if( group->HasLiveObjects() )
  3866. return asCONFIG_GROUP_IS_IN_USE;
  3867. // Remove the group from the list
  3868. if( n == configGroups.GetLength() - 1 )
  3869. configGroups.PopLast();
  3870. else
  3871. configGroups[n] = configGroups.PopLast();
  3872. // Remove the configurations registered with this group
  3873. group->RemoveConfiguration(this);
  3874. asDELETE(group,asCConfigGroup);
  3875. }
  3876. }
  3877. return 0;
  3878. }
  3879. asCConfigGroup *asCScriptEngine::FindConfigGroupForFunction(int funcId) const
  3880. {
  3881. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  3882. {
  3883. // Check global functions
  3884. asUINT m;
  3885. for( m = 0; m < configGroups[n]->scriptFunctions.GetLength(); m++ )
  3886. {
  3887. if( configGroups[n]->scriptFunctions[m]->id == funcId )
  3888. return configGroups[n];
  3889. }
  3890. }
  3891. return 0;
  3892. }
  3893. asCConfigGroup *asCScriptEngine::FindConfigGroupForGlobalVar(int gvarId) const
  3894. {
  3895. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  3896. {
  3897. for( asUINT m = 0; m < configGroups[n]->globalProps.GetLength(); m++ )
  3898. {
  3899. if( int(configGroups[n]->globalProps[m]->id) == gvarId )
  3900. return configGroups[n];
  3901. }
  3902. }
  3903. return 0;
  3904. }
  3905. asCConfigGroup *asCScriptEngine::FindConfigGroupForObjectType(const asCObjectType *objType) const
  3906. {
  3907. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  3908. {
  3909. for( asUINT m = 0; m < configGroups[n]->objTypes.GetLength(); m++ )
  3910. {
  3911. if( configGroups[n]->objTypes[m] == objType )
  3912. return configGroups[n];
  3913. }
  3914. }
  3915. return 0;
  3916. }
  3917. asCConfigGroup *asCScriptEngine::FindConfigGroupForFuncDef(const asCScriptFunction *funcDef) const
  3918. {
  3919. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  3920. {
  3921. asCScriptFunction *f = const_cast<asCScriptFunction*>(funcDef);
  3922. if( configGroups[n]->funcDefs.Exists(f) )
  3923. return configGroups[n];
  3924. }
  3925. return 0;
  3926. }
  3927. // interface
  3928. asDWORD asCScriptEngine::SetDefaultAccessMask(asDWORD defaultMask)
  3929. {
  3930. asDWORD old = defaultAccessMask;
  3931. defaultAccessMask = defaultMask;
  3932. return old;
  3933. }
  3934. int asCScriptEngine::GetNextScriptFunctionId()
  3935. {
  3936. // This function only returns the next function id that
  3937. // should be used. It doesn't update the internal arrays.
  3938. if( freeScriptFunctionIds.GetLength() )
  3939. return freeScriptFunctionIds[freeScriptFunctionIds.GetLength()-1];
  3940. return (int)scriptFunctions.GetLength();
  3941. }
  3942. void asCScriptEngine::SetScriptFunction(asCScriptFunction *func)
  3943. {
  3944. // Update the internal arrays with the function id that is now used
  3945. if( freeScriptFunctionIds.GetLength() && freeScriptFunctionIds[freeScriptFunctionIds.GetLength()-1] == func->id )
  3946. freeScriptFunctionIds.PopLast();
  3947. if( asUINT(func->id) == scriptFunctions.GetLength() )
  3948. scriptFunctions.PushLast(func);
  3949. else
  3950. {
  3951. // The slot should be empty or already set with the function, which happens if an existing shared function is reused
  3952. asASSERT( scriptFunctions[func->id] == 0 || scriptFunctions[func->id] == func );
  3953. scriptFunctions[func->id] = func;
  3954. }
  3955. }
  3956. void asCScriptEngine::FreeScriptFunctionId(int id)
  3957. {
  3958. if( id < 0 ) return;
  3959. id &= ~FUNC_IMPORTED;
  3960. if( id >= (int)scriptFunctions.GetLength() ) return;
  3961. if( scriptFunctions[id] )
  3962. {
  3963. asCScriptFunction *func = scriptFunctions[id];
  3964. // Remove the function from the list of script functions
  3965. if( id == (int)scriptFunctions.GetLength() - 1 )
  3966. {
  3967. scriptFunctions.PopLast();
  3968. }
  3969. else
  3970. {
  3971. scriptFunctions[id] = 0;
  3972. freeScriptFunctionIds.PushLast(id);
  3973. }
  3974. // Is the function used as signature id?
  3975. if( func->signatureId == id )
  3976. {
  3977. // Remove the signature id
  3978. signatureIds.RemoveValue(func);
  3979. // Update all functions using the signature id
  3980. int newSigId = 0;
  3981. for( asUINT n = 0; n < scriptFunctions.GetLength(); n++ )
  3982. {
  3983. if( scriptFunctions[n] && scriptFunctions[n]->signatureId == id )
  3984. {
  3985. if( newSigId == 0 )
  3986. {
  3987. newSigId = scriptFunctions[n]->id;
  3988. signatureIds.PushLast(scriptFunctions[n]);
  3989. }
  3990. scriptFunctions[n]->signatureId = newSigId;
  3991. }
  3992. }
  3993. }
  3994. }
  3995. }
  3996. // interface
  3997. int asCScriptEngine::RegisterFuncdef(const char *decl)
  3998. {
  3999. if( decl == 0 ) return ConfigError(asINVALID_ARG, "RegisterFuncdef", decl, 0);
  4000. // Parse the function declaration
  4001. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_FUNCDEF);
  4002. if( func == 0 )
  4003. return ConfigError(asOUT_OF_MEMORY, "RegisterFuncdef", decl, 0);
  4004. asCBuilder bld(this, 0);
  4005. int r = bld.ParseFunctionDeclaration(0, decl, func, false, 0, 0, defaultNamespace);
  4006. if( r < 0 )
  4007. {
  4008. // Set as dummy function before deleting
  4009. func->funcType = asFUNC_DUMMY;
  4010. asDELETE(func,asCScriptFunction);
  4011. return ConfigError(asINVALID_DECLARATION, "RegisterFuncdef", decl, 0);
  4012. }
  4013. // Check name conflicts
  4014. r = bld.CheckNameConflict(func->name.AddressOf(), 0, 0, defaultNamespace);
  4015. if( r < 0 )
  4016. {
  4017. asDELETE(func,asCScriptFunction);
  4018. return ConfigError(asNAME_TAKEN, "RegisterFuncdef", decl, 0);
  4019. }
  4020. func->id = GetNextScriptFunctionId();
  4021. SetScriptFunction(func);
  4022. funcDefs.PushLast(func);
  4023. registeredFuncDefs.PushLast(func);
  4024. currentGroup->funcDefs.PushLast(func);
  4025. // If parameter type from other groups are used, add references
  4026. if( func->returnType.GetObjectType() )
  4027. {
  4028. asCConfigGroup *group = FindConfigGroupForObjectType(func->returnType.GetObjectType());
  4029. currentGroup->RefConfigGroup(group);
  4030. }
  4031. for( asUINT n = 0; n < func->parameterTypes.GetLength(); n++ )
  4032. {
  4033. if( func->parameterTypes[n].GetObjectType() )
  4034. {
  4035. asCConfigGroup *group = FindConfigGroupForObjectType(func->parameterTypes[n].GetObjectType());
  4036. currentGroup->RefConfigGroup(group);
  4037. }
  4038. }
  4039. // Return the function id as success
  4040. return func->id;
  4041. }
  4042. // interface
  4043. asUINT asCScriptEngine::GetFuncdefCount() const
  4044. {
  4045. return asUINT(registeredFuncDefs.GetLength());
  4046. }
  4047. // interface
  4048. asIScriptFunction *asCScriptEngine::GetFuncdefByIndex(asUINT index) const
  4049. {
  4050. if( index >= registeredFuncDefs.GetLength() )
  4051. return 0;
  4052. return registeredFuncDefs[index];
  4053. }
  4054. // interface
  4055. // TODO: typedef: Accept complex types for the typedefs
  4056. int asCScriptEngine::RegisterTypedef(const char *type, const char *decl)
  4057. {
  4058. if( type == 0 ) return ConfigError(asINVALID_NAME, "RegisterTypedef", type, decl);
  4059. // Verify if the name has been registered as a type already
  4060. asUINT n;
  4061. for( n = 0; n < objectTypes.GetLength(); n++ )
  4062. {
  4063. if( objectTypes[n] && objectTypes[n]->name == type && objectTypes[n]->nameSpace == defaultNamespace )
  4064. // Let the application recover from this error, for example if the same typedef is registered twice
  4065. return asALREADY_REGISTERED;
  4066. }
  4067. // Grab the data type
  4068. size_t tokenLen;
  4069. eTokenType token;
  4070. asCDataType dataType;
  4071. // Create the data type
  4072. token = tok.GetToken(decl, strlen(decl), &tokenLen);
  4073. switch(token)
  4074. {
  4075. case ttBool:
  4076. case ttInt:
  4077. case ttInt8:
  4078. case ttInt16:
  4079. case ttInt64:
  4080. case ttUInt:
  4081. case ttUInt8:
  4082. case ttUInt16:
  4083. case ttUInt64:
  4084. case ttFloat:
  4085. case ttDouble:
  4086. if( strlen(decl) != tokenLen )
  4087. {
  4088. return ConfigError(asINVALID_TYPE, "RegisterTypedef", type, decl);
  4089. }
  4090. break;
  4091. default:
  4092. return ConfigError(asINVALID_TYPE, "RegisterTypedef", type, decl);
  4093. }
  4094. dataType = asCDataType::CreatePrimitive(token, false);
  4095. // Make sure the name is not a reserved keyword
  4096. token = tok.GetToken(type, strlen(type), &tokenLen);
  4097. if( token != ttIdentifier || strlen(type) != tokenLen )
  4098. return ConfigError(asINVALID_NAME, "RegisterTypedef", type, decl);
  4099. asCBuilder bld(this, 0);
  4100. int r = bld.CheckNameConflict(type, 0, 0, defaultNamespace);
  4101. if( r < 0 )
  4102. return ConfigError(asNAME_TAKEN, "RegisterTypedef", type, decl);
  4103. // Don't have to check against members of object
  4104. // types as they are allowed to use the names
  4105. // Put the data type in the list
  4106. asCObjectType *object = asNEW(asCObjectType)(this);
  4107. if( object == 0 )
  4108. return ConfigError(asOUT_OF_MEMORY, "RegisterTypedef", type, decl);
  4109. object->flags = asOBJ_TYPEDEF;
  4110. object->size = dataType.GetSizeInMemoryBytes();
  4111. object->name = type;
  4112. object->nameSpace = defaultNamespace;
  4113. object->templateSubTypes.PushLast(dataType);
  4114. objectTypes.PushLast(object);
  4115. registeredTypeDefs.PushLast(object);
  4116. currentGroup->objTypes.PushLast(object);
  4117. return asSUCCESS;
  4118. }
  4119. // interface
  4120. asUINT asCScriptEngine::GetTypedefCount() const
  4121. {
  4122. return asUINT(registeredTypeDefs.GetLength());
  4123. }
  4124. // interface
  4125. const char *asCScriptEngine::GetTypedefByIndex(asUINT index, int *typeId, const char **nameSpace, const char **configGroup, asDWORD *accessMask) const
  4126. {
  4127. if( index >= registeredTypeDefs.GetLength() )
  4128. return 0;
  4129. if( typeId )
  4130. *typeId = GetTypeIdFromDataType(registeredTypeDefs[index]->templateSubTypes[0]);
  4131. if( configGroup )
  4132. {
  4133. asCConfigGroup *group = FindConfigGroupForObjectType(registeredTypeDefs[index]);
  4134. if( group )
  4135. *configGroup = group->groupName.AddressOf();
  4136. else
  4137. *configGroup = 0;
  4138. }
  4139. if( accessMask )
  4140. *accessMask = registeredTypeDefs[index]->accessMask;
  4141. if( nameSpace )
  4142. *nameSpace = registeredTypeDefs[index]->nameSpace->name.AddressOf();
  4143. return registeredTypeDefs[index]->name.AddressOf();
  4144. }
  4145. // interface
  4146. int asCScriptEngine::RegisterEnum(const char *name)
  4147. {
  4148. // Check the name
  4149. if( NULL == name )
  4150. return ConfigError(asINVALID_NAME, "RegisterEnum", name, 0);
  4151. // Verify if the name has been registered as a type already
  4152. asUINT n;
  4153. for( n = 0; n < objectTypes.GetLength(); n++ )
  4154. if( objectTypes[n] && objectTypes[n]->name == name && objectTypes[n]->nameSpace == defaultNamespace )
  4155. return asALREADY_REGISTERED;
  4156. // Use builder to parse the datatype
  4157. asCDataType dt;
  4158. asCBuilder bld(this, 0);
  4159. bool oldMsgCallback = msgCallback; msgCallback = false;
  4160. int r = bld.ParseDataType(name, &dt, defaultNamespace);
  4161. msgCallback = oldMsgCallback;
  4162. if( r >= 0 )
  4163. return ConfigError(asERROR, "RegisterEnum", name, 0);
  4164. // Make sure the name is not a reserved keyword
  4165. size_t tokenLen;
  4166. int token = tok.GetToken(name, strlen(name), &tokenLen);
  4167. if( token != ttIdentifier || strlen(name) != tokenLen )
  4168. return ConfigError(asINVALID_NAME, "RegisterEnum", name, 0);
  4169. r = bld.CheckNameConflict(name, 0, 0, defaultNamespace);
  4170. if( r < 0 )
  4171. return ConfigError(asNAME_TAKEN, "RegisterEnum", name, 0);
  4172. asCObjectType *st = asNEW(asCObjectType)(this);
  4173. if( st == 0 )
  4174. return ConfigError(asOUT_OF_MEMORY, "RegisterEnum", name, 0);
  4175. asCDataType dataType;
  4176. dataType.CreatePrimitive(ttInt, false);
  4177. st->flags = asOBJ_ENUM | asOBJ_SHARED;
  4178. st->size = 4;
  4179. st->name = name;
  4180. st->nameSpace = defaultNamespace;
  4181. objectTypes.PushLast(st);
  4182. registeredEnums.PushLast(st);
  4183. currentGroup->objTypes.PushLast(st);
  4184. return asSUCCESS;
  4185. }
  4186. // interface
  4187. int asCScriptEngine::RegisterEnumValue(const char *typeName, const char *valueName, int value)
  4188. {
  4189. // Verify that the correct config group is used
  4190. if( currentGroup->FindType(typeName) == 0 )
  4191. return ConfigError(asWRONG_CONFIG_GROUP, "RegisterEnumValue", typeName, valueName);
  4192. asCDataType dt;
  4193. int r;
  4194. asCBuilder bld(this, 0);
  4195. r = bld.ParseDataType(typeName, &dt, defaultNamespace);
  4196. if( r < 0 )
  4197. return ConfigError(r, "RegisterEnumValue", typeName, valueName);
  4198. // Store the enum value
  4199. asCObjectType *ot = dt.GetObjectType();
  4200. if( ot == 0 || !(ot->flags & asOBJ_ENUM) )
  4201. return ConfigError(asINVALID_TYPE, "RegisterEnumValue", typeName, valueName);
  4202. if( NULL == valueName )
  4203. return ConfigError(asINVALID_NAME, "RegisterEnumValue", typeName, valueName);
  4204. int tokenLen;
  4205. asETokenClass tokenClass = ParseToken(valueName, 0, &tokenLen);
  4206. if( tokenClass != asTC_IDENTIFIER || tokenLen != (int)strlen(valueName) )
  4207. return ConfigError(asINVALID_NAME, "RegisterEnumValue", typeName, valueName);
  4208. for( unsigned int n = 0; n < ot->enumValues.GetLength(); n++ )
  4209. {
  4210. if( ot->enumValues[n]->name == valueName )
  4211. return ConfigError(asALREADY_REGISTERED, "RegisterEnumValue", typeName, valueName);
  4212. }
  4213. asSEnumValue *e = asNEW(asSEnumValue);
  4214. if( e == 0 )
  4215. return ConfigError(asOUT_OF_MEMORY, "RegisterEnumValue", typeName, valueName);
  4216. e->name = valueName;
  4217. e->value = value;
  4218. ot->enumValues.PushLast(e);
  4219. return asSUCCESS;
  4220. }
  4221. // interface
  4222. asUINT asCScriptEngine::GetEnumCount() const
  4223. {
  4224. return asUINT(registeredEnums.GetLength());
  4225. }
  4226. // interface
  4227. const char *asCScriptEngine::GetEnumByIndex(asUINT index, int *enumTypeId, const char **nameSpace, const char **configGroup, asDWORD *accessMask) const
  4228. {
  4229. if( index >= registeredEnums.GetLength() )
  4230. return 0;
  4231. if( configGroup )
  4232. {
  4233. asCConfigGroup *group = FindConfigGroupForObjectType(registeredEnums[index]);
  4234. if( group )
  4235. *configGroup = group->groupName.AddressOf();
  4236. else
  4237. *configGroup = 0;
  4238. }
  4239. if( accessMask )
  4240. *accessMask = registeredEnums[index]->accessMask;
  4241. if( enumTypeId )
  4242. *enumTypeId = GetTypeIdFromDataType(asCDataType::CreateObject(registeredEnums[index], false));
  4243. if( nameSpace )
  4244. *nameSpace = registeredEnums[index]->nameSpace->name.AddressOf();
  4245. return registeredEnums[index]->name.AddressOf();
  4246. }
  4247. // interface
  4248. int asCScriptEngine::GetEnumValueCount(int enumTypeId) const
  4249. {
  4250. asCDataType dt = GetDataTypeFromTypeId(enumTypeId);
  4251. asCObjectType *t = dt.GetObjectType();
  4252. if( t == 0 || !(t->GetFlags() & asOBJ_ENUM) )
  4253. return asINVALID_TYPE;
  4254. return (int)t->enumValues.GetLength();
  4255. }
  4256. // interface
  4257. const char *asCScriptEngine::GetEnumValueByIndex(int enumTypeId, asUINT index, int *outValue) const
  4258. {
  4259. // TODO: This same function is implemented in as_module.cpp as well. Perhaps it should be moved to asCObjectType?
  4260. asCDataType dt = GetDataTypeFromTypeId(enumTypeId);
  4261. asCObjectType *t = dt.GetObjectType();
  4262. if( t == 0 || !(t->GetFlags() & asOBJ_ENUM) )
  4263. return 0;
  4264. if( index >= t->enumValues.GetLength() )
  4265. return 0;
  4266. if( outValue )
  4267. *outValue = t->enumValues[index]->value;
  4268. return t->enumValues[index]->name.AddressOf();
  4269. }
  4270. // interface
  4271. asUINT asCScriptEngine::GetObjectTypeCount() const
  4272. {
  4273. return asUINT(registeredObjTypes.GetLength());
  4274. }
  4275. // interface
  4276. asIObjectType *asCScriptEngine::GetObjectTypeByIndex(asUINT index) const
  4277. {
  4278. if( index >= registeredObjTypes.GetLength() )
  4279. return 0;
  4280. return registeredObjTypes[index];
  4281. }
  4282. // interface
  4283. asIObjectType *asCScriptEngine::GetObjectTypeByName(const char *name) const
  4284. {
  4285. for( asUINT n = 0; n < registeredObjTypes.GetLength(); n++ )
  4286. {
  4287. if( registeredObjTypes[n]->name == name &&
  4288. registeredObjTypes[n]->nameSpace == defaultNamespace )
  4289. return registeredObjTypes[n];
  4290. }
  4291. return 0;
  4292. }
  4293. // interface
  4294. asIObjectType *asCScriptEngine::GetObjectTypeById(int typeId) const
  4295. {
  4296. asCDataType dt = GetDataTypeFromTypeId(typeId);
  4297. // Is the type id valid?
  4298. if( !dt.IsValid() ) return 0;
  4299. // Enum types are not objects, so we shouldn't return an object type for them
  4300. if( dt.GetObjectType() && dt.GetObjectType()->GetFlags() & asOBJ_ENUM )
  4301. return 0;
  4302. return dt.GetObjectType();
  4303. }
  4304. // interface
  4305. asIScriptFunction *asCScriptEngine::GetFunctionById(int funcId) const
  4306. {
  4307. return GetScriptFunction(funcId);
  4308. }
  4309. // interface
  4310. asIScriptFunction *asCScriptEngine::GetFuncDefFromTypeId(int typeId) const
  4311. {
  4312. return GetDataTypeFromTypeId(typeId).GetFuncDef();
  4313. }
  4314. // internal
  4315. bool asCScriptEngine::IsTemplateType(const char *name) const
  4316. {
  4317. // TODO: optimize: Improve linear search
  4318. for( unsigned int n = 0; n < objectTypes.GetLength(); n++ )
  4319. {
  4320. if( objectTypes[n] && objectTypes[n]->name == name )
  4321. {
  4322. return objectTypes[n]->flags & asOBJ_TEMPLATE ? true : false;
  4323. }
  4324. }
  4325. return false;
  4326. }
  4327. // internal
  4328. int asCScriptEngine::AddConstantString(const char *str, size_t len)
  4329. {
  4330. // This is only called when build a script module, so it is
  4331. // known that only one thread can enter the function at a time.
  4332. asASSERT( isBuilding );
  4333. // The str may contain null chars, so we cannot use strlen, or strcmp, or strcpy
  4334. // Has the string been registered before?
  4335. asSMapNode<asCStringPointer, int> *cursor = 0;
  4336. if (stringToIdMap.MoveTo(&cursor, asCStringPointer(str, len)))
  4337. return cursor->value;
  4338. // No match was found, add the string
  4339. asCString *cstr = asNEW(asCString)(str, len);
  4340. if( cstr )
  4341. {
  4342. stringConstants.PushLast(cstr);
  4343. int index = (int)stringConstants.GetLength() - 1;
  4344. stringToIdMap.Insert(asCStringPointer(cstr), index);
  4345. // The VM currently doesn't handle string ids larger than 65535
  4346. asASSERT(stringConstants.GetLength() <= 65536);
  4347. return index;
  4348. }
  4349. return 0;
  4350. }
  4351. // internal
  4352. const asCString &asCScriptEngine::GetConstantString(int id)
  4353. {
  4354. return *stringConstants[id];
  4355. }
  4356. // internal
  4357. int asCScriptEngine::GetScriptSectionNameIndex(const char *name)
  4358. {
  4359. ACQUIREEXCLUSIVE(engineRWLock);
  4360. // TODO: These names are only released when the engine is freed. The assumption is that
  4361. // the same script section names will be reused instead of there always being new
  4362. // names. Is this assumption valid? Do we need to add reference counting?
  4363. // Store the script section names for future reference
  4364. for( asUINT n = 0; n < scriptSectionNames.GetLength(); n++ )
  4365. {
  4366. if( scriptSectionNames[n]->Compare(name) == 0 )
  4367. {
  4368. RELEASEEXCLUSIVE(engineRWLock);
  4369. return n;
  4370. }
  4371. }
  4372. asCString *str = asNEW(asCString)(name);
  4373. if( str )
  4374. scriptSectionNames.PushLast(str);
  4375. int r = int(scriptSectionNames.GetLength()-1);
  4376. RELEASEEXCLUSIVE(engineRWLock);
  4377. return r;
  4378. }
  4379. // interface
  4380. void asCScriptEngine::SetEngineUserDataCleanupCallback(asCLEANENGINEFUNC_t callback, asPWORD type)
  4381. {
  4382. ACQUIREEXCLUSIVE(engineRWLock);
  4383. for( asUINT n = 0; n < cleanEngineFuncs.GetLength(); n++ )
  4384. {
  4385. if( cleanEngineFuncs[n].type == type )
  4386. {
  4387. cleanEngineFuncs[n].cleanFunc = callback;
  4388. RELEASEEXCLUSIVE(engineRWLock);
  4389. return;
  4390. }
  4391. }
  4392. SEngineClean otc = {type, callback};
  4393. cleanEngineFuncs.PushLast(otc);
  4394. RELEASEEXCLUSIVE(engineRWLock);
  4395. }
  4396. // interface
  4397. void asCScriptEngine::SetModuleUserDataCleanupCallback(asCLEANMODULEFUNC_t callback)
  4398. {
  4399. cleanModuleFunc = callback;
  4400. }
  4401. // interface
  4402. void asCScriptEngine::SetContextUserDataCleanupCallback(asCLEANCONTEXTFUNC_t callback)
  4403. {
  4404. cleanContextFunc = callback;
  4405. }
  4406. // interface
  4407. void asCScriptEngine::SetFunctionUserDataCleanupCallback(asCLEANFUNCTIONFUNC_t callback)
  4408. {
  4409. cleanFunctionFunc = callback;
  4410. }
  4411. // interface
  4412. void asCScriptEngine::SetObjectTypeUserDataCleanupCallback(asCLEANOBJECTTYPEFUNC_t callback, asPWORD type)
  4413. {
  4414. ACQUIREEXCLUSIVE(engineRWLock);
  4415. for( asUINT n = 0; n < cleanObjectTypeFuncs.GetLength(); n++ )
  4416. {
  4417. if( cleanObjectTypeFuncs[n].type == type )
  4418. {
  4419. cleanObjectTypeFuncs[n].cleanFunc = callback;
  4420. RELEASEEXCLUSIVE(engineRWLock);
  4421. return;
  4422. }
  4423. }
  4424. SObjTypeClean otc = {type, callback};
  4425. cleanObjectTypeFuncs.PushLast(otc);
  4426. RELEASEEXCLUSIVE(engineRWLock);
  4427. }
  4428. END_AS_NAMESPACE