as_scriptengine.cpp 174 KB

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