as_scriptengine.cpp 146 KB

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