as_builder.cpp 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2018 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. // Modified by Lasse Oorni for Urho3D
  24. //
  25. // as_builder.cpp
  26. //
  27. // This is the class that manages the compilation of the scripts
  28. //
  29. #include "as_config.h"
  30. #include "as_builder.h"
  31. #include "as_parser.h"
  32. #include "as_compiler.h"
  33. #include "as_tokendef.h"
  34. #include "as_string_util.h"
  35. #include "as_outputbuffer.h"
  36. #include "as_texts.h"
  37. #include "as_scriptobject.h"
  38. #include "as_debug.h"
  39. BEGIN_AS_NAMESPACE
  40. #ifndef AS_NO_COMPILER
  41. // asCSymbolTable template specializations for sGlobalVariableDescription entries
  42. template<>
  43. void asCSymbolTable<sGlobalVariableDescription>::GetKey(const sGlobalVariableDescription *entry, asSNameSpaceNamePair &key) const
  44. {
  45. asSNameSpace *ns = entry->ns;
  46. asCString name = entry->name;
  47. key = asSNameSpaceNamePair(ns, name);
  48. }
  49. // Comparator for exact variable search
  50. class asCCompGlobVarType : public asIFilter
  51. {
  52. public:
  53. const asCDataType &m_type;
  54. asCCompGlobVarType(const asCDataType &type) : m_type(type) {}
  55. bool operator()(const void *p) const
  56. {
  57. const sGlobalVariableDescription* desc = reinterpret_cast<const sGlobalVariableDescription*>(p);
  58. return desc->datatype == m_type;
  59. }
  60. private:
  61. // The assignment operator is required for MSVC9, otherwise it will complain that it is not possible to auto generate the operator
  62. asCCompGlobVarType &operator=(const asCCompGlobVarType &) {return *this;}
  63. };
  64. #endif
  65. asCBuilder::asCBuilder(asCScriptEngine *_engine, asCModule *_module)
  66. {
  67. this->engine = _engine;
  68. this->module = _module;
  69. silent = false;
  70. }
  71. asCBuilder::~asCBuilder()
  72. {
  73. #ifndef AS_NO_COMPILER
  74. asUINT n;
  75. // Free all functions
  76. for( n = 0; n < functions.GetLength(); n++ )
  77. {
  78. if( functions[n] )
  79. {
  80. if( functions[n]->node )
  81. functions[n]->node->Destroy(engine);
  82. asDELETE(functions[n],sFunctionDescription);
  83. }
  84. functions[n] = 0;
  85. }
  86. // Free all global variables
  87. asCSymbolTable<sGlobalVariableDescription>::iterator it = globVariables.List();
  88. while( it )
  89. {
  90. if( (*it)->declaredAtNode )
  91. (*it)->declaredAtNode->Destroy(engine);
  92. if( (*it)->initializationNode )
  93. (*it)->initializationNode->Destroy(engine);
  94. asDELETE((*it),sGlobalVariableDescription);
  95. it++;
  96. }
  97. globVariables.Clear();
  98. // Free all the loaded files
  99. for( n = 0; n < scripts.GetLength(); n++ )
  100. {
  101. if( scripts[n] )
  102. asDELETE(scripts[n],asCScriptCode);
  103. scripts[n] = 0;
  104. }
  105. // Free all class declarations
  106. for( n = 0; n < classDeclarations.GetLength(); n++ )
  107. {
  108. if( classDeclarations[n] )
  109. {
  110. if( classDeclarations[n]->node )
  111. classDeclarations[n]->node->Destroy(engine);
  112. asDELETE(classDeclarations[n],sClassDeclaration);
  113. classDeclarations[n] = 0;
  114. }
  115. }
  116. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  117. {
  118. if( interfaceDeclarations[n] )
  119. {
  120. if( interfaceDeclarations[n]->node )
  121. interfaceDeclarations[n]->node->Destroy(engine);
  122. asDELETE(interfaceDeclarations[n],sClassDeclaration);
  123. interfaceDeclarations[n] = 0;
  124. }
  125. }
  126. for( n = 0; n < namedTypeDeclarations.GetLength(); n++ )
  127. {
  128. if( namedTypeDeclarations[n] )
  129. {
  130. if( namedTypeDeclarations[n]->node )
  131. namedTypeDeclarations[n]->node->Destroy(engine);
  132. asDELETE(namedTypeDeclarations[n],sClassDeclaration);
  133. namedTypeDeclarations[n] = 0;
  134. }
  135. }
  136. for( n = 0; n < funcDefs.GetLength(); n++ )
  137. {
  138. if( funcDefs[n] )
  139. {
  140. if( funcDefs[n]->node )
  141. funcDefs[n]->node->Destroy(engine);
  142. asDELETE(funcDefs[n],sFuncDef);
  143. funcDefs[n] = 0;
  144. }
  145. }
  146. for( n = 0; n < mixinClasses.GetLength(); n++ )
  147. {
  148. if( mixinClasses[n] )
  149. {
  150. if( mixinClasses[n]->node )
  151. mixinClasses[n]->node->Destroy(engine);
  152. asDELETE(mixinClasses[n],sMixinClass);
  153. mixinClasses[n] = 0;
  154. }
  155. }
  156. #endif // AS_NO_COMPILER
  157. }
  158. void asCBuilder::Reset()
  159. {
  160. numErrors = 0;
  161. numWarnings = 0;
  162. engine->preMessage.isSet = false;
  163. #ifndef AS_NO_COMPILER
  164. // Clear the cache of known types
  165. hasCachedKnownTypes = false;
  166. knownTypes.EraseAll();
  167. #endif
  168. }
  169. #ifndef AS_NO_COMPILER
  170. int asCBuilder::AddCode(const char *name, const char *code, int codeLength, int lineOffset, int sectionIdx, bool makeCopy)
  171. {
  172. asCScriptCode *script = asNEW(asCScriptCode);
  173. if( script == 0 )
  174. return asOUT_OF_MEMORY;
  175. int r = script->SetCode(name, code, codeLength, makeCopy);
  176. if( r < 0 )
  177. {
  178. asDELETE(script, asCScriptCode);
  179. return r;
  180. }
  181. script->lineOffset = lineOffset;
  182. script->idx = sectionIdx;
  183. scripts.PushLast(script);
  184. return 0;
  185. }
  186. void asCBuilder::EvaluateTemplateInstances(asUINT startIdx, bool keepSilent)
  187. {
  188. // Backup the original message stream
  189. bool msgCallback = engine->msgCallback;
  190. asSSystemFunctionInterface msgCallbackFunc = engine->msgCallbackFunc;
  191. void *msgCallbackObj = engine->msgCallbackObj;
  192. // Set the new temporary message stream
  193. asCOutputBuffer outBuffer;
  194. if( keepSilent )
  195. engine->SetMessageCallback(asMETHOD(asCOutputBuffer, Callback), &outBuffer, asCALL_THISCALL);
  196. // Evaluate each of the template instances that have been created since the start of the build
  197. // TODO: This is not exactly correct, since another thread may have created template instances in parallel
  198. for( asUINT n = startIdx; n < engine->templateInstanceTypes.GetLength(); n++ )
  199. {
  200. bool dontGarbageCollect = false;
  201. asCObjectType *tmpl = engine->templateInstanceTypes[n];
  202. asCScriptFunction *callback = engine->scriptFunctions[tmpl->beh.templateCallback];
  203. if( callback && !engine->CallGlobalFunctionRetBool(tmpl, &dontGarbageCollect, callback->sysFuncIntf, callback) )
  204. {
  205. asCString sub = tmpl->templateSubTypes[0].Format(engine->nameSpaces[0]);
  206. for( asUINT m = 1; m < tmpl->templateSubTypes.GetLength(); m++ )
  207. {
  208. sub += ",";
  209. sub += tmpl->templateSubTypes[m].Format(engine->nameSpaces[0]);
  210. }
  211. asCString str;
  212. str.Format(TXT_INSTANCING_INVLD_TMPL_TYPE_s_s, tmpl->name.AddressOf(), sub.AddressOf());
  213. WriteError(tmpl->scriptSectionIdx >= 0 ? engine->scriptSectionNames[tmpl->scriptSectionIdx]->AddressOf() : "", str, tmpl->declaredAt&0xFFFFF, (tmpl->declaredAt>>20)&0xFFF);
  214. }
  215. else
  216. {
  217. // If the callback said this template instance won't be garbage collected then remove the flag
  218. if( dontGarbageCollect )
  219. tmpl->flags &= ~asOBJ_GC;
  220. }
  221. }
  222. // Restore message callback
  223. if( keepSilent )
  224. {
  225. engine->msgCallback = msgCallback;
  226. engine->msgCallbackFunc = msgCallbackFunc;
  227. engine->msgCallbackObj = msgCallbackObj;
  228. }
  229. }
  230. int asCBuilder::Build()
  231. {
  232. Reset();
  233. // The template callbacks must only be called after the subtypes have a known structure,
  234. // otherwise the callback may think it is not possible to create the template instance,
  235. // even though it is.
  236. // TODO: This flag shouldn't be set globally in the engine, as it would mean that another
  237. // thread requesting a template instance in parallel to the compilation wouldn't
  238. // evaluate the template instance.
  239. engine->deferValidationOfTemplateTypes = true;
  240. asUINT numTempl = (asUINT)engine->templateInstanceTypes.GetLength();
  241. ParseScripts();
  242. // Compile the types first
  243. CompileInterfaces();
  244. CompileClasses(numTempl);
  245. // Evaluate the template instances one last time, this time with error messages, as we know
  246. // all classes have been fully built and it is known which ones will need garbage collection.
  247. EvaluateTemplateInstances(numTempl, false);
  248. engine->deferValidationOfTemplateTypes = false;
  249. // Then the global variables. Here the variables declared with auto
  250. // will be resolved, so they can be accessed properly in the functions
  251. CompileGlobalVariables();
  252. // Finally the global functions and class methods
  253. CompileFunctions();
  254. // TODO: Attempt to reorder the initialization of global variables so that
  255. // they do not access other uninitialized global variables out-of-order
  256. // The builder needs to check for each of the global variable, what functions
  257. // that are accessed, and what global variables are access by these functions.
  258. if( numWarnings > 0 && engine->ep.compilerWarnings == 2 )
  259. WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
  260. if( numErrors > 0 )
  261. return asERROR;
  262. // Make sure something was compiled, otherwise return an error
  263. if( module->IsEmpty() )
  264. {
  265. WriteError(TXT_NOTHING_WAS_BUILT, 0, 0);
  266. return asERROR;
  267. }
  268. return asSUCCESS;
  269. }
  270. int asCBuilder::CompileGlobalVar(const char *sectionName, const char *code, int lineOffset)
  271. {
  272. Reset();
  273. // Add the string to the script code
  274. asCScriptCode *script = asNEW(asCScriptCode);
  275. if( script == 0 )
  276. return asOUT_OF_MEMORY;
  277. script->SetCode(sectionName, code, true);
  278. script->lineOffset = lineOffset;
  279. script->idx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
  280. scripts.PushLast(script);
  281. // Parse the string
  282. asCParser parser(this);
  283. if( parser.ParseScript(scripts[0]) < 0 )
  284. return asERROR;
  285. asCScriptNode *node = parser.GetScriptNode();
  286. // Make sure there is nothing else than the global variable in the script code
  287. if( node == 0 ||
  288. node->firstChild == 0 ||
  289. node->firstChild != node->lastChild ||
  290. node->firstChild->nodeType != snDeclaration )
  291. {
  292. WriteError(TXT_ONLY_ONE_VARIABLE_ALLOWED, script, 0);
  293. return asERROR;
  294. }
  295. node = node->firstChild;
  296. node->DisconnectParent();
  297. RegisterGlobalVar(node, script, module->defaultNamespace);
  298. CompileGlobalVariables();
  299. // It is possible that the global variable initialization included anonymous functions that must be compiled too
  300. for( asUINT n = 0; n < functions.GetLength(); n++ )
  301. {
  302. asCCompiler compiler(engine);
  303. asCScriptFunction *func = engine->scriptFunctions[functions[n]->funcId];
  304. int r = compiler.CompileFunction(this, functions[n]->script, func->parameterNames, functions[n]->node, func, 0);
  305. if( r < 0 )
  306. break;
  307. }
  308. if( numWarnings > 0 && engine->ep.compilerWarnings == 2 )
  309. WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
  310. // None of the functions should be added to the module if any error occurred,
  311. // or it was requested that the functions wouldn't be added to the scope
  312. if( numErrors > 0 )
  313. {
  314. for( asUINT n = 0; n < functions.GetLength(); n++ )
  315. {
  316. asCScriptFunction *func = engine->scriptFunctions[functions[n]->funcId];
  317. if( module->globalFunctions.GetIndex(func) >= 0 )
  318. {
  319. module->globalFunctions.Erase(module->globalFunctions.GetIndex(func));
  320. module->scriptFunctions.RemoveValue(func);
  321. func->ReleaseInternal();
  322. }
  323. }
  324. }
  325. if( numErrors > 0 )
  326. {
  327. // Remove the variable from the module, if it was registered
  328. if( globVariables.GetSize() > 0 )
  329. module->RemoveGlobalVar(module->GetGlobalVarCount()-1);
  330. return asERROR;
  331. }
  332. return 0;
  333. }
  334. #endif
  335. int asCBuilder::ValidateDefaultArgs(asCScriptCode *script, asCScriptNode *node, asCScriptFunction *func)
  336. {
  337. int firstArgWithDefaultValue = -1;
  338. for( asUINT n = 0; n < func->defaultArgs.GetLength(); n++ )
  339. {
  340. if( func->defaultArgs[n] )
  341. firstArgWithDefaultValue = n;
  342. else if( firstArgWithDefaultValue >= 0 )
  343. {
  344. asCString str;
  345. str.Format(TXT_DEF_ARG_MISSING_IN_FUNC_s, func->GetDeclaration());
  346. WriteError(str, script, node);
  347. return asINVALID_DECLARATION;
  348. }
  349. }
  350. return 0;
  351. }
  352. #ifndef AS_NO_COMPILER
  353. // This function will verify if the newly created function will conflict another overload due to having
  354. // identical function arguments that are not default args, e.g: foo(int) and foo(int, int=0)
  355. int asCBuilder::CheckForConflictsDueToDefaultArgs(asCScriptCode *script, asCScriptNode *node, asCScriptFunction *func, asCObjectType *objType)
  356. {
  357. // TODO: Implement for global functions too
  358. if( func->objectType == 0 || objType == 0 ) return 0;
  359. asCArray<int> funcs;
  360. GetObjectMethodDescriptions(func->name.AddressOf(), objType, funcs, false);
  361. for( asUINT n = 0; n < funcs.GetLength(); n++ )
  362. {
  363. asCScriptFunction *func2 = engine->scriptFunctions[funcs[n]];
  364. if( func == func2 )
  365. continue;
  366. if( func->IsReadOnly() != func2->IsReadOnly() )
  367. continue;
  368. bool match = true;
  369. asUINT p = 0;
  370. for( ; p < func->parameterTypes.GetLength() && p < func2->parameterTypes.GetLength(); p++ )
  371. {
  372. // Only verify until the first argument with default args
  373. if( (func->defaultArgs.GetLength() > p && func->defaultArgs[p]) ||
  374. (func2->defaultArgs.GetLength() > p && func2->defaultArgs[p]) )
  375. break;
  376. if( func->parameterTypes[p] != func2->parameterTypes[p] ||
  377. func->inOutFlags[p] != func2->inOutFlags[p] )
  378. {
  379. match = false;
  380. break;
  381. }
  382. }
  383. if( match )
  384. {
  385. if( !((p >= func->parameterTypes.GetLength() && p < func2->defaultArgs.GetLength() && func2->defaultArgs[p]) ||
  386. (p >= func2->parameterTypes.GetLength() && p < func->defaultArgs.GetLength() && func->defaultArgs[p])) )
  387. {
  388. // The argument lists match for the full length of the shorter, but the next
  389. // argument on the longer does not have a default arg so there is no conflict
  390. match = false;
  391. }
  392. }
  393. if( match )
  394. {
  395. WriteWarning(TXT_OVERLOAD_CONFLICTS_DUE_TO_DEFAULT_ARGS, script, node);
  396. WriteInfo(func->GetDeclaration(), script, node);
  397. WriteInfo(func2->GetDeclaration(), script, node);
  398. break;
  399. }
  400. }
  401. return 0;
  402. }
  403. int asCBuilder::CompileFunction(const char *sectionName, const char *code, int lineOffset, asDWORD compileFlags, asCScriptFunction **outFunc)
  404. {
  405. asASSERT(outFunc != 0);
  406. Reset();
  407. // Add the string to the script code
  408. asCScriptCode *script = asNEW(asCScriptCode);
  409. if( script == 0 )
  410. return asOUT_OF_MEMORY;
  411. script->SetCode(sectionName, code, true);
  412. script->lineOffset = lineOffset;
  413. script->idx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
  414. scripts.PushLast(script);
  415. // Parse the string
  416. asCParser parser(this);
  417. if( parser.ParseScript(scripts[0]) < 0 )
  418. return asERROR;
  419. asCScriptNode *node = parser.GetScriptNode();
  420. // Make sure there is nothing else than the function in the script code
  421. if( node == 0 ||
  422. node->firstChild == 0 ||
  423. node->firstChild != node->lastChild ||
  424. node->firstChild->nodeType != snFunction )
  425. {
  426. WriteError(TXT_ONLY_ONE_FUNCTION_ALLOWED, script, 0);
  427. return asERROR;
  428. }
  429. // Find the function node
  430. node = node->firstChild;
  431. // Create the function
  432. asSFunctionTraits funcTraits;
  433. asCScriptFunction *func = asNEW(asCScriptFunction)(engine, compileFlags & asCOMP_ADD_TO_MODULE ? module : 0, asFUNC_SCRIPT);
  434. if( func == 0 )
  435. return asOUT_OF_MEMORY;
  436. GetParsedFunctionDetails(node, scripts[0], 0, func->name, func->returnType, func->parameterNames, func->parameterTypes, func->inOutFlags, func->defaultArgs, funcTraits, module->defaultNamespace);
  437. func->id = engine->GetNextScriptFunctionId();
  438. func->scriptData->scriptSectionIdx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
  439. int row, col;
  440. scripts[0]->ConvertPosToRowCol(node->tokenPos, &row, &col);
  441. func->scriptData->declaredAt = (row & 0xFFFFF)|((col & 0xFFF)<<20);
  442. func->nameSpace = module->defaultNamespace;
  443. // Make sure the default args are declared correctly
  444. int r = ValidateDefaultArgs(script, node, func);
  445. if( r < 0 )
  446. {
  447. func->ReleaseInternal();
  448. return asERROR;
  449. }
  450. // Tell the engine that the function exists already so the compiler can access it
  451. if( compileFlags & asCOMP_ADD_TO_MODULE )
  452. {
  453. r = CheckNameConflict(func->name.AddressOf(), node, scripts[0], module->defaultNamespace);
  454. if( r < 0 )
  455. {
  456. func->ReleaseInternal();
  457. return asERROR;
  458. }
  459. module->globalFunctions.Put(func);
  460. module->AddScriptFunction(func);
  461. }
  462. else
  463. engine->AddScriptFunction(func);
  464. // Fill in the function info for the builder too
  465. node->DisconnectParent();
  466. sFunctionDescription *funcDesc = asNEW(sFunctionDescription);
  467. if( funcDesc == 0 )
  468. {
  469. func->ReleaseInternal();
  470. return asOUT_OF_MEMORY;
  471. }
  472. functions.PushLast(funcDesc);
  473. funcDesc->script = scripts[0];
  474. funcDesc->node = node;
  475. funcDesc->name = func->name;
  476. funcDesc->funcId = func->id;
  477. funcDesc->paramNames = func->parameterNames;
  478. funcDesc->isExistingShared = false;
  479. // This must be done in a loop, as it is possible that additional functions get declared as lambda's in the code
  480. for( asUINT n = 0; n < functions.GetLength(); n++ )
  481. {
  482. asCCompiler compiler(engine);
  483. asCScriptFunction *f = engine->scriptFunctions[functions[n]->funcId];
  484. r = compiler.CompileFunction(this, functions[n]->script, f->parameterNames, functions[n]->node, f, 0);
  485. if( r < 0 )
  486. break;
  487. }
  488. if( numWarnings > 0 && engine->ep.compilerWarnings == 2 )
  489. WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
  490. // None of the functions should be added to the module if any error occurred,
  491. // or it was requested that the functions wouldn't be added to the scope
  492. if( !(compileFlags & asCOMP_ADD_TO_MODULE) || numErrors > 0 )
  493. {
  494. for( asUINT n = 0; n < functions.GetLength(); n++ )
  495. {
  496. asCScriptFunction *f = engine->scriptFunctions[functions[n]->funcId];
  497. if( module->globalFunctions.GetIndex(f) >= 0 )
  498. {
  499. module->globalFunctions.Erase(module->globalFunctions.GetIndex(f));
  500. module->scriptFunctions.RemoveValue(f);
  501. f->ReleaseInternal();
  502. }
  503. }
  504. }
  505. if( numErrors > 0 )
  506. {
  507. // Release the function pointer that would otherwise be returned if no errors occured
  508. func->ReleaseInternal();
  509. return asERROR;
  510. }
  511. // Return the function
  512. *outFunc = func;
  513. return asSUCCESS;
  514. }
  515. void asCBuilder::ParseScripts()
  516. {
  517. TimeIt("asCBuilder::ParseScripts");
  518. asCArray<asCParser*> parsers((int)scripts.GetLength());
  519. // Parse all the files as if they were one
  520. asUINT n = 0;
  521. for( n = 0; n < scripts.GetLength(); n++ )
  522. {
  523. asCParser *parser = asNEW(asCParser)(this);
  524. if( parser != 0 )
  525. {
  526. parsers.PushLast(parser);
  527. // Parse the script file
  528. parser->ParseScript(scripts[n]);
  529. }
  530. }
  531. if (numErrors == 0)
  532. {
  533. // Find all type declarations
  534. for (n = 0; n < scripts.GetLength(); n++)
  535. {
  536. asCScriptNode *node = parsers[n]->GetScriptNode();
  537. RegisterTypesFromScript(node, scripts[n], engine->nameSpaces[0]);
  538. }
  539. // Before moving forward the builder must establish the relationship between types
  540. // so that a derived type can see the child types of the parent type.
  541. DetermineTypeRelations();
  542. // Complete function definitions (defining returntype and parameters)
  543. for( n = 0; n < funcDefs.GetLength(); n++ )
  544. CompleteFuncDef(funcDefs[n]);
  545. // Register script methods found in the interfaces
  546. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  547. {
  548. sClassDeclaration *decl = interfaceDeclarations[n];
  549. asCScriptNode *node = decl->node->firstChild->next;
  550. // Skip list of inherited interfaces
  551. while( node && node->nodeType == snIdentifier )
  552. node = node->next;
  553. while( node )
  554. {
  555. asCScriptNode *next = node->next;
  556. if( node->nodeType == snFunction )
  557. {
  558. node->DisconnectParent();
  559. RegisterScriptFunctionFromNode(node, decl->script, CastToObjectType(decl->typeInfo), true, false, 0, decl->isExistingShared);
  560. }
  561. else if( node->nodeType == snVirtualProperty )
  562. {
  563. node->DisconnectParent();
  564. RegisterVirtualProperty(node, decl->script, CastToObjectType(decl->typeInfo), true, false, 0, decl->isExistingShared);
  565. }
  566. node = next;
  567. }
  568. }
  569. // Register script methods found in the classes
  570. for( n = 0; n < classDeclarations.GetLength(); n++ )
  571. {
  572. sClassDeclaration *decl = classDeclarations[n];
  573. asCScriptNode *node = decl->node->firstChild->next;
  574. // Skip list of classes and interfaces
  575. while( node && node->nodeType == snIdentifier )
  576. node = node->next;
  577. while( node )
  578. {
  579. asCScriptNode *next = node->next;
  580. if( node->nodeType == snFunction )
  581. {
  582. node->DisconnectParent();
  583. RegisterScriptFunctionFromNode(node, decl->script, CastToObjectType(decl->typeInfo), false, false, 0, decl->isExistingShared);
  584. }
  585. else if( node->nodeType == snVirtualProperty )
  586. {
  587. node->DisconnectParent();
  588. RegisterVirtualProperty(node, decl->script, CastToObjectType(decl->typeInfo), false, false, 0, decl->isExistingShared);
  589. }
  590. node = next;
  591. }
  592. // Make sure the default factory & constructor exists for classes
  593. asCObjectType *ot = CastToObjectType(decl->typeInfo);
  594. if( ot->beh.construct == engine->scriptTypeBehaviours.beh.construct )
  595. {
  596. if( ot->beh.constructors.GetLength() == 1 || engine->ep.alwaysImplDefaultConstruct )
  597. {
  598. AddDefaultConstructor(ot, decl->script);
  599. }
  600. else
  601. {
  602. // As the class has another constructor we shouldn't provide the default constructor
  603. if( ot->beh.construct )
  604. {
  605. engine->scriptFunctions[ot->beh.construct]->ReleaseInternal();
  606. ot->beh.construct = 0;
  607. ot->beh.constructors.RemoveIndex(0);
  608. }
  609. if( ot->beh.factory )
  610. {
  611. engine->scriptFunctions[ot->beh.factory]->ReleaseInternal();
  612. ot->beh.factory = 0;
  613. ot->beh.factories.RemoveIndex(0);
  614. }
  615. // Only remove the opAssign method if the script hasn't provided one
  616. if( ot->beh.copy == engine->scriptTypeBehaviours.beh.copy )
  617. {
  618. engine->scriptFunctions[ot->beh.copy]->ReleaseInternal();
  619. ot->beh.copy = 0;
  620. }
  621. }
  622. }
  623. }
  624. // Find other global nodes
  625. for( n = 0; n < scripts.GetLength(); n++ )
  626. {
  627. // Find other global nodes
  628. asCScriptNode *node = parsers[n]->GetScriptNode();
  629. RegisterNonTypesFromScript(node, scripts[n], engine->nameSpaces[0]);
  630. }
  631. }
  632. for( n = 0; n < parsers.GetLength(); n++ )
  633. {
  634. asDELETE(parsers[n],asCParser);
  635. }
  636. }
  637. void asCBuilder::RegisterTypesFromScript(asCScriptNode *node, asCScriptCode *script, asSNameSpace *ns)
  638. {
  639. asASSERT(node->nodeType == snScript);
  640. // Find structure definitions first
  641. node = node->firstChild;
  642. while( node )
  643. {
  644. asCScriptNode *next = node->next;
  645. if( node->nodeType == snNamespace )
  646. {
  647. // Recursively register the entities defined in the namespace
  648. asCString nsName;
  649. nsName.Assign(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  650. if( ns->name != "" )
  651. nsName = ns->name + "::" + nsName;
  652. asSNameSpace *nsChild = engine->AddNameSpace(nsName.AddressOf());
  653. RegisterTypesFromScript(node->lastChild, script, nsChild);
  654. }
  655. else
  656. {
  657. if( node->nodeType == snClass )
  658. {
  659. node->DisconnectParent();
  660. RegisterClass(node, script, ns);
  661. }
  662. else if( node->nodeType == snInterface )
  663. {
  664. node->DisconnectParent();
  665. RegisterInterface(node, script, ns);
  666. }
  667. else if( node->nodeType == snEnum )
  668. {
  669. node->DisconnectParent();
  670. RegisterEnum(node, script, ns);
  671. }
  672. else if( node->nodeType == snTypedef )
  673. {
  674. node->DisconnectParent();
  675. RegisterTypedef(node, script, ns);
  676. }
  677. else if( node->nodeType == snFuncDef )
  678. {
  679. node->DisconnectParent();
  680. RegisterFuncDef(node, script, ns, 0);
  681. }
  682. else if( node->nodeType == snMixin )
  683. {
  684. node->DisconnectParent();
  685. RegisterMixinClass(node, script, ns);
  686. }
  687. }
  688. node = next;
  689. }
  690. }
  691. void asCBuilder::RegisterNonTypesFromScript(asCScriptNode *node, asCScriptCode *script, asSNameSpace *ns)
  692. {
  693. node = node->firstChild;
  694. while( node )
  695. {
  696. asCScriptNode *next = node->next;
  697. if( node->nodeType == snNamespace )
  698. {
  699. // Determine the name of the namespace
  700. asCString nsName;
  701. nsName.Assign(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  702. if( ns->name != "" )
  703. nsName = ns->name + "::" + nsName;
  704. // Declare the namespace, then add the entities
  705. asSNameSpace *nsChild = engine->AddNameSpace(nsName.AddressOf());
  706. RegisterNonTypesFromScript(node->lastChild, script, nsChild);
  707. }
  708. else
  709. {
  710. node->DisconnectParent();
  711. if( node->nodeType == snFunction )
  712. RegisterScriptFunctionFromNode(node, script, 0, false, true, ns);
  713. else if( node->nodeType == snDeclaration )
  714. RegisterGlobalVar(node, script, ns);
  715. else if( node->nodeType == snVirtualProperty )
  716. RegisterVirtualProperty(node, script, 0, false, true, ns);
  717. else if( node->nodeType == snImport )
  718. RegisterImportedFunction(module->GetNextImportedFunctionId(), node, script, ns);
  719. else
  720. {
  721. // Unused script node
  722. int r, c;
  723. script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  724. WriteWarning(script->name, TXT_UNUSED_SCRIPT_NODE, r, c);
  725. node->Destroy(engine);
  726. }
  727. }
  728. node = next;
  729. }
  730. }
  731. void asCBuilder::CompileFunctions()
  732. {
  733. // Compile each function
  734. for( asUINT n = 0; n < functions.GetLength(); n++ )
  735. {
  736. sFunctionDescription *current = functions[n];
  737. if( current == 0 ) continue;
  738. // Don't compile the function again if it was an existing shared function
  739. if( current->isExistingShared ) continue;
  740. // Don't compile if there is no statement block
  741. if (current->node && !(current->node->nodeType == snStatementBlock || current->node->lastChild->nodeType == snStatementBlock))
  742. continue;
  743. asCCompiler compiler(engine);
  744. asCScriptFunction *func = engine->scriptFunctions[current->funcId];
  745. // Find the class declaration for constructors
  746. sClassDeclaration *classDecl = 0;
  747. if( current->objType && current->name == current->objType->name )
  748. {
  749. for( asUINT c = 0; c < classDeclarations.GetLength(); c++ )
  750. {
  751. if( classDeclarations[c]->typeInfo == current->objType )
  752. {
  753. classDecl = classDeclarations[c];
  754. break;
  755. }
  756. }
  757. asASSERT( classDecl );
  758. }
  759. if( current->node )
  760. {
  761. int r, c;
  762. current->script->ConvertPosToRowCol(current->node->tokenPos, &r, &c);
  763. asCString str = func->GetDeclarationStr();
  764. str.Format(TXT_COMPILING_s, str.AddressOf());
  765. WriteInfo(current->script->name, str, r, c, true);
  766. // When compiling a constructor need to pass the class declaration for member initializations
  767. compiler.CompileFunction(this, current->script, current->paramNames, current->node, func, classDecl);
  768. engine->preMessage.isSet = false;
  769. }
  770. else if( current->objType && current->name == current->objType->name )
  771. {
  772. asCScriptNode *node = classDecl->node;
  773. int r = 0, c = 0;
  774. if( node )
  775. current->script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  776. asCString str = func->GetDeclarationStr();
  777. str.Format(TXT_COMPILING_s, str.AddressOf());
  778. WriteInfo(current->script->name, str, r, c, true);
  779. // This is the default constructor that is generated
  780. // automatically if not implemented by the user.
  781. compiler.CompileDefaultConstructor(this, current->script, node, func, classDecl);
  782. engine->preMessage.isSet = false;
  783. }
  784. else
  785. {
  786. asASSERT( false );
  787. }
  788. }
  789. }
  790. #endif
  791. // Called from module and engine
  792. int asCBuilder::ParseDataType(const char *datatype, asCDataType *result, asSNameSpace *implicitNamespace, bool isReturnType)
  793. {
  794. Reset();
  795. asCScriptCode source;
  796. source.SetCode("", datatype, true);
  797. asCParser parser(this);
  798. int r = parser.ParseDataType(&source, isReturnType);
  799. if( r < 0 )
  800. return asINVALID_TYPE;
  801. // Get data type and property name
  802. asCScriptNode *dataType = parser.GetScriptNode()->firstChild;
  803. *result = CreateDataTypeFromNode(dataType, &source, implicitNamespace, true);
  804. if( isReturnType )
  805. *result = ModifyDataTypeFromNode(*result, dataType->next, &source, 0, 0);
  806. if( numErrors > 0 )
  807. return asINVALID_TYPE;
  808. return asSUCCESS;
  809. }
  810. int asCBuilder::ParseTemplateDecl(const char *decl, asCString *name, asCArray<asCString> &subtypeNames)
  811. {
  812. Reset();
  813. asCScriptCode source;
  814. source.SetCode("", decl, true);
  815. asCParser parser(this);
  816. int r = parser.ParseTemplateDecl(&source);
  817. if( r < 0 )
  818. return asINVALID_TYPE;
  819. // Get the template name and subtype names
  820. asCScriptNode *node = parser.GetScriptNode()->firstChild;
  821. name->Assign(&decl[node->tokenPos], node->tokenLength);
  822. while( (node = node->next) != 0 )
  823. {
  824. asCString subtypeName;
  825. subtypeName.Assign(&decl[node->tokenPos], node->tokenLength);
  826. subtypeNames.PushLast(subtypeName);
  827. }
  828. // TODO: template: check for name conflicts
  829. if( numErrors > 0 )
  830. return asINVALID_DECLARATION;
  831. return asSUCCESS;
  832. }
  833. int asCBuilder::VerifyProperty(asCDataType *dt, const char *decl, asCString &name, asCDataType &type, asSNameSpace *ns)
  834. {
  835. // Either datatype or namespace must be informed
  836. asASSERT( dt || ns );
  837. Reset();
  838. if( dt )
  839. {
  840. // Verify that the object type exist
  841. if( CastToObjectType(dt->GetTypeInfo()) == 0 )
  842. return asINVALID_OBJECT;
  843. }
  844. // Check property declaration and type
  845. asCScriptCode source;
  846. source.SetCode(TXT_PROPERTY, decl, true);
  847. asCParser parser(this);
  848. int r = parser.ParsePropertyDeclaration(&source);
  849. if( r < 0 )
  850. return asINVALID_DECLARATION;
  851. // Get data type
  852. asCScriptNode *dataType = parser.GetScriptNode()->firstChild;
  853. // Check if the property is declared 'by reference'
  854. bool isReference = (dataType->next->tokenType == ttAmp);
  855. // Get the name of the property
  856. asCScriptNode *nameNode = isReference ? dataType->next->next : dataType->next;
  857. // If an object property is registered, then use the
  858. // object's namespace, otherwise use the specified namespace
  859. type = CreateDataTypeFromNode(dataType, &source, dt ? dt->GetTypeInfo()->nameSpace : ns);
  860. name.Assign(&decl[nameNode->tokenPos], nameNode->tokenLength);
  861. type.MakeReference(isReference);
  862. // Validate that the type really can be a registered property
  863. // We cannot use CanBeInstantiated, as it is allowed to register
  864. // properties of type that cannot otherwise be instantiated
  865. if( type.IsFuncdef() && !type.IsObjectHandle() )
  866. {
  867. // Function definitions must always be handles
  868. return asINVALID_DECLARATION;
  869. }
  870. // Verify property name
  871. if( dt )
  872. {
  873. if( CheckNameConflictMember(dt->GetTypeInfo(), name.AddressOf(), nameNode, &source, true) < 0 )
  874. return asNAME_TAKEN;
  875. }
  876. else
  877. {
  878. if( CheckNameConflict(name.AddressOf(), nameNode, &source, ns) < 0 )
  879. return asNAME_TAKEN;
  880. }
  881. if( numErrors > 0 )
  882. return asINVALID_DECLARATION;
  883. return asSUCCESS;
  884. }
  885. #ifndef AS_NO_COMPILER
  886. asCObjectProperty *asCBuilder::GetObjectProperty(asCDataType &obj, const char *prop)
  887. {
  888. asASSERT(CastToObjectType(obj.GetTypeInfo()) != 0);
  889. // TODO: optimize: Improve linear search
  890. asCArray<asCObjectProperty *> &props = CastToObjectType(obj.GetTypeInfo())->properties;
  891. for( asUINT n = 0; n < props.GetLength(); n++ )
  892. {
  893. if( props[n]->name == prop )
  894. {
  895. if( module->accessMask & props[n]->accessMask )
  896. return props[n];
  897. else
  898. return 0;
  899. }
  900. }
  901. return 0;
  902. }
  903. #endif
  904. bool asCBuilder::DoesGlobalPropertyExist(const char *prop, asSNameSpace *ns, asCGlobalProperty **outProp, sGlobalVariableDescription **outDesc, bool *isAppProp)
  905. {
  906. if( outProp ) *outProp = 0;
  907. if( outDesc ) *outDesc = 0;
  908. if( isAppProp ) *isAppProp = false;
  909. // Check application registered properties
  910. asCString name(prop);
  911. asCGlobalProperty *globProp = engine->registeredGlobalProps.GetFirst(ns, name);
  912. if( globProp )
  913. {
  914. if( isAppProp ) *isAppProp = true;
  915. if( outProp ) *outProp = globProp;
  916. return true;
  917. }
  918. #ifndef AS_NO_COMPILER
  919. // Check properties being compiled now
  920. sGlobalVariableDescription* desc = globVariables.GetFirst(ns, prop);
  921. if( desc && !desc->isEnumValue )
  922. {
  923. if( outProp ) *outProp = desc->property;
  924. if( outDesc ) *outDesc = desc;
  925. return true;
  926. }
  927. #endif
  928. // Check previously compiled global variables
  929. if( module )
  930. {
  931. globProp = module->scriptGlobals.GetFirst(ns, prop);
  932. if( globProp )
  933. {
  934. if( outProp ) *outProp = globProp;
  935. return true;
  936. }
  937. }
  938. return false;
  939. }
  940. asCGlobalProperty *asCBuilder::GetGlobalProperty(const char *prop, asSNameSpace *ns, bool *isCompiled, bool *isPureConstant, asQWORD *constantValue, bool *isAppProp)
  941. {
  942. if( isCompiled ) *isCompiled = true;
  943. if( isPureConstant ) *isPureConstant = false;
  944. if( isAppProp ) *isAppProp = false;
  945. if( constantValue ) *constantValue = 0;
  946. asCGlobalProperty *globProp = 0;
  947. sGlobalVariableDescription *globDesc = 0;
  948. if( DoesGlobalPropertyExist(prop, ns, &globProp, &globDesc, isAppProp) )
  949. {
  950. #ifndef AS_NO_COMPILER
  951. if( globDesc )
  952. {
  953. // The property was declared in this build call, check if it has been compiled successfully already
  954. if( isCompiled ) *isCompiled = globDesc->isCompiled;
  955. if( isPureConstant ) *isPureConstant = globDesc->isPureConstant;
  956. if( constantValue ) *constantValue = globDesc->constantValue;
  957. }
  958. else
  959. #endif
  960. if( isAppProp )
  961. {
  962. // Don't return the property if the module doesn't have access to it
  963. if( !(module->accessMask & globProp->accessMask) )
  964. globProp = 0;
  965. }
  966. return globProp;
  967. }
  968. return 0;
  969. }
  970. int asCBuilder::ParseFunctionDeclaration(asCObjectType *objType, const char *decl, asCScriptFunction *func, bool isSystemFunction, asCArray<bool> *paramAutoHandles, bool *returnAutoHandle, asSNameSpace *ns, asCScriptNode **listPattern, asCObjectType **outParentClass)
  971. {
  972. asASSERT( objType || ns );
  973. if (listPattern)
  974. *listPattern = 0;
  975. if (outParentClass)
  976. *outParentClass = 0;
  977. // TODO: Can't we use GetParsedFunctionDetails to do most of what is done in this function?
  978. Reset();
  979. asCScriptCode source;
  980. source.SetCode(TXT_SYSTEM_FUNCTION, decl, true);
  981. asCParser parser(this);
  982. int r = parser.ParseFunctionDefinition(&source, listPattern != 0);
  983. if( r < 0 )
  984. return asINVALID_DECLARATION;
  985. asCScriptNode *node = parser.GetScriptNode();
  986. // Determine scope
  987. asCScriptNode *n = node->firstChild->next->next;
  988. asCObjectType *parentClass = 0;
  989. func->nameSpace = GetNameSpaceFromNode(n, &source, ns, &n, &parentClass);
  990. if( func->nameSpace == 0 && parentClass == 0 )
  991. return asINVALID_DECLARATION;
  992. if (parentClass && func->funcType != asFUNC_FUNCDEF)
  993. return asINVALID_DECLARATION;
  994. if (outParentClass)
  995. *outParentClass = parentClass;
  996. // Find name
  997. func->name.Assign(&source.code[n->tokenPos], n->tokenLength);
  998. // Initialize a script function object for registration
  999. bool autoHandle;
  1000. // Scoped reference types are allowed to use handle when returned from application functions
  1001. func->returnType = CreateDataTypeFromNode(node->firstChild, &source, objType ? objType->nameSpace : ns, true, parentClass ? parentClass : objType);
  1002. func->returnType = ModifyDataTypeFromNode(func->returnType, node->firstChild->next, &source, 0, &autoHandle);
  1003. if( autoHandle && (!func->returnType.IsObjectHandle() || func->returnType.IsReference()) )
  1004. return asINVALID_DECLARATION;
  1005. if( returnAutoHandle ) *returnAutoHandle = autoHandle;
  1006. // Reference types cannot be returned by value from system functions
  1007. if( isSystemFunction &&
  1008. (func->returnType.GetTypeInfo() &&
  1009. (func->returnType.GetTypeInfo()->flags & asOBJ_REF)) &&
  1010. !(func->returnType.IsReference() ||
  1011. func->returnType.IsObjectHandle()) )
  1012. return asINVALID_DECLARATION;
  1013. // Count number of parameters
  1014. int paramCount = 0;
  1015. asCScriptNode *paramList = n->next;
  1016. n = paramList->firstChild;
  1017. while( n )
  1018. {
  1019. paramCount++;
  1020. n = n->next->next;
  1021. if( n && n->nodeType == snIdentifier )
  1022. n = n->next;
  1023. if( n && n->nodeType == snExpression )
  1024. n = n->next;
  1025. }
  1026. // Preallocate memory
  1027. func->parameterTypes.Allocate(paramCount, false);
  1028. func->parameterNames.SetLength(paramCount);
  1029. func->inOutFlags.Allocate(paramCount, false);
  1030. func->defaultArgs.Allocate(paramCount, false);
  1031. if( paramAutoHandles ) paramAutoHandles->Allocate(paramCount, false);
  1032. n = paramList->firstChild;
  1033. asUINT index = 0;
  1034. while( n )
  1035. {
  1036. asETypeModifiers inOutFlags;
  1037. asCDataType type = CreateDataTypeFromNode(n, &source, objType ? objType->nameSpace : ns, false, parentClass ? parentClass : objType);
  1038. type = ModifyDataTypeFromNode(type, n->next, &source, &inOutFlags, &autoHandle);
  1039. // Reference types cannot be passed by value to system functions
  1040. if( isSystemFunction &&
  1041. (type.GetTypeInfo() &&
  1042. (type.GetTypeInfo()->flags & asOBJ_REF)) &&
  1043. !(type.IsReference() ||
  1044. type.IsObjectHandle()) )
  1045. return asINVALID_DECLARATION;
  1046. // Store the parameter type
  1047. func->parameterTypes.PushLast(type);
  1048. func->inOutFlags.PushLast(inOutFlags);
  1049. // Don't permit void parameters
  1050. if( type.GetTokenType() == ttVoid )
  1051. return asINVALID_DECLARATION;
  1052. if( autoHandle && (!type.IsObjectHandle() || type.IsReference()) )
  1053. return asINVALID_DECLARATION;
  1054. if( paramAutoHandles ) paramAutoHandles->PushLast(autoHandle);
  1055. // Make sure that var type parameters are references
  1056. if( type.GetTokenType() == ttQuestion &&
  1057. !type.IsReference() )
  1058. return asINVALID_DECLARATION;
  1059. // Move to next parameter
  1060. n = n->next->next;
  1061. if( n && n->nodeType == snIdentifier )
  1062. {
  1063. func->parameterNames[index] = asCString(&source.code[n->tokenPos], n->tokenLength);
  1064. n = n->next;
  1065. }
  1066. ++index;
  1067. if( n && n->nodeType == snExpression )
  1068. {
  1069. // Strip out white space and comments to better share the string
  1070. asCString *defaultArgStr = asNEW(asCString);
  1071. if( defaultArgStr )
  1072. {
  1073. *defaultArgStr = GetCleanExpressionString(n, &source);
  1074. func->defaultArgs.PushLast(defaultArgStr);
  1075. }
  1076. n = n->next;
  1077. }
  1078. else
  1079. func->defaultArgs.PushLast(0);
  1080. }
  1081. // Set the read-only flag if const is declared after parameter list
  1082. n = paramList->next;
  1083. if( n && n->nodeType == snUndefined && n->tokenType == ttConst )
  1084. {
  1085. if( objType == 0 )
  1086. return asINVALID_DECLARATION;
  1087. func->SetReadOnly(true);
  1088. n = n->next;
  1089. }
  1090. else
  1091. func->SetReadOnly(false);
  1092. // If the caller expects a list pattern, check for the existence, else report an error if not
  1093. if( listPattern )
  1094. {
  1095. if( n == 0 || n->nodeType != snListPattern )
  1096. return asINVALID_DECLARATION;
  1097. else
  1098. {
  1099. *listPattern = n;
  1100. n->DisconnectParent();
  1101. }
  1102. }
  1103. else
  1104. {
  1105. if( n )
  1106. return asINVALID_DECLARATION;
  1107. }
  1108. // Make sure the default args are declared correctly
  1109. ValidateDefaultArgs(&source, node, func);
  1110. if( numErrors > 0 || numWarnings > 0 )
  1111. return asINVALID_DECLARATION;
  1112. return 0;
  1113. }
  1114. int asCBuilder::ParseVariableDeclaration(const char *decl, asSNameSpace *implicitNamespace, asCString &outName, asSNameSpace *&outNamespace, asCDataType &outDt)
  1115. {
  1116. Reset();
  1117. asCScriptCode source;
  1118. source.SetCode(TXT_VARIABLE_DECL, decl, true);
  1119. asCParser parser(this);
  1120. int r = parser.ParsePropertyDeclaration(&source);
  1121. if( r < 0 )
  1122. return asINVALID_DECLARATION;
  1123. asCScriptNode *node = parser.GetScriptNode();
  1124. // Determine the scope from declaration
  1125. asCScriptNode *n = node->firstChild->next;
  1126. // TODO: child funcdef: The parentType will be set if the scope is actually a type rather than a namespace
  1127. outNamespace = GetNameSpaceFromNode(n, &source, implicitNamespace, &n);
  1128. if( outNamespace == 0 )
  1129. return asINVALID_DECLARATION;
  1130. // Find name
  1131. outName.Assign(&source.code[n->tokenPos], n->tokenLength);
  1132. // Initialize a script variable object for registration
  1133. outDt = CreateDataTypeFromNode(node->firstChild, &source, implicitNamespace);
  1134. if( numErrors > 0 || numWarnings > 0 )
  1135. return asINVALID_DECLARATION;
  1136. return 0;
  1137. }
  1138. int asCBuilder::CheckNameConflictMember(asCTypeInfo *t, const char *name, asCScriptNode *node, asCScriptCode *code, bool isProperty)
  1139. {
  1140. // It's not necessary to check against object types
  1141. asCObjectType *ot = CastToObjectType(t);
  1142. if (!ot)
  1143. return 0;
  1144. // TODO: optimize: Improve linear search
  1145. asCArray<asCObjectProperty *> &props = ot->properties;
  1146. for( asUINT n = 0; n < props.GetLength(); n++ )
  1147. {
  1148. if( props[n]->name == name )
  1149. {
  1150. if( code )
  1151. {
  1152. asCString str;
  1153. str.Format(TXT_NAME_CONFLICT_s_OBJ_PROPERTY, name);
  1154. WriteError(str, code, node);
  1155. }
  1156. return -1;
  1157. }
  1158. }
  1159. asCArray<asCFuncdefType*> &funcdefs = ot->childFuncDefs;
  1160. for (asUINT n = 0; n < funcdefs.GetLength(); n++)
  1161. {
  1162. if (funcdefs[n]->name == name)
  1163. {
  1164. if (code)
  1165. {
  1166. asCString str;
  1167. str.Format(TXT_NAME_CONFLICT_s_IS_FUNCDEF, name);
  1168. WriteError(str, code, node);
  1169. }
  1170. return -1;
  1171. }
  1172. }
  1173. // Property names must be checked against method names
  1174. if( isProperty )
  1175. {
  1176. asCArray<int> methods = ot->methods;
  1177. for( asUINT n = 0; n < methods.GetLength(); n++ )
  1178. {
  1179. if( engine->scriptFunctions[methods[n]]->name == name )
  1180. {
  1181. if( code )
  1182. {
  1183. asCString str;
  1184. str.Format(TXT_NAME_CONFLICT_s_METHOD, name);
  1185. WriteError(str, code, node);
  1186. }
  1187. return -1;
  1188. }
  1189. }
  1190. }
  1191. return 0;
  1192. }
  1193. int asCBuilder::CheckNameConflict(const char *name, asCScriptNode *node, asCScriptCode *code, asSNameSpace *ns)
  1194. {
  1195. // Check against registered object types
  1196. // TODO: Must check against registered funcdefs too
  1197. if( engine->GetRegisteredType(name, ns) != 0 )
  1198. {
  1199. if( code )
  1200. {
  1201. asCString str;
  1202. str.Format(TXT_NAME_CONFLICT_s_EXTENDED_TYPE, name);
  1203. WriteError(str, code, node);
  1204. }
  1205. return -1;
  1206. }
  1207. // Check against global properties
  1208. if( DoesGlobalPropertyExist(name, ns) )
  1209. {
  1210. if( code )
  1211. {
  1212. asCString str;
  1213. str.Format(TXT_NAME_CONFLICT_s_GLOBAL_PROPERTY, name);
  1214. WriteError(str, code, node);
  1215. }
  1216. return -1;
  1217. }
  1218. // TODO: Property names must be checked against function names
  1219. #ifndef AS_NO_COMPILER
  1220. // Check against class types
  1221. asUINT n;
  1222. for( n = 0; n < classDeclarations.GetLength(); n++ )
  1223. {
  1224. if( classDeclarations[n]->name == name &&
  1225. classDeclarations[n]->typeInfo->nameSpace == ns )
  1226. {
  1227. if( code )
  1228. {
  1229. asCString str;
  1230. str.Format(TXT_NAME_CONFLICT_s_STRUCT, name);
  1231. WriteError(str, code, node);
  1232. }
  1233. return -1;
  1234. }
  1235. }
  1236. // Check against named types
  1237. for( n = 0; n < namedTypeDeclarations.GetLength(); n++ )
  1238. {
  1239. if( namedTypeDeclarations[n]->name == name &&
  1240. namedTypeDeclarations[n]->typeInfo->nameSpace == ns )
  1241. {
  1242. if( code )
  1243. {
  1244. asCString str;
  1245. str.Format(TXT_NAME_CONFLICT_s_IS_NAMED_TYPE, name);
  1246. WriteError(str, code, node);
  1247. }
  1248. return -1;
  1249. }
  1250. }
  1251. // Must check for name conflicts with funcdefs
  1252. for( n = 0; n < funcDefs.GetLength(); n++ )
  1253. {
  1254. if( funcDefs[n]->name == name &&
  1255. module->funcDefs[funcDefs[n]->idx]->nameSpace == ns )
  1256. {
  1257. if( code )
  1258. {
  1259. asCString str;
  1260. str.Format(TXT_NAME_CONFLICT_s_IS_FUNCDEF, name);
  1261. WriteError(str, code, node);
  1262. }
  1263. return -1;
  1264. }
  1265. }
  1266. // Check against mixin classes
  1267. if( GetMixinClass(name, ns) )
  1268. {
  1269. if( code )
  1270. {
  1271. asCString str;
  1272. str.Format(TXT_NAME_CONFLICT_s_IS_MIXIN, name);
  1273. WriteError(str, code, node);
  1274. }
  1275. return -1;
  1276. }
  1277. #endif
  1278. return 0;
  1279. }
  1280. #ifndef AS_NO_COMPILER
  1281. sMixinClass *asCBuilder::GetMixinClass(const char *name, asSNameSpace *ns)
  1282. {
  1283. for( asUINT n = 0; n < mixinClasses.GetLength(); n++ )
  1284. if( mixinClasses[n]->name == name &&
  1285. mixinClasses[n]->ns == ns )
  1286. return mixinClasses[n];
  1287. return 0;
  1288. }
  1289. int asCBuilder::RegisterFuncDef(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns, asCObjectType *parent)
  1290. {
  1291. // namespace and parent are exclusively mutual
  1292. asASSERT((ns == 0 && parent) || (ns && parent == 0));
  1293. // Skip leading 'shared' and 'external' keywords
  1294. asCScriptNode *n = node->firstChild;
  1295. while (n->nodeType == snIdentifier)
  1296. n = n->next;
  1297. // Find the name
  1298. asASSERT( n->nodeType == snDataType );
  1299. n = n->next->next;
  1300. asCString name;
  1301. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  1302. // Check for name conflict with other types
  1303. if (ns)
  1304. {
  1305. int r = CheckNameConflict(name.AddressOf(), node, file, ns);
  1306. if (asSUCCESS != r)
  1307. {
  1308. node->Destroy(engine);
  1309. return r;
  1310. }
  1311. }
  1312. else
  1313. {
  1314. int r = CheckNameConflictMember(parent, name.AddressOf(), node, file, false);
  1315. if (asSUCCESS != r)
  1316. {
  1317. node->Destroy(engine);
  1318. return r;
  1319. }
  1320. }
  1321. // The function definition should be stored as a asCScriptFunction so that the application
  1322. // can use the asIScriptFunction interface to enumerate the return type and parameters
  1323. // The return type and parameter types aren't determined in this function. A second pass is
  1324. // necessary after all type declarations have been identified. The second pass is implemented
  1325. // in CompleteFuncDef().
  1326. sFuncDef *fd = asNEW(sFuncDef);
  1327. if( fd == 0 )
  1328. {
  1329. node->Destroy(engine);
  1330. return asOUT_OF_MEMORY;
  1331. }
  1332. fd->name = name;
  1333. fd->node = node;
  1334. fd->script = file;
  1335. fd->idx = module->AddFuncDef(name, ns, parent);
  1336. funcDefs.PushLast(fd);
  1337. return 0;
  1338. }
  1339. void asCBuilder::CompleteFuncDef(sFuncDef *funcDef)
  1340. {
  1341. asCArray<asCString *> defaultArgs;
  1342. asSFunctionTraits funcTraits;
  1343. asCFuncdefType *fdt = module->funcDefs[funcDef->idx];
  1344. asASSERT( fdt );
  1345. asCScriptFunction *func = fdt->funcdef;
  1346. asSNameSpace *implicitNs = func->nameSpace ? func->nameSpace : fdt->parentClass->nameSpace;
  1347. GetParsedFunctionDetails(funcDef->node, funcDef->script, fdt->parentClass, funcDef->name, func->returnType, func->parameterNames, func->parameterTypes, func->inOutFlags, defaultArgs, funcTraits, implicitNs);
  1348. // There should not be any defaultArgs, but if there are any we need to delete them to avoid leaks
  1349. for( asUINT n = 0; n < defaultArgs.GetLength(); n++ )
  1350. if( defaultArgs[n] )
  1351. asDELETE(defaultArgs[n], asCString);
  1352. // All funcdefs are shared, unless one of the parameter types or return type is not shared
  1353. bool declaredShared = funcTraits.GetTrait(asTRAIT_SHARED);
  1354. funcTraits.SetTrait(asTRAIT_SHARED, true);
  1355. if (func->returnType.GetTypeInfo() && !func->returnType.GetTypeInfo()->IsShared())
  1356. {
  1357. if (declaredShared)
  1358. {
  1359. asCString s;
  1360. s.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, func->returnType.GetTypeInfo()->name.AddressOf());
  1361. WriteError(s.AddressOf(), funcDef->script, funcDef->node);
  1362. }
  1363. funcTraits.SetTrait(asTRAIT_SHARED, false);
  1364. }
  1365. for( asUINT n = 0; funcTraits.GetTrait(asTRAIT_SHARED) && n < func->parameterTypes.GetLength(); n++ )
  1366. if (func->parameterTypes[n].GetTypeInfo() && !func->parameterTypes[n].GetTypeInfo()->IsShared())
  1367. {
  1368. if (declaredShared)
  1369. {
  1370. asCString s;
  1371. s.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, func->parameterTypes[n].GetTypeInfo()->name.AddressOf());
  1372. WriteError(s.AddressOf(), funcDef->script, funcDef->node);
  1373. }
  1374. funcTraits.SetTrait(asTRAIT_SHARED, false);
  1375. }
  1376. func->SetShared(funcTraits.GetTrait(asTRAIT_SHARED));
  1377. // Check if there is another identical funcdef from another module and if so reuse that instead
  1378. bool found = false;
  1379. if( func->IsShared() )
  1380. {
  1381. for( asUINT n = 0; n < engine->funcDefs.GetLength(); n++ )
  1382. {
  1383. asCFuncdefType *fdt2 = engine->funcDefs[n];
  1384. if( fdt2 == 0 || fdt == fdt2 )
  1385. continue;
  1386. if( !fdt2->funcdef->IsShared() )
  1387. continue;
  1388. if( fdt2->name == fdt->name &&
  1389. fdt2->nameSpace == fdt->nameSpace &&
  1390. fdt2->funcdef->IsSignatureExceptNameEqual(func) )
  1391. {
  1392. // Replace our funcdef for the existing one
  1393. funcDef->idx = fdt2->funcdef->id;
  1394. module->funcDefs[module->funcDefs.IndexOf(fdt)] = fdt2;
  1395. fdt2->AddRefInternal();
  1396. engine->funcDefs.RemoveValue(fdt);
  1397. fdt->ReleaseInternal();
  1398. found = true;
  1399. break;
  1400. }
  1401. }
  1402. }
  1403. // If the funcdef was declared as external then the existing shared declaration must have been found
  1404. if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && !found)
  1405. {
  1406. asCString str;
  1407. str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, funcDef->name.AddressOf());
  1408. WriteError(str, funcDef->script, funcDef->node);
  1409. }
  1410. // Remember if the type was declared as external so the saved bytecode can be flagged accordingly
  1411. if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && found)
  1412. module->externalTypes.PushLast(engine->scriptFunctions[funcDef->idx]->funcdefType);
  1413. }
  1414. int asCBuilder::RegisterGlobalVar(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1415. {
  1416. // Has the application disabled global vars?
  1417. if( engine->ep.disallowGlobalVars )
  1418. WriteError(TXT_GLOBAL_VARS_NOT_ALLOWED, file, node);
  1419. // What data type is it?
  1420. asCDataType type = CreateDataTypeFromNode(node->firstChild, file, ns);
  1421. if( !type.CanBeInstantiated() )
  1422. {
  1423. asCString str;
  1424. if( type.IsAbstractClass() )
  1425. str.Format(TXT_ABSTRACT_CLASS_s_CANNOT_BE_INSTANTIATED, type.Format(ns).AddressOf());
  1426. else if( type.IsInterface() )
  1427. str.Format(TXT_INTERFACE_s_CANNOT_BE_INSTANTIATED, type.Format(ns).AddressOf());
  1428. else
  1429. // TODO: Improve error message to explain why
  1430. str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format(ns).AddressOf());
  1431. WriteError(str, file, node);
  1432. }
  1433. asCScriptNode *n = node->firstChild->next;
  1434. while( n )
  1435. {
  1436. // Verify that the name isn't taken
  1437. asCString name(&file->code[n->tokenPos], n->tokenLength);
  1438. CheckNameConflict(name.AddressOf(), n, file, ns);
  1439. // Register the global variable
  1440. sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription);
  1441. if( gvar == 0 )
  1442. {
  1443. node->Destroy(engine);
  1444. return asOUT_OF_MEMORY;
  1445. }
  1446. gvar->script = file;
  1447. gvar->name = name;
  1448. gvar->isCompiled = false;
  1449. gvar->datatype = type;
  1450. gvar->isEnumValue = false;
  1451. gvar->ns = ns;
  1452. // TODO: Give error message if wrong
  1453. asASSERT(!gvar->datatype.IsReference());
  1454. // Allocation is done when the variable is compiled, to allow for autos
  1455. gvar->property = 0;
  1456. gvar->index = 0;
  1457. globVariables.Put(gvar);
  1458. gvar->declaredAtNode = n;
  1459. n = n->next;
  1460. gvar->declaredAtNode->DisconnectParent();
  1461. gvar->initializationNode = 0;
  1462. if( n &&
  1463. ( n->nodeType == snAssignment ||
  1464. n->nodeType == snArgList ||
  1465. n->nodeType == snInitList ) )
  1466. {
  1467. gvar->initializationNode = n;
  1468. n = n->next;
  1469. gvar->initializationNode->DisconnectParent();
  1470. }
  1471. }
  1472. node->Destroy(engine);
  1473. return 0;
  1474. }
  1475. int asCBuilder::RegisterMixinClass(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1476. {
  1477. asCScriptNode *cl = node->firstChild;
  1478. asASSERT( cl->nodeType == snClass );
  1479. asCScriptNode *n = cl->firstChild;
  1480. // Skip potential 'final' and 'shared' tokens
  1481. while( n->tokenType == ttIdentifier &&
  1482. (file->TokenEquals(n->tokenPos, n->tokenLength, FINAL_TOKEN) ||
  1483. file->TokenEquals(n->tokenPos, n->tokenLength, SHARED_TOKEN)) )
  1484. {
  1485. // Report error, because mixin class cannot be final or shared
  1486. asCString msg;
  1487. msg.Format(TXT_MIXIN_CANNOT_BE_DECLARED_AS_s, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
  1488. WriteError(msg, file, n);
  1489. asCScriptNode *tmp = n;
  1490. n = n->next;
  1491. // Remove the invalid node, so compilation can continue as if it wasn't there
  1492. tmp->DisconnectParent();
  1493. tmp->Destroy(engine);
  1494. }
  1495. asCString name(&file->code[n->tokenPos], n->tokenLength);
  1496. int r, c;
  1497. file->ConvertPosToRowCol(n->tokenPos, &r, &c);
  1498. CheckNameConflict(name.AddressOf(), n, file, ns);
  1499. sMixinClass *decl = asNEW(sMixinClass);
  1500. if( decl == 0 )
  1501. {
  1502. node->Destroy(engine);
  1503. return asOUT_OF_MEMORY;
  1504. }
  1505. mixinClasses.PushLast(decl);
  1506. decl->name = name;
  1507. decl->ns = ns;
  1508. decl->node = cl;
  1509. decl->script = file;
  1510. // Clean up memory
  1511. cl->DisconnectParent();
  1512. node->Destroy(engine);
  1513. // Check that the mixin class doesn't contain any child types
  1514. // TODO: Add support for child types in mixin classes
  1515. n = cl->firstChild;
  1516. while (n)
  1517. {
  1518. if (n->nodeType == snFuncDef)
  1519. {
  1520. WriteError(TXT_MIXIN_CANNOT_HAVE_CHILD_TYPES, file, n);
  1521. break;
  1522. }
  1523. n = n->next;
  1524. }
  1525. return 0;
  1526. }
  1527. int asCBuilder::RegisterClass(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1528. {
  1529. asCScriptNode *n = node->firstChild;
  1530. bool isFinal = false;
  1531. bool isShared = false;
  1532. bool isAbstract = false;
  1533. bool isExternal = false;
  1534. // Check the class modifiers
  1535. while( n->tokenType == ttIdentifier )
  1536. {
  1537. if( file->TokenEquals(n->tokenPos, n->tokenLength, FINAL_TOKEN) )
  1538. {
  1539. if( isAbstract )
  1540. WriteError(TXT_CLASS_CANT_BE_FINAL_AND_ABSTRACT, file, n);
  1541. else
  1542. {
  1543. if( isFinal )
  1544. {
  1545. asCString msg;
  1546. msg.Format(TXT_ATTR_s_INFORMED_MULTIPLE_TIMES, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
  1547. WriteWarning(msg, file, n);
  1548. }
  1549. isFinal = true;
  1550. }
  1551. }
  1552. else if( file->TokenEquals(n->tokenPos, n->tokenLength, SHARED_TOKEN) )
  1553. {
  1554. if( isShared )
  1555. {
  1556. asCString msg;
  1557. msg.Format(TXT_ATTR_s_INFORMED_MULTIPLE_TIMES, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
  1558. WriteWarning(msg, file, n);
  1559. }
  1560. isShared = true;
  1561. }
  1562. else if (file->TokenEquals(n->tokenPos, n->tokenLength, EXTERNAL_TOKEN))
  1563. {
  1564. if (isExternal)
  1565. {
  1566. asCString msg;
  1567. msg.Format(TXT_ATTR_s_INFORMED_MULTIPLE_TIMES, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
  1568. WriteWarning(msg, file, n);
  1569. }
  1570. isExternal = true;
  1571. }
  1572. else if( file->TokenEquals(n->tokenPos, n->tokenLength, ABSTRACT_TOKEN) )
  1573. {
  1574. if( isFinal )
  1575. WriteError(TXT_CLASS_CANT_BE_FINAL_AND_ABSTRACT, file, n);
  1576. else
  1577. {
  1578. if( isAbstract )
  1579. {
  1580. asCString msg;
  1581. msg.Format(TXT_ATTR_s_INFORMED_MULTIPLE_TIMES, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
  1582. WriteWarning(msg, file, n);
  1583. }
  1584. isAbstract = true;
  1585. }
  1586. }
  1587. else
  1588. {
  1589. // This is the name of the class
  1590. break;
  1591. }
  1592. n = n->next;
  1593. }
  1594. asCString name(&file->code[n->tokenPos], n->tokenLength);
  1595. int r, c;
  1596. file->ConvertPosToRowCol(n->tokenPos, &r, &c);
  1597. CheckNameConflict(name.AddressOf(), n, file, ns);
  1598. sClassDeclaration *decl = asNEW(sClassDeclaration);
  1599. if( decl == 0 )
  1600. {
  1601. node->Destroy(engine);
  1602. return asOUT_OF_MEMORY;
  1603. }
  1604. classDeclarations.PushLast(decl);
  1605. decl->name = name;
  1606. decl->script = file;
  1607. decl->node = node;
  1608. // External shared interfaces must not try to redefine the interface
  1609. if (isExternal && (n->next == 0 || n->next->tokenType != ttEndStatement))
  1610. {
  1611. asCString str;
  1612. str.Format(TXT_EXTERNAL_SHARED_s_CANNOT_REDEF, name.AddressOf());
  1613. WriteError(str, file, n);
  1614. }
  1615. else if (!isExternal && n->next && n->next->tokenType == ttEndStatement)
  1616. {
  1617. asCString str;
  1618. str.Format(TXT_MISSING_DEFINITION_OF_s, name.AddressOf());
  1619. WriteError(str, file, n);
  1620. }
  1621. // If this type is shared and there already exist another shared
  1622. // type of the same name, then that one should be used instead of
  1623. // creating a new one.
  1624. asCObjectType *st = 0;
  1625. if( isShared )
  1626. {
  1627. for( asUINT i = 0; i < engine->sharedScriptTypes.GetLength(); i++ )
  1628. {
  1629. st = CastToObjectType(engine->sharedScriptTypes[i]);
  1630. if( st &&
  1631. st->IsShared() &&
  1632. st->name == name &&
  1633. st->nameSpace == ns &&
  1634. !st->IsInterface() )
  1635. {
  1636. // We'll use the existing type
  1637. decl->isExistingShared = true;
  1638. decl->typeInfo = st;
  1639. module->classTypes.PushLast(st);
  1640. st->AddRefInternal();
  1641. break;
  1642. }
  1643. }
  1644. }
  1645. // If the class was declared as external then it must have been compiled in a different module first
  1646. if (isExternal && decl->typeInfo == 0)
  1647. {
  1648. asCString str;
  1649. str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, name.AddressOf());
  1650. WriteError(str, file, n);
  1651. }
  1652. // Remember if the class was declared as external so the saved bytecode can be flagged accordingly
  1653. if (isExternal)
  1654. module->externalTypes.PushLast(st);
  1655. if (!decl->isExistingShared)
  1656. {
  1657. // Create a new object type for this class
  1658. st = asNEW(asCObjectType)(engine);
  1659. if (st == 0)
  1660. return asOUT_OF_MEMORY;
  1661. // By default all script classes are marked as garbage collected.
  1662. // Only after the complete structure and relationship between classes
  1663. // is known, can the flag be cleared for those objects that truly cannot
  1664. // form circular references. This is important because a template
  1665. // callback may be called with a script class before the compilation
  1666. // completes, and until it is known, the callback must assume the class
  1667. // is garbage collected.
  1668. st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT | asOBJ_GC;
  1669. if (isShared)
  1670. st->flags |= asOBJ_SHARED;
  1671. if (isFinal)
  1672. st->flags |= asOBJ_NOINHERIT;
  1673. if (isAbstract)
  1674. st->flags |= asOBJ_ABSTRACT;
  1675. if (node->tokenType == ttHandle)
  1676. st->flags |= asOBJ_IMPLICIT_HANDLE;
  1677. st->size = sizeof(asCScriptObject);
  1678. st->name = name;
  1679. st->nameSpace = ns;
  1680. st->module = module;
  1681. module->classTypes.PushLast(st);
  1682. if (isShared)
  1683. {
  1684. engine->sharedScriptTypes.PushLast(st);
  1685. st->AddRefInternal();
  1686. }
  1687. decl->typeInfo = st;
  1688. // Use the default script class behaviours
  1689. st->beh = engine->scriptTypeBehaviours.beh;
  1690. // TODO: Move this to asCObjectType so that the asCRestore can reuse it
  1691. engine->scriptFunctions[st->beh.addref]->AddRefInternal();
  1692. engine->scriptFunctions[st->beh.release]->AddRefInternal();
  1693. engine->scriptFunctions[st->beh.gcEnumReferences]->AddRefInternal();
  1694. engine->scriptFunctions[st->beh.gcGetFlag]->AddRefInternal();
  1695. engine->scriptFunctions[st->beh.gcGetRefCount]->AddRefInternal();
  1696. engine->scriptFunctions[st->beh.gcReleaseAllReferences]->AddRefInternal();
  1697. engine->scriptFunctions[st->beh.gcSetFlag]->AddRefInternal();
  1698. engine->scriptFunctions[st->beh.copy]->AddRefInternal();
  1699. engine->scriptFunctions[st->beh.factory]->AddRefInternal();
  1700. engine->scriptFunctions[st->beh.construct]->AddRefInternal();
  1701. // TODO: weak: Should not do this if the class has been declared with noweak
  1702. engine->scriptFunctions[st->beh.getWeakRefFlag]->AddRefInternal();
  1703. // Skip to the content of the class
  1704. while (n && n->nodeType == snIdentifier)
  1705. n = n->next;
  1706. }
  1707. // Register possible child types
  1708. while (n)
  1709. {
  1710. node = n->next;
  1711. if (n->nodeType == snFuncDef)
  1712. {
  1713. n->DisconnectParent();
  1714. if (!decl->isExistingShared)
  1715. RegisterFuncDef(n, file, 0, st);
  1716. else
  1717. {
  1718. // Destroy the node, since it won't be used
  1719. // TODO: Should verify that the funcdef is identical to the one in the existing shared class
  1720. n->Destroy(engine);
  1721. }
  1722. }
  1723. n = node;
  1724. }
  1725. return 0;
  1726. }
  1727. int asCBuilder::RegisterInterface(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1728. {
  1729. asCScriptNode *n = node->firstChild;
  1730. bool isShared = false;
  1731. bool isExternal = false;
  1732. while( n->nodeType == snIdentifier )
  1733. {
  1734. if (file->TokenEquals(n->tokenPos, n->tokenLength, SHARED_TOKEN))
  1735. isShared = true;
  1736. else if (file->TokenEquals(n->tokenPos, n->tokenLength, EXTERNAL_TOKEN))
  1737. isExternal = true;
  1738. else
  1739. break;
  1740. n = n->next;
  1741. }
  1742. int r, c;
  1743. file->ConvertPosToRowCol(n->tokenPos, &r, &c);
  1744. asCString name;
  1745. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  1746. CheckNameConflict(name.AddressOf(), n, file, ns);
  1747. sClassDeclaration *decl = asNEW(sClassDeclaration);
  1748. if( decl == 0 )
  1749. {
  1750. node->Destroy(engine);
  1751. return asOUT_OF_MEMORY;
  1752. }
  1753. interfaceDeclarations.PushLast(decl);
  1754. decl->name = name;
  1755. decl->script = file;
  1756. decl->node = node;
  1757. // External shared interfaces must not try to redefine the interface
  1758. if (isExternal && (n->next == 0 || n->next->tokenType != ttEndStatement) )
  1759. {
  1760. asCString str;
  1761. str.Format(TXT_EXTERNAL_SHARED_s_CANNOT_REDEF, name.AddressOf());
  1762. WriteError(str, file, n);
  1763. }
  1764. else if (!isExternal && n->next && n->next->tokenType == ttEndStatement)
  1765. {
  1766. asCString str;
  1767. str.Format(TXT_MISSING_DEFINITION_OF_s, name.AddressOf());
  1768. WriteError(str, file, n);
  1769. }
  1770. // If this type is shared and there already exist another shared
  1771. // type of the same name, then that one should be used instead of
  1772. // creating a new one.
  1773. if( isShared )
  1774. {
  1775. for( asUINT i = 0; i < engine->sharedScriptTypes.GetLength(); i++ )
  1776. {
  1777. asCObjectType *st = CastToObjectType(engine->sharedScriptTypes[i]);
  1778. if( st &&
  1779. st->IsShared() &&
  1780. st->name == name &&
  1781. st->nameSpace == ns &&
  1782. st->IsInterface() )
  1783. {
  1784. // We'll use the existing type
  1785. decl->isExistingShared = true;
  1786. decl->typeInfo = st;
  1787. module->classTypes.PushLast(st);
  1788. st->AddRefInternal();
  1789. // Remember if the interface was declared as external so the saved bytecode can be flagged accordingly
  1790. if (isExternal)
  1791. module->externalTypes.PushLast(st);
  1792. return 0;
  1793. }
  1794. }
  1795. }
  1796. // If the interface was declared as external then it must have been compiled in a different module first
  1797. if (isExternal)
  1798. {
  1799. asCString str;
  1800. str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, name.AddressOf());
  1801. WriteError(str, file, n);
  1802. }
  1803. // Register the object type for the interface
  1804. asCObjectType *st = asNEW(asCObjectType)(engine);
  1805. if( st == 0 )
  1806. return asOUT_OF_MEMORY;
  1807. st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT;
  1808. if( isShared )
  1809. st->flags |= asOBJ_SHARED;
  1810. st->size = 0; // Cannot be instantiated
  1811. st->name = name;
  1812. st->nameSpace = ns;
  1813. st->module = module;
  1814. module->classTypes.PushLast(st);
  1815. if( isShared )
  1816. {
  1817. engine->sharedScriptTypes.PushLast(st);
  1818. st->AddRefInternal();
  1819. }
  1820. decl->typeInfo = st;
  1821. // Use the default script class behaviours
  1822. st->beh.construct = 0;
  1823. st->beh.addref = engine->scriptTypeBehaviours.beh.addref;
  1824. engine->scriptFunctions[st->beh.addref]->AddRefInternal();
  1825. st->beh.release = engine->scriptTypeBehaviours.beh.release;
  1826. engine->scriptFunctions[st->beh.release]->AddRefInternal();
  1827. st->beh.copy = 0;
  1828. return 0;
  1829. }
  1830. void asCBuilder::CompileGlobalVariables()
  1831. {
  1832. bool compileSucceeded = true;
  1833. // Store state of compilation (errors, warning, output)
  1834. int currNumErrors = numErrors;
  1835. int currNumWarnings = numWarnings;
  1836. // Backup the original message stream
  1837. bool msgCallback = engine->msgCallback;
  1838. asSSystemFunctionInterface msgCallbackFunc = engine->msgCallbackFunc;
  1839. void *msgCallbackObj = engine->msgCallbackObj;
  1840. // Set the new temporary message stream
  1841. asCOutputBuffer outBuffer;
  1842. engine->SetMessageCallback(asMETHOD(asCOutputBuffer, Callback), &outBuffer, asCALL_THISCALL);
  1843. asCOutputBuffer finalOutput;
  1844. asCScriptFunction *initFunc = 0;
  1845. asCSymbolTable<asCGlobalProperty> initOrder;
  1846. // We first try to compile all the primitive global variables, and only after that
  1847. // compile the non-primitive global variables. This permits the constructors
  1848. // for the complex types to use the already initialized variables of primitive
  1849. // type. Note, we currently don't know which global variables are used in the
  1850. // constructors, so we cannot guarantee that variables of complex types are
  1851. // initialized in the correct order, so we won't reorder those.
  1852. bool compilingPrimitives = true;
  1853. // Compile each global variable
  1854. while( compileSucceeded )
  1855. {
  1856. compileSucceeded = false;
  1857. int accumErrors = 0;
  1858. int accumWarnings = 0;
  1859. // Restore state of compilation
  1860. finalOutput.Clear();
  1861. asCSymbolTable<sGlobalVariableDescription>::iterator it = globVariables.List();
  1862. for( ; it; it++ )
  1863. {
  1864. sGlobalVariableDescription *gvar = *it;
  1865. if( gvar->isCompiled )
  1866. continue;
  1867. asCByteCode init(engine);
  1868. numWarnings = 0;
  1869. numErrors = 0;
  1870. outBuffer.Clear();
  1871. // Skip this for now if we're not compiling complex types yet
  1872. if( compilingPrimitives && !gvar->datatype.IsPrimitive() )
  1873. continue;
  1874. if( gvar->declaredAtNode )
  1875. {
  1876. int r, c;
  1877. gvar->script->ConvertPosToRowCol(gvar->declaredAtNode->tokenPos, &r, &c);
  1878. asCString str = gvar->datatype.Format(gvar->ns);
  1879. str += " " + gvar->name;
  1880. str.Format(TXT_COMPILING_s, str.AddressOf());
  1881. WriteInfo(gvar->script->name, str, r, c, true);
  1882. }
  1883. if( gvar->isEnumValue )
  1884. {
  1885. int r;
  1886. if( gvar->initializationNode )
  1887. {
  1888. asCCompiler comp(engine);
  1889. asCScriptFunction func(engine, module, asFUNC_SCRIPT);
  1890. // Set the namespace that should be used during the compilation
  1891. func.nameSpace = gvar->datatype.GetTypeInfo()->nameSpace;
  1892. // Temporarily switch the type of the variable to int so it can be compiled properly
  1893. asCDataType saveType;
  1894. saveType = gvar->datatype;
  1895. gvar->datatype = asCDataType::CreatePrimitive(ttInt, true);
  1896. r = comp.CompileGlobalVariable(this, gvar->script, gvar->initializationNode, gvar, &func);
  1897. gvar->datatype = saveType;
  1898. // Make the function a dummy so it doesn't try to release objects while destroying the function
  1899. func.funcType = asFUNC_DUMMY;
  1900. }
  1901. else
  1902. {
  1903. r = 0;
  1904. // When there is no assignment the value is the last + 1
  1905. int enumVal = 0;
  1906. asCSymbolTable<sGlobalVariableDescription>::iterator prev_it = it;
  1907. prev_it--;
  1908. if( prev_it )
  1909. {
  1910. sGlobalVariableDescription *gvar2 = *prev_it;
  1911. if(gvar2->datatype == gvar->datatype )
  1912. {
  1913. enumVal = int(gvar2->constantValue) + 1;
  1914. if( !gvar2->isCompiled )
  1915. {
  1916. int row, col;
  1917. gvar->script->ConvertPosToRowCol(gvar->declaredAtNode->tokenPos, &row, &col);
  1918. asCString str = gvar->datatype.Format(gvar->ns);
  1919. str += " " + gvar->name;
  1920. str.Format(TXT_COMPILING_s, str.AddressOf());
  1921. WriteInfo(gvar->script->name, str, row, col, true);
  1922. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, gvar2->name.AddressOf());
  1923. WriteError(gvar->script->name, str, row, col);
  1924. r = -1;
  1925. }
  1926. }
  1927. }
  1928. gvar->constantValue = enumVal;
  1929. }
  1930. if( r >= 0 )
  1931. {
  1932. // Set the value as compiled
  1933. gvar->isCompiled = true;
  1934. compileSucceeded = true;
  1935. }
  1936. }
  1937. else
  1938. {
  1939. // Compile the global variable
  1940. initFunc = asNEW(asCScriptFunction)(engine, module, asFUNC_SCRIPT);
  1941. if( initFunc == 0 )
  1942. {
  1943. // Out of memory
  1944. return;
  1945. }
  1946. // Set the namespace that should be used for this function
  1947. initFunc->nameSpace = gvar->ns;
  1948. asCCompiler comp(engine);
  1949. int r = comp.CompileGlobalVariable(this, gvar->script, gvar->initializationNode, gvar, initFunc);
  1950. if( r >= 0 )
  1951. {
  1952. // Compilation succeeded
  1953. gvar->isCompiled = true;
  1954. compileSucceeded = true;
  1955. }
  1956. else
  1957. {
  1958. // Compilation failed
  1959. initFunc->funcType = asFUNC_DUMMY;
  1960. asDELETE(initFunc, asCScriptFunction);
  1961. initFunc = 0;
  1962. }
  1963. }
  1964. if( gvar->isCompiled )
  1965. {
  1966. // Add warnings for this constant to the total build
  1967. if( numWarnings )
  1968. {
  1969. currNumWarnings += numWarnings;
  1970. if( msgCallback )
  1971. outBuffer.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj);
  1972. }
  1973. // Determine order of variable initializations
  1974. if( gvar->property && !gvar->isEnumValue )
  1975. initOrder.Put(gvar->property);
  1976. // Does the function contain more than just a SUSPEND followed by a RET instruction?
  1977. if( initFunc && initFunc->scriptData->byteCode.GetLength() > 2 )
  1978. {
  1979. // Create the init function for this variable
  1980. initFunc->id = engine->GetNextScriptFunctionId();
  1981. engine->AddScriptFunction(initFunc);
  1982. // Finalize the init function for this variable
  1983. initFunc->returnType = asCDataType::CreatePrimitive(ttVoid, false);
  1984. initFunc->scriptData->scriptSectionIdx = engine->GetScriptSectionNameIndex(gvar->script->name.AddressOf());
  1985. if( gvar->declaredAtNode )
  1986. {
  1987. int row, col;
  1988. gvar->script->ConvertPosToRowCol(gvar->declaredAtNode->tokenPos, &row, &col);
  1989. initFunc->scriptData->declaredAt = (row & 0xFFFFF)|((col & 0xFFF)<<20);
  1990. }
  1991. gvar->property->SetInitFunc(initFunc);
  1992. initFunc->ReleaseInternal();
  1993. initFunc = 0;
  1994. }
  1995. else if( initFunc )
  1996. {
  1997. // Destroy the function as it won't be used
  1998. initFunc->funcType = asFUNC_DUMMY;
  1999. asDELETE(initFunc, asCScriptFunction);
  2000. initFunc = 0;
  2001. }
  2002. // Convert enums to true enum values, so subsequent compilations can access it as an enum
  2003. if( gvar->isEnumValue )
  2004. {
  2005. asCEnumType *enumType = CastToEnumType(gvar->datatype.GetTypeInfo());
  2006. asASSERT(NULL != enumType);
  2007. asSEnumValue *e = asNEW(asSEnumValue);
  2008. if( e == 0 )
  2009. {
  2010. // Out of memory
  2011. numErrors++;
  2012. return;
  2013. }
  2014. e->name = gvar->name;
  2015. e->value = int(gvar->constantValue);
  2016. enumType->enumValues.PushLast(e);
  2017. }
  2018. }
  2019. else
  2020. {
  2021. // Add output to final output
  2022. finalOutput.Append(outBuffer);
  2023. accumErrors += numErrors;
  2024. accumWarnings += numWarnings;
  2025. }
  2026. engine->preMessage.isSet = false;
  2027. }
  2028. if( !compileSucceeded )
  2029. {
  2030. if( compilingPrimitives )
  2031. {
  2032. // No more primitives could be compiled, so
  2033. // switch to compiling the complex variables
  2034. compilingPrimitives = false;
  2035. compileSucceeded = true;
  2036. }
  2037. else
  2038. {
  2039. // No more variables can be compiled
  2040. // Add errors and warnings to total build
  2041. currNumWarnings += accumWarnings;
  2042. currNumErrors += accumErrors;
  2043. if( msgCallback )
  2044. finalOutput.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj);
  2045. }
  2046. }
  2047. }
  2048. // Restore states
  2049. engine->msgCallback = msgCallback;
  2050. engine->msgCallbackFunc = msgCallbackFunc;
  2051. engine->msgCallbackObj = msgCallbackObj;
  2052. numWarnings = currNumWarnings;
  2053. numErrors = currNumErrors;
  2054. // Set the correct order of initialization
  2055. if( numErrors == 0 )
  2056. {
  2057. // If the length of the arrays are not the same, then this is the compilation
  2058. // of a single variable, in which case the initialization order of the previous
  2059. // variables must be preserved.
  2060. if( module->scriptGlobals.GetSize() == initOrder.GetSize() )
  2061. module->scriptGlobals.SwapWith(initOrder);
  2062. }
  2063. // Delete the enum expressions
  2064. asCSymbolTableIterator<sGlobalVariableDescription> it = globVariables.List();
  2065. while( it )
  2066. {
  2067. sGlobalVariableDescription *gvar = *it;
  2068. if( gvar->isEnumValue )
  2069. {
  2070. // Remove from symboltable. This has to be done prior to freeing the memeory
  2071. globVariables.Erase(it.GetIndex());
  2072. // Destroy the gvar property
  2073. if( gvar->declaredAtNode )
  2074. {
  2075. gvar->declaredAtNode->Destroy(engine);
  2076. gvar->declaredAtNode = 0;
  2077. }
  2078. if( gvar->initializationNode )
  2079. {
  2080. gvar->initializationNode->Destroy(engine);
  2081. gvar->initializationNode = 0;
  2082. }
  2083. if( gvar->property )
  2084. {
  2085. asDELETE(gvar->property, asCGlobalProperty);
  2086. gvar->property = 0;
  2087. }
  2088. asDELETE(gvar, sGlobalVariableDescription);
  2089. }
  2090. else
  2091. it++;
  2092. }
  2093. }
  2094. int asCBuilder::GetNamespaceAndNameFromNode(asCScriptNode *n, asCScriptCode *script, asSNameSpace *implicitNs, asSNameSpace *&outNs, asCString &outName)
  2095. {
  2096. // TODO: child funcdef: The node might be a snScope now
  2097. asASSERT( n->nodeType == snIdentifier );
  2098. // Get the optional scope from the node
  2099. // TODO: child funcdef: The parentType will be set if the scope is actually a type rather than a namespace
  2100. asSNameSpace *ns = GetNameSpaceFromNode(n->firstChild, script, implicitNs, 0);
  2101. if( ns == 0 )
  2102. return -1;
  2103. // Get the name
  2104. asCString name(&script->code[n->lastChild->tokenPos], n->lastChild->tokenLength);
  2105. outNs = ns;
  2106. outName = name;
  2107. return 0;
  2108. }
  2109. void asCBuilder::AddInterfaceFromMixinToClass(sClassDeclaration *decl, asCScriptNode *errNode, sMixinClass *mixin)
  2110. {
  2111. // Determine what interfaces that the mixin implements
  2112. asCScriptNode *node = mixin->node;
  2113. asASSERT(node->nodeType == snClass);
  2114. // Skip the name of the mixin
  2115. node = node->firstChild->next;
  2116. while( node && node->nodeType == snIdentifier )
  2117. {
  2118. bool ok = true;
  2119. asSNameSpace *ns;
  2120. asCString name;
  2121. if( GetNamespaceAndNameFromNode(node, mixin->script, mixin->ns, ns, name) < 0 )
  2122. ok = false;
  2123. else
  2124. {
  2125. // Find the object type for the interface
  2126. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  2127. // Check that the object type is an interface
  2128. if( objType && objType->IsInterface() )
  2129. {
  2130. // Only add the interface if the class doesn't already implement it
  2131. if( !decl->typeInfo->Implements(objType) )
  2132. AddInterfaceToClass(decl, errNode, objType);
  2133. }
  2134. else
  2135. {
  2136. WriteError(TXT_MIXIN_CLASS_CANNOT_INHERIT, mixin->script, node);
  2137. ok = false;
  2138. }
  2139. }
  2140. if( !ok )
  2141. {
  2142. // Remove this node so the error isn't reported again
  2143. asCScriptNode *delNode = node;
  2144. node = node->prev;
  2145. delNode->DisconnectParent();
  2146. delNode->Destroy(engine);
  2147. }
  2148. node = node->next;
  2149. }
  2150. }
  2151. void asCBuilder::AddInterfaceToClass(sClassDeclaration *decl, asCScriptNode *errNode, asCObjectType *intfType)
  2152. {
  2153. // A shared type may only implement from shared interfaces
  2154. if( decl->typeInfo->IsShared() && !intfType->IsShared() )
  2155. {
  2156. asCString msg;
  2157. msg.Format(TXT_SHARED_CANNOT_IMPLEMENT_NON_SHARED_s, intfType->name.AddressOf());
  2158. WriteError(msg, decl->script, errNode);
  2159. return;
  2160. }
  2161. if( decl->isExistingShared )
  2162. {
  2163. // If the class is an existing shared class, then just check if the
  2164. // interface exists in the original declaration too
  2165. if( !decl->typeInfo->Implements(intfType) )
  2166. {
  2167. asCString str;
  2168. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->typeInfo->GetName());
  2169. WriteError(str, decl->script, errNode);
  2170. return;
  2171. }
  2172. }
  2173. else
  2174. {
  2175. // If the interface is already in the class then don't add it again
  2176. if( decl->typeInfo->Implements(intfType) )
  2177. return;
  2178. // Add the interface to the class
  2179. CastToObjectType(decl->typeInfo)->interfaces.PushLast(intfType);
  2180. // Add the inherited interfaces too
  2181. // For interfaces this will be done outside to handle out-of-order declarations
  2182. if( !CastToObjectType(decl->typeInfo)->IsInterface() )
  2183. {
  2184. for( asUINT n = 0; n < intfType->interfaces.GetLength(); n++ )
  2185. AddInterfaceToClass(decl, errNode, intfType->interfaces[n]);
  2186. }
  2187. }
  2188. }
  2189. void asCBuilder::CompileInterfaces()
  2190. {
  2191. asUINT n;
  2192. // Order the interfaces with inheritances so that the inherited
  2193. // of inherited interfaces can be added properly
  2194. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  2195. {
  2196. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  2197. asCObjectType *intfType = CastToObjectType(intfDecl->typeInfo);
  2198. if( intfType->interfaces.GetLength() == 0 ) continue;
  2199. // If any of the derived interfaces are found after this interface, then move this to the end of the list
  2200. for( asUINT m = n+1; m < interfaceDeclarations.GetLength(); m++ )
  2201. {
  2202. if( intfType->Implements(interfaceDeclarations[m]->typeInfo) )
  2203. {
  2204. interfaceDeclarations.RemoveIndex(n);
  2205. interfaceDeclarations.PushLast(intfDecl);
  2206. // Decrease index so that we don't skip an entry
  2207. n--;
  2208. break;
  2209. }
  2210. }
  2211. }
  2212. // Now recursively add the additional inherited interfaces
  2213. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  2214. {
  2215. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  2216. asCObjectType *intfType = CastToObjectType(intfDecl->typeInfo);
  2217. // TODO: Is this really at the correct place? Hasn't the vfTableIdx already been set here?
  2218. // Co-opt the vfTableIdx value in our own methods to indicate the
  2219. // index the function should have in the table chunk for this interface.
  2220. for( asUINT d = 0; d < intfType->methods.GetLength(); d++ )
  2221. {
  2222. asCScriptFunction *func = GetFunctionDescription(intfType->methods[d]);
  2223. func->vfTableIdx = d;
  2224. asASSERT(func->objectType == intfType);
  2225. }
  2226. // As new interfaces will be added to the end of the list, all
  2227. // interfaces will be traversed the same as recursively
  2228. for( asUINT m = 0; m < intfType->interfaces.GetLength(); m++ )
  2229. {
  2230. asCObjectType *base = intfType->interfaces[m];
  2231. // Add any interfaces not already implemented
  2232. for( asUINT l = 0; l < base->interfaces.GetLength(); l++ )
  2233. AddInterfaceToClass(intfDecl, intfDecl->node, base->interfaces[l]);
  2234. // Add the methods from the implemented interface
  2235. for( asUINT l = 0; l < base->methods.GetLength(); l++ )
  2236. {
  2237. // If the derived interface implements the same method, then don't add the base interface' method
  2238. asCScriptFunction *baseFunc = GetFunctionDescription(base->methods[l]);
  2239. asCScriptFunction *derivedFunc = 0;
  2240. bool found = false;
  2241. for( asUINT d = 0; d < intfType->methods.GetLength(); d++ )
  2242. {
  2243. derivedFunc = GetFunctionDescription(intfType->methods[d]);
  2244. if( derivedFunc->IsSignatureEqual(baseFunc) )
  2245. {
  2246. found = true;
  2247. break;
  2248. }
  2249. }
  2250. if( !found )
  2251. {
  2252. // Add the method
  2253. intfType->methods.PushLast(baseFunc->id);
  2254. baseFunc->AddRefInternal();
  2255. }
  2256. }
  2257. }
  2258. }
  2259. }
  2260. void asCBuilder::DetermineTypeRelations()
  2261. {
  2262. // Determine inheritance between interfaces
  2263. for (asUINT n = 0; n < interfaceDeclarations.GetLength(); n++)
  2264. {
  2265. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  2266. asCObjectType *intfType = CastToObjectType(intfDecl->typeInfo);
  2267. asCScriptNode *node = intfDecl->node;
  2268. asASSERT(node && node->nodeType == snInterface);
  2269. node = node->firstChild;
  2270. // Skip the 'shared' & 'external' keywords
  2271. while( node->nodeType == snIdentifier &&
  2272. (intfDecl->script->TokenEquals(node->tokenPos, node->tokenLength, SHARED_TOKEN) ||
  2273. intfDecl->script->TokenEquals(node->tokenPos, node->tokenLength, EXTERNAL_TOKEN)) )
  2274. node = node->next;
  2275. // Skip the name
  2276. node = node->next;
  2277. // Verify the inherited interfaces
  2278. while (node && node->nodeType == snIdentifier)
  2279. {
  2280. asSNameSpace *ns;
  2281. asCString name;
  2282. if (GetNamespaceAndNameFromNode(node, intfDecl->script, intfType->nameSpace, ns, name) < 0)
  2283. {
  2284. node = node->next;
  2285. continue;
  2286. }
  2287. // Find the object type for the interface
  2288. asCObjectType *objType = 0;
  2289. while (ns)
  2290. {
  2291. objType = GetObjectType(name.AddressOf(), ns);
  2292. if (objType) break;
  2293. ns = engine->GetParentNameSpace(ns);
  2294. }
  2295. // Check that the object type is an interface
  2296. bool ok = true;
  2297. if (objType && objType->IsInterface())
  2298. {
  2299. // Check that the implemented interface is shared if the base interface is shared
  2300. if (intfType->IsShared() && !objType->IsShared())
  2301. {
  2302. asCString str;
  2303. str.Format(TXT_SHARED_CANNOT_IMPLEMENT_NON_SHARED_s, objType->GetName());
  2304. WriteError(str, intfDecl->script, node);
  2305. ok = false;
  2306. }
  2307. }
  2308. else
  2309. {
  2310. WriteError(TXT_INTERFACE_CAN_ONLY_IMPLEMENT_INTERFACE, intfDecl->script, node);
  2311. ok = false;
  2312. }
  2313. if (ok)
  2314. {
  2315. // Make sure none of the implemented interfaces implement from this one
  2316. asCObjectType *base = objType;
  2317. while (base != 0)
  2318. {
  2319. if (base == intfType)
  2320. {
  2321. WriteError(TXT_CANNOT_IMPLEMENT_SELF, intfDecl->script, node);
  2322. ok = false;
  2323. break;
  2324. }
  2325. // At this point there is at most one implemented interface
  2326. if (base->interfaces.GetLength())
  2327. base = base->interfaces[0];
  2328. else
  2329. break;
  2330. }
  2331. }
  2332. if (ok)
  2333. AddInterfaceToClass(intfDecl, node, objType);
  2334. // Remove the nodes so they aren't parsed again
  2335. asCScriptNode *delNode = node;
  2336. node = node->next;
  2337. delNode->DisconnectParent();
  2338. delNode->Destroy(engine);
  2339. }
  2340. }
  2341. // Determine class inheritances and interfaces
  2342. for (asUINT n = 0; n < classDeclarations.GetLength(); n++)
  2343. {
  2344. sClassDeclaration *decl = classDeclarations[n];
  2345. asCScriptCode *file = decl->script;
  2346. // Find the base class that this class inherits from
  2347. bool multipleInheritance = false;
  2348. asCScriptNode *node = decl->node->firstChild;
  2349. while (file->TokenEquals(node->tokenPos, node->tokenLength, FINAL_TOKEN) ||
  2350. file->TokenEquals(node->tokenPos, node->tokenLength, SHARED_TOKEN) ||
  2351. file->TokenEquals(node->tokenPos, node->tokenLength, ABSTRACT_TOKEN) ||
  2352. file->TokenEquals(node->tokenPos, node->tokenLength, EXTERNAL_TOKEN))
  2353. {
  2354. node = node->next;
  2355. }
  2356. // Skip the name of the class
  2357. asASSERT(node->tokenType == ttIdentifier);
  2358. node = node->next;
  2359. while (node && node->nodeType == snIdentifier)
  2360. {
  2361. asSNameSpace *ns;
  2362. asCString name;
  2363. if (GetNamespaceAndNameFromNode(node, file, decl->typeInfo->nameSpace, ns, name) < 0)
  2364. {
  2365. node = node->next;
  2366. continue;
  2367. }
  2368. // Find the object type for the interface
  2369. asCObjectType *objType = 0;
  2370. sMixinClass *mixin = 0;
  2371. asSNameSpace *origNs = ns;
  2372. while (ns)
  2373. {
  2374. objType = GetObjectType(name.AddressOf(), ns);
  2375. if (objType == 0)
  2376. mixin = GetMixinClass(name.AddressOf(), ns);
  2377. if (objType || mixin)
  2378. break;
  2379. ns = engine->GetParentNameSpace(ns);
  2380. }
  2381. if (objType == 0 && mixin == 0)
  2382. {
  2383. asCString str;
  2384. if (origNs->name == "")
  2385. str.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_GLOBAL_NS, name.AddressOf());
  2386. else
  2387. str.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_NS_s, name.AddressOf(), origNs->name.AddressOf());
  2388. WriteError(str, file, node);
  2389. }
  2390. else if (mixin)
  2391. {
  2392. AddInterfaceFromMixinToClass(decl, node, mixin);
  2393. }
  2394. else if (!(objType->flags & asOBJ_SCRIPT_OBJECT) ||
  2395. (objType->flags & asOBJ_NOINHERIT))
  2396. {
  2397. // Either the class is not a script class or interface
  2398. // or the class has been declared as 'final'
  2399. asCString str;
  2400. str.Format(TXT_CANNOT_INHERIT_FROM_s_FINAL, objType->name.AddressOf());
  2401. WriteError(str, file, node);
  2402. }
  2403. else if (objType->size != 0)
  2404. {
  2405. // The class inherits from another script class
  2406. if (!decl->isExistingShared && CastToObjectType(decl->typeInfo)->derivedFrom != 0)
  2407. {
  2408. if (!multipleInheritance)
  2409. {
  2410. WriteError(TXT_CANNOT_INHERIT_FROM_MULTIPLE_CLASSES, file, node);
  2411. multipleInheritance = true;
  2412. }
  2413. }
  2414. else
  2415. {
  2416. // Make sure none of the base classes inherit from this one
  2417. asCObjectType *base = objType;
  2418. bool error = false;
  2419. while (base != 0)
  2420. {
  2421. if (base == decl->typeInfo)
  2422. {
  2423. WriteError(TXT_CANNOT_INHERIT_FROM_SELF, file, node);
  2424. error = true;
  2425. break;
  2426. }
  2427. base = base->derivedFrom;
  2428. }
  2429. if (!error)
  2430. {
  2431. // A shared type may only inherit from other shared types
  2432. if ((decl->typeInfo->IsShared()) && !(objType->IsShared()))
  2433. {
  2434. asCString msg;
  2435. msg.Format(TXT_SHARED_CANNOT_INHERIT_FROM_NON_SHARED_s, objType->name.AddressOf());
  2436. WriteError(msg, file, node);
  2437. error = true;
  2438. }
  2439. }
  2440. if (!error)
  2441. {
  2442. if (decl->isExistingShared)
  2443. {
  2444. // Verify that the base class is the same as the original shared type
  2445. if (CastToObjectType(decl->typeInfo)->derivedFrom != objType)
  2446. {
  2447. asCString str;
  2448. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->typeInfo->GetName());
  2449. WriteError(str, file, node);
  2450. }
  2451. }
  2452. else
  2453. {
  2454. // Set the base class
  2455. CastToObjectType(decl->typeInfo)->derivedFrom = objType;
  2456. objType->AddRefInternal();
  2457. }
  2458. }
  2459. }
  2460. }
  2461. else
  2462. {
  2463. // The class implements an interface
  2464. AddInterfaceToClass(decl, node, objType);
  2465. }
  2466. node = node->next;
  2467. }
  2468. }
  2469. }
  2470. // numTempl is the number of template instances that existed in the engine before the build begun
  2471. void asCBuilder::CompileClasses(asUINT numTempl)
  2472. {
  2473. asUINT n;
  2474. asCArray<sClassDeclaration*> toValidate((int)classDeclarations.GetLength());
  2475. // Order class declarations so that base classes are compiled before derived classes.
  2476. // This will allow the derived classes to copy properties and methods in the next step.
  2477. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2478. {
  2479. sClassDeclaration *decl = classDeclarations[n];
  2480. asCObjectType *derived = CastToObjectType(decl->typeInfo);
  2481. asCObjectType *base = derived->derivedFrom;
  2482. if( base == 0 ) continue;
  2483. // If the base class is found after the derived class, then move the derived class to the end of the list
  2484. for( asUINT m = n+1; m < classDeclarations.GetLength(); m++ )
  2485. {
  2486. sClassDeclaration *declBase = classDeclarations[m];
  2487. if( base == declBase->typeInfo )
  2488. {
  2489. classDeclarations.RemoveIndex(n);
  2490. classDeclarations.PushLast(decl);
  2491. // Decrease index so that we don't skip an entry
  2492. n--;
  2493. break;
  2494. }
  2495. }
  2496. }
  2497. // Go through each of the classes and register the object type descriptions
  2498. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2499. {
  2500. sClassDeclaration *decl = classDeclarations[n];
  2501. asCObjectType *ot = CastToObjectType(decl->typeInfo);
  2502. if( decl->isExistingShared )
  2503. {
  2504. // Set the declaration as validated already, so that other
  2505. // types that contain this will accept this type
  2506. decl->validState = 1;
  2507. // We'll still validate the declaration to make sure nothing new is
  2508. // added to the shared class that wasn't there in the previous
  2509. // compilation. We do not care if something that is there in the previous
  2510. // declaration is not included in the new declaration though.
  2511. asASSERT( ot->interfaces.GetLength() == ot->interfaceVFTOffsets.GetLength() );
  2512. }
  2513. // Methods included from mixin classes should take precedence over inherited methods
  2514. IncludeMethodsFromMixins(decl);
  2515. // Add all properties and methods from the base class
  2516. if( !decl->isExistingShared && ot->derivedFrom )
  2517. {
  2518. asCObjectType *baseType = ot->derivedFrom;
  2519. // The derived class inherits all interfaces from the base class
  2520. for( unsigned int m = 0; m < baseType->interfaces.GetLength(); m++ )
  2521. {
  2522. if( !ot->Implements(baseType->interfaces[m]) )
  2523. ot->interfaces.PushLast(baseType->interfaces[m]);
  2524. }
  2525. // TODO: Need to check for name conflict with new class methods
  2526. // Copy properties from base class to derived class
  2527. for( asUINT p = 0; p < baseType->properties.GetLength(); p++ )
  2528. {
  2529. asCObjectProperty *prop = AddPropertyToClass(decl, baseType->properties[p]->name, baseType->properties[p]->type, baseType->properties[p]->isPrivate, baseType->properties[p]->isProtected, true);
  2530. // The properties must maintain the same offset
  2531. asASSERT(prop && prop->byteOffset == baseType->properties[p]->byteOffset); UNUSED_VAR(prop);
  2532. }
  2533. // Copy methods from base class to derived class
  2534. for( asUINT m = 0; m < baseType->methods.GetLength(); m++ )
  2535. {
  2536. // If the derived class implements the same method, then don't add the base class' method
  2537. asCScriptFunction *baseFunc = GetFunctionDescription(baseType->methods[m]);
  2538. asCScriptFunction *derivedFunc = 0;
  2539. bool found = false;
  2540. for( asUINT d = 0; d < ot->methods.GetLength(); d++ )
  2541. {
  2542. derivedFunc = GetFunctionDescription(ot->methods[d]);
  2543. if( baseFunc->name == "opConv" || baseFunc->name == "opImplConv" ||
  2544. baseFunc->name == "opCast" || baseFunc->name == "opImplCast" )
  2545. {
  2546. // For the opConv and opCast methods, the return type can differ if they are different methods
  2547. if( derivedFunc->name == baseFunc->name &&
  2548. derivedFunc->IsSignatureExceptNameEqual(baseFunc) )
  2549. {
  2550. if( baseFunc->IsFinal() )
  2551. {
  2552. asCString msg;
  2553. msg.Format(TXT_METHOD_CANNOT_OVERRIDE_s, baseFunc->GetDeclaration());
  2554. WriteError(msg, decl->script, decl->node);
  2555. }
  2556. // Move the function from the methods array to the virtualFunctionTable
  2557. ot->methods.RemoveIndex(d);
  2558. ot->virtualFunctionTable.PushLast(derivedFunc);
  2559. found = true;
  2560. break;
  2561. }
  2562. }
  2563. else
  2564. {
  2565. if( derivedFunc->name == baseFunc->name &&
  2566. derivedFunc->IsSignatureExceptNameAndReturnTypeEqual(baseFunc) )
  2567. {
  2568. if( baseFunc->returnType != derivedFunc->returnType )
  2569. {
  2570. asCString msg;
  2571. msg.Format(TXT_DERIVED_METHOD_MUST_HAVE_SAME_RETTYPE_s, baseFunc->GetDeclaration());
  2572. WriteError(msg, decl->script, decl->node);
  2573. }
  2574. if( baseFunc->IsFinal() )
  2575. {
  2576. asCString msg;
  2577. msg.Format(TXT_METHOD_CANNOT_OVERRIDE_s, baseFunc->GetDeclaration());
  2578. WriteError(msg, decl->script, decl->node);
  2579. }
  2580. // Move the function from the methods array to the virtualFunctionTable
  2581. ot->methods.RemoveIndex(d);
  2582. ot->virtualFunctionTable.PushLast(derivedFunc);
  2583. found = true;
  2584. break;
  2585. }
  2586. }
  2587. }
  2588. if( !found )
  2589. {
  2590. // Push the base class function on the virtual function table
  2591. ot->virtualFunctionTable.PushLast(baseType->virtualFunctionTable[m]);
  2592. baseType->virtualFunctionTable[m]->AddRefInternal();
  2593. CheckForConflictsDueToDefaultArgs(decl->script, decl->node, baseType->virtualFunctionTable[m], ot);
  2594. }
  2595. ot->methods.PushLast(baseType->methods[m]);
  2596. engine->scriptFunctions[baseType->methods[m]]->AddRefInternal();
  2597. }
  2598. }
  2599. if( !decl->isExistingShared )
  2600. {
  2601. // Move this class' methods into the virtual function table
  2602. for( asUINT m = 0; m < ot->methods.GetLength(); m++ )
  2603. {
  2604. asCScriptFunction *func = GetFunctionDescription(ot->methods[m]);
  2605. if( func->funcType != asFUNC_VIRTUAL )
  2606. {
  2607. // Move the reference from the method list to the virtual function list
  2608. ot->methods.RemoveIndex(m);
  2609. ot->virtualFunctionTable.PushLast(func);
  2610. // Substitute the function description in the method list for a virtual method
  2611. // Make sure the methods are in the same order as the virtual function table
  2612. ot->methods.PushLast(CreateVirtualFunction(func, (int)ot->virtualFunctionTable.GetLength() - 1));
  2613. m--;
  2614. }
  2615. }
  2616. // Make virtual function table chunks for each implemented interface
  2617. for( asUINT m = 0; m < ot->interfaces.GetLength(); m++ )
  2618. {
  2619. asCObjectType *intf = ot->interfaces[m];
  2620. // Add all the interface's functions to the virtual function table
  2621. asUINT offset = asUINT(ot->virtualFunctionTable.GetLength());
  2622. ot->interfaceVFTOffsets.PushLast(offset);
  2623. for( asUINT j = 0; j < intf->methods.GetLength(); j++ )
  2624. {
  2625. asCScriptFunction *intfFunc = GetFunctionDescription(intf->methods[j]);
  2626. // Only create the table for functions that are explicitly from this interface,
  2627. // inherited interface methods will be put in that interface's table.
  2628. if( intfFunc->objectType != intf )
  2629. continue;
  2630. asASSERT((asUINT)intfFunc->vfTableIdx == j);
  2631. //Find the interface function in the list of methods
  2632. asCScriptFunction *realFunc = 0;
  2633. for( asUINT p = 0; p < ot->methods.GetLength(); p++ )
  2634. {
  2635. asCScriptFunction *func = GetFunctionDescription(ot->methods[p]);
  2636. if( func->signatureId == intfFunc->signatureId )
  2637. {
  2638. if( func->funcType == asFUNC_VIRTUAL )
  2639. {
  2640. realFunc = ot->virtualFunctionTable[func->vfTableIdx];
  2641. }
  2642. else
  2643. {
  2644. // This should not happen, all methods were moved into the virtual table
  2645. asASSERT(false);
  2646. }
  2647. break;
  2648. }
  2649. }
  2650. // If realFunc is still null, the interface was not
  2651. // implemented and we error out later in the checks.
  2652. ot->virtualFunctionTable.PushLast(realFunc);
  2653. if( realFunc )
  2654. realFunc->AddRefInternal();
  2655. }
  2656. }
  2657. }
  2658. // Enumerate each of the declared properties
  2659. asCScriptNode *node = decl->node->firstChild->next;
  2660. // Skip list of classes and interfaces
  2661. while( node && node->nodeType == snIdentifier )
  2662. node = node->next;
  2663. while( node && node->nodeType == snDeclaration )
  2664. {
  2665. asCScriptNode *nd = node->firstChild;
  2666. // Is the property declared as private or protected?
  2667. bool isPrivate = false, isProtected = false;
  2668. if( nd && nd->tokenType == ttPrivate )
  2669. {
  2670. isPrivate = true;
  2671. nd = nd->next;
  2672. }
  2673. else if( nd && nd->tokenType == ttProtected )
  2674. {
  2675. isProtected = true;
  2676. nd = nd->next;
  2677. }
  2678. // Determine the type of the property
  2679. asCScriptCode *file = decl->script;
  2680. asCDataType dt = CreateDataTypeFromNode(nd, file, ot->nameSpace, false, ot);
  2681. if( ot->IsShared() && dt.GetTypeInfo() && !dt.GetTypeInfo()->IsShared() )
  2682. {
  2683. asCString msg;
  2684. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetTypeInfo()->name.AddressOf());
  2685. WriteError(msg, file, node);
  2686. }
  2687. if( dt.IsReadOnly() )
  2688. WriteError(TXT_PROPERTY_CANT_BE_CONST, file, node);
  2689. // Multiple properties can be declared separated by ,
  2690. nd = nd->next;
  2691. while( nd )
  2692. {
  2693. asCString name(&file->code[nd->tokenPos], nd->tokenLength);
  2694. if( !decl->isExistingShared )
  2695. {
  2696. CheckNameConflictMember(ot, name.AddressOf(), nd, file, true);
  2697. AddPropertyToClass(decl, name, dt, isPrivate, isProtected, false, file, nd);
  2698. }
  2699. else
  2700. {
  2701. // Verify that the property exists in the original declaration
  2702. bool found = false;
  2703. for( asUINT p = 0; p < ot->properties.GetLength(); p++ )
  2704. {
  2705. asCObjectProperty *prop = ot->properties[p];
  2706. if( prop->isPrivate == isPrivate &&
  2707. prop->isProtected == isProtected &&
  2708. prop->name == name &&
  2709. prop->type.IsEqualExceptRef(dt) )
  2710. {
  2711. found = true;
  2712. break;
  2713. }
  2714. }
  2715. if( !found )
  2716. {
  2717. asCString str;
  2718. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, ot->GetName());
  2719. WriteError(str, file, nd);
  2720. }
  2721. }
  2722. // Skip the initialization node
  2723. if( nd->next && nd->next->nodeType != snIdentifier )
  2724. nd = nd->next;
  2725. nd = nd->next;
  2726. }
  2727. node = node->next;
  2728. }
  2729. // Add properties from included mixin classes that don't conflict with existing properties
  2730. IncludePropertiesFromMixins(decl);
  2731. if( !decl->isExistingShared )
  2732. toValidate.PushLast(decl);
  2733. asASSERT( ot->interfaces.GetLength() == ot->interfaceVFTOffsets.GetLength() );
  2734. }
  2735. // TODO: Warn if a method overrides a base method without marking it as 'override'.
  2736. // It must be possible to turn off this warning through engine property.
  2737. // TODO: A base class should be able to mark a method as 'abstract'. This will
  2738. // allow a base class to provide a partial implementation, but still force
  2739. // derived classes to implement specific methods.
  2740. // Verify that all interface methods are implemented in the classes
  2741. // We do this here so the base class' methods have already been inherited
  2742. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2743. {
  2744. sClassDeclaration *decl = classDeclarations[n];
  2745. if( decl->isExistingShared ) continue;
  2746. asCObjectType *ot = CastToObjectType(decl->typeInfo);
  2747. asCArray<bool> overrideValidations(ot->GetMethodCount());
  2748. for( asUINT k = 0; k < ot->methods.GetLength(); k++ )
  2749. overrideValidations.PushLast( !static_cast<asCScriptFunction*>(ot->GetMethodByIndex(k, false))->IsOverride() );
  2750. for( asUINT m = 0; m < ot->interfaces.GetLength(); m++ )
  2751. {
  2752. asCObjectType *objType = ot->interfaces[m];
  2753. for( asUINT i = 0; i < objType->methods.GetLength(); i++ )
  2754. {
  2755. // Only check the interface methods that was explicitly declared in this interface
  2756. // Methods that was inherited from other interfaces will be checked in those interfaces
  2757. if( objType != engine->scriptFunctions[objType->methods[i]]->objectType )
  2758. continue;
  2759. asUINT overrideIndex;
  2760. if( !DoesMethodExist(ot, objType->methods[i], &overrideIndex) )
  2761. {
  2762. asCString str;
  2763. str.Format(TXT_MISSING_IMPLEMENTATION_OF_s,
  2764. engine->GetFunctionDeclaration(objType->methods[i]).AddressOf());
  2765. WriteError(str, decl->script, decl->node);
  2766. }
  2767. else
  2768. overrideValidations[overrideIndex] = true;
  2769. }
  2770. }
  2771. bool hasBaseClass = ot->derivedFrom != 0;
  2772. for( asUINT j = 0; j < overrideValidations.GetLength(); j++ )
  2773. {
  2774. if( !overrideValidations[j] && (!hasBaseClass || !DoesMethodExist(ot->derivedFrom, ot->methods[j])) )
  2775. {
  2776. asCString msg;
  2777. msg.Format(TXT_METHOD_s_DOES_NOT_OVERRIDE, ot->GetMethodByIndex(j, false)->GetDeclaration());
  2778. WriteError(msg, decl->script, decl->node);
  2779. }
  2780. }
  2781. }
  2782. // Verify that the declared structures are valid, e.g. that the structure
  2783. // doesn't contain a member of its own type directly or indirectly
  2784. while( toValidate.GetLength() > 0 )
  2785. {
  2786. asUINT numClasses = (asUINT)toValidate.GetLength();
  2787. asCArray<sClassDeclaration*> toValidateNext((int)toValidate.GetLength());
  2788. while( toValidate.GetLength() > 0 )
  2789. {
  2790. sClassDeclaration *decl = toValidate[toValidate.GetLength()-1];
  2791. asCObjectType *ot = CastToObjectType(decl->typeInfo);
  2792. int validState = 1;
  2793. for( n = 0; n < ot->properties.GetLength(); n++ )
  2794. {
  2795. // A valid structure is one that uses only primitives or other valid objects
  2796. asCObjectProperty *prop = ot->properties[n];
  2797. asCDataType dt = prop->type;
  2798. // TODO: Add this check again, once solving the issues commented below
  2799. /*
  2800. if( dt.IsTemplate() )
  2801. {
  2802. // TODO: This must verify all sub types, not just the first one
  2803. // TODO: Just because the subtype is not a handle doesn't mean the template will actually instance the object
  2804. // this it shouldn't automatically raise an error for this, e.g. weakref<Object> should be legal as member
  2805. // of the Object class
  2806. asCDataType sub = dt;
  2807. while( sub.IsTemplate() && !sub.IsObjectHandle() )
  2808. sub = sub.GetSubType();
  2809. dt = sub;
  2810. }
  2811. */
  2812. if( dt.IsObject() && !dt.IsObjectHandle() )
  2813. {
  2814. // Find the class declaration
  2815. sClassDeclaration *pdecl = 0;
  2816. for( asUINT p = 0; p < classDeclarations.GetLength(); p++ )
  2817. {
  2818. if( classDeclarations[p]->typeInfo == dt.GetTypeInfo() )
  2819. {
  2820. pdecl = classDeclarations[p];
  2821. break;
  2822. }
  2823. }
  2824. if( pdecl )
  2825. {
  2826. if( pdecl->typeInfo == decl->typeInfo )
  2827. {
  2828. WriteError(TXT_ILLEGAL_MEMBER_TYPE, decl->script, decl->node);
  2829. validState = 2;
  2830. break;
  2831. }
  2832. else if( pdecl->validState != 1 )
  2833. {
  2834. validState = pdecl->validState;
  2835. break;
  2836. }
  2837. }
  2838. }
  2839. }
  2840. if( validState == 1 )
  2841. {
  2842. decl->validState = 1;
  2843. toValidate.PopLast();
  2844. }
  2845. else if( validState == 2 )
  2846. {
  2847. decl->validState = 2;
  2848. toValidate.PopLast();
  2849. }
  2850. else
  2851. {
  2852. toValidateNext.PushLast(toValidate.PopLast());
  2853. }
  2854. }
  2855. toValidate = toValidateNext;
  2856. toValidateNext.SetLength(0);
  2857. if( numClasses == toValidate.GetLength() )
  2858. {
  2859. WriteError(TXT_ILLEGAL_MEMBER_TYPE, toValidate[0]->script, toValidate[0]->node);
  2860. break;
  2861. }
  2862. }
  2863. if( numErrors > 0 ) return;
  2864. // Verify which script classes can really form circular references, and mark only those as garbage collected.
  2865. // This must be done in the correct order, so that a class that contains another class isn't needlessly marked
  2866. // as garbage collected, just because the contained class was evaluated afterwards.
  2867. // TODO: runtime optimize: This algorithm can be further improved by checking the types that inherits from
  2868. // a base class. If the base class is not shared all the classes that derive from it
  2869. // are known at compile time, and can thus be checked for potential circular references too.
  2870. //
  2871. // Observe, that doing this would conflict with another potential future feature, which is to
  2872. // allow incremental builds, i.e. allow application to add or replace classes in an
  2873. // existing module. However, the applications that want to use that should use a special
  2874. // build flag to not finalize the module.
  2875. // Urho3D: disable garbage collection from script classes
  2876. /*
  2877. asCArray<asCObjectType*> typesToValidate;
  2878. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2879. {
  2880. // Existing shared classes won't need evaluating, nor interfaces
  2881. sClassDeclaration *decl = classDeclarations[n];
  2882. if( decl->isExistingShared ) continue;
  2883. asCObjectType *ot = CastToObjectType(decl->typeInfo);
  2884. if( ot->IsInterface() ) continue;
  2885. typesToValidate.PushLast(ot);
  2886. }
  2887. asUINT numReevaluations = 0;
  2888. while( typesToValidate.GetLength() )
  2889. {
  2890. if( numReevaluations > typesToValidate.GetLength() )
  2891. {
  2892. // No types could be completely evaluated in the last iteration so
  2893. // we consider the remaining types in the array as garbage collected
  2894. break;
  2895. }
  2896. asCObjectType *type = typesToValidate[0];
  2897. typesToValidate.RemoveIndex(0);
  2898. // If the type inherits from another type that is yet to be validated, then reinsert it at the end
  2899. if( type->derivedFrom && typesToValidate.Exists(type->derivedFrom) )
  2900. {
  2901. typesToValidate.PushLast(type);
  2902. numReevaluations++;
  2903. continue;
  2904. }
  2905. // If the type inherits from a known garbage collected type, then this type must also be garbage collected
  2906. if( type->derivedFrom && (type->derivedFrom->flags & asOBJ_GC) )
  2907. {
  2908. type->flags |= asOBJ_GC;
  2909. continue;
  2910. }
  2911. // Evaluate template instances (silently) before verifying each of the classes, since it is possible that
  2912. // a class will be marked as non-garbage collected, which in turn will mark the template instance that uses
  2913. // it as non-garbage collected, which in turn means the class that contains the array also do not have to be
  2914. // garbage collected
  2915. EvaluateTemplateInstances(numTempl, true);
  2916. // Is there some path in which this structure is involved in circular references?
  2917. // If the type contains a member of a type that is yet to be validated, then reinsert it at the end
  2918. bool mustReevaluate = false;
  2919. bool gc = false;
  2920. for( asUINT p = 0; p < type->properties.GetLength(); p++ )
  2921. {
  2922. asCDataType dt = type->properties[p]->type;
  2923. if (dt.IsFuncdef())
  2924. {
  2925. // If a class holds a function pointer as member then the class must be garbage collected as the
  2926. // function pointer can form circular references with the class through use of a delegate. Example:
  2927. //
  2928. // class A { B @b; void f(); }
  2929. // class B { F @f; }
  2930. // funcdef void F();
  2931. //
  2932. // A a;
  2933. // @a.b = B(); // instance of A refers to instance of B
  2934. // @a.b.f = F(a.f); // instance of B refers to delegate that refers to instance of A
  2935. //
  2936. gc = true;
  2937. break;
  2938. }
  2939. if( !dt.IsObject() )
  2940. continue;
  2941. if( typesToValidate.Exists(CastToObjectType(dt.GetTypeInfo())) )
  2942. mustReevaluate = true;
  2943. else
  2944. {
  2945. if( dt.IsTemplate() )
  2946. {
  2947. // Check if any of the subtypes are yet to be evaluated
  2948. bool skip = false;
  2949. for( asUINT s = 0; s < dt.GetTypeInfo()->GetSubTypeCount(); s++ )
  2950. {
  2951. asCObjectType *t = reinterpret_cast<asCObjectType*>(dt.GetTypeInfo()->GetSubType(s));
  2952. if( typesToValidate.Exists(t) )
  2953. {
  2954. mustReevaluate = true;
  2955. skip = true;
  2956. break;
  2957. }
  2958. }
  2959. if( skip )
  2960. continue;
  2961. }
  2962. if( dt.IsObjectHandle() )
  2963. {
  2964. // If it is known that the handle can't be involved in a circular reference
  2965. // then this object doesn't need to be marked as garbage collected.
  2966. asCObjectType *prop = CastToObjectType(dt.GetTypeInfo());
  2967. if( prop->flags & asOBJ_SCRIPT_OBJECT )
  2968. {
  2969. // For script objects, treat non-final classes as if they can contain references
  2970. // as it is not known what derived classes might do. For final types, check all
  2971. // properties to determine if any of those can cause a circular reference with this
  2972. // class.
  2973. if( prop->flags & asOBJ_NOINHERIT )
  2974. {
  2975. for( asUINT sp = 0; sp < prop->properties.GetLength(); sp++ )
  2976. {
  2977. asCDataType sdt = prop->properties[sp]->type;
  2978. if( sdt.IsObject() )
  2979. {
  2980. if( sdt.IsObjectHandle() )
  2981. {
  2982. // TODO: runtime optimize: If the handle is again to a final class, then we can recursively check if the circular reference can occur
  2983. if( sdt.GetTypeInfo()->flags & (asOBJ_SCRIPT_OBJECT | asOBJ_GC) )
  2984. {
  2985. gc = true;
  2986. break;
  2987. }
  2988. }
  2989. else if( sdt.GetTypeInfo()->flags & asOBJ_GC )
  2990. {
  2991. // TODO: runtime optimize: Just because the member type is a potential circle doesn't mean that this one is.
  2992. // Only if the object is of a type that can reference this type, either directly or indirectly
  2993. gc = true;
  2994. break;
  2995. }
  2996. }
  2997. }
  2998. if( gc )
  2999. break;
  3000. }
  3001. else
  3002. {
  3003. // Assume it is garbage collected as it is not known at compile time what might inherit from this type
  3004. gc = true;
  3005. break;
  3006. }
  3007. }
  3008. else if( prop->flags & asOBJ_GC )
  3009. {
  3010. // If a type is not a script object, adopt its GC flag
  3011. // TODO: runtime optimize: Just because an application registered class is garbage collected, doesn't mean it
  3012. // can form a circular reference with this script class. Perhaps need a flag to tell
  3013. // if the script classes that contains the type should be garbage collected or not.
  3014. gc = true;
  3015. break;
  3016. }
  3017. }
  3018. else if( dt.GetTypeInfo()->flags & asOBJ_GC )
  3019. {
  3020. // TODO: runtime optimize: Just because the member type is a potential circle doesn't mean that this one is.
  3021. // Only if the object is of a type that can reference this type, either directly or indirectly
  3022. gc = true;
  3023. break;
  3024. }
  3025. }
  3026. }
  3027. // If the class wasn't found to require garbage collection, but it
  3028. // contains another type that has yet to be evaluated then it must be
  3029. // re-evaluated.
  3030. if( !gc && mustReevaluate )
  3031. {
  3032. typesToValidate.PushLast(type);
  3033. numReevaluations++;
  3034. continue;
  3035. }
  3036. // Update the flag in the object type
  3037. if( gc )
  3038. type->flags |= asOBJ_GC;
  3039. else
  3040. type->flags &= ~asOBJ_GC;
  3041. // Reset the counter
  3042. numReevaluations = 0;
  3043. }
  3044. */
  3045. }
  3046. void asCBuilder::IncludeMethodsFromMixins(sClassDeclaration *decl)
  3047. {
  3048. asCScriptNode *node = decl->node->firstChild;
  3049. // Skip the class attributes
  3050. while( node->nodeType == snIdentifier &&
  3051. !decl->script->TokenEquals(node->tokenPos, node->tokenLength, decl->name.AddressOf()) )
  3052. node = node->next;
  3053. // Skip the name of the class
  3054. node = node->next;
  3055. // Find the included mixin classes
  3056. while( node && node->nodeType == snIdentifier )
  3057. {
  3058. asSNameSpace *ns;
  3059. asCString name;
  3060. if( GetNamespaceAndNameFromNode(node, decl->script, decl->typeInfo->nameSpace, ns, name) < 0 )
  3061. {
  3062. node = node->next;
  3063. continue;
  3064. }
  3065. sMixinClass *mixin = 0;
  3066. while( ns )
  3067. {
  3068. // Need to make sure the name is not an object type
  3069. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  3070. if( objType == 0 )
  3071. mixin = GetMixinClass(name.AddressOf(), ns);
  3072. if( objType || mixin )
  3073. break;
  3074. ns = engine->GetParentNameSpace(ns);
  3075. }
  3076. if( mixin )
  3077. {
  3078. // Find methods from mixin declaration
  3079. asCScriptNode *n = mixin->node->firstChild;
  3080. // Skip to the member declarations
  3081. // Possible keywords 'final' and 'shared' are removed in RegisterMixinClass so we don't need to worry about those here
  3082. while( n && n->nodeType == snIdentifier )
  3083. n = n->next;
  3084. // Add methods from the mixin that are not already existing in the class
  3085. while( n )
  3086. {
  3087. if( n->nodeType == snFunction )
  3088. {
  3089. // Instead of disconnecting the node, we need to clone it, otherwise other
  3090. // classes that include the same mixin will not see the methods
  3091. asCScriptNode *copy = n->CreateCopy(engine);
  3092. // Register the method, but only if it doesn't already exist in the class
  3093. RegisterScriptFunctionFromNode(copy, mixin->script, CastToObjectType(decl->typeInfo), false, false, mixin->ns, false, true);
  3094. }
  3095. else if( n->nodeType == snVirtualProperty )
  3096. {
  3097. // TODO: mixin: Support virtual properties too
  3098. WriteError("The virtual property syntax is currently not supported for mixin classes", mixin->script, n);
  3099. //RegisterVirtualProperty(node, decl->script, decl->objType, false, false);
  3100. }
  3101. n = n->next;
  3102. }
  3103. }
  3104. node = node->next;
  3105. }
  3106. }
  3107. void asCBuilder::IncludePropertiesFromMixins(sClassDeclaration *decl)
  3108. {
  3109. asCScriptNode *node = decl->node->firstChild;
  3110. // Skip the class attributes
  3111. while( node->nodeType == snIdentifier &&
  3112. !decl->script->TokenEquals(node->tokenPos, node->tokenLength, decl->name.AddressOf()) )
  3113. node = node->next;
  3114. // Skip the name of the class
  3115. node = node->next;
  3116. // Find the included mixin classes
  3117. while( node && node->nodeType == snIdentifier )
  3118. {
  3119. asSNameSpace *ns;
  3120. asCString name;
  3121. if( GetNamespaceAndNameFromNode(node, decl->script, decl->typeInfo->nameSpace, ns, name) < 0 )
  3122. {
  3123. node = node->next;
  3124. continue;
  3125. }
  3126. sMixinClass *mixin = 0;
  3127. while( ns )
  3128. {
  3129. // Need to make sure the name is not an object type
  3130. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  3131. if( objType == 0 )
  3132. mixin = GetMixinClass(name.AddressOf(), ns);
  3133. if( objType || mixin )
  3134. break;
  3135. ns = engine->GetParentNameSpace(ns);
  3136. }
  3137. if( mixin )
  3138. {
  3139. // Find properties from mixin declaration
  3140. asCScriptNode *n = mixin->node->firstChild;
  3141. // Skip to the member declarations
  3142. // Possible keywords 'final' and 'shared' are removed in RegisterMixinClass so we don't need to worry about those here
  3143. while( n && n->nodeType == snIdentifier )
  3144. n = n->next;
  3145. // Add properties from the mixin that are not already existing in the class
  3146. while( n )
  3147. {
  3148. if( n->nodeType == snDeclaration )
  3149. {
  3150. asCScriptNode *n2 = n->firstChild;
  3151. bool isPrivate = false, isProtected = false;
  3152. if( n2 && n2->tokenType == ttPrivate )
  3153. {
  3154. isPrivate = true;
  3155. n2 = n2->next;
  3156. }
  3157. else if( n2 && n2->tokenType == ttProtected )
  3158. {
  3159. isProtected = true;
  3160. n2 = n2->next;
  3161. }
  3162. asCScriptCode *file = mixin->script;
  3163. asCDataType dt = CreateDataTypeFromNode(n2, file, mixin->ns);
  3164. if( decl->typeInfo->IsShared() && dt.GetTypeInfo() && !dt.GetTypeInfo()->IsShared() )
  3165. {
  3166. asCString msg;
  3167. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetTypeInfo()->name.AddressOf());
  3168. WriteError(msg, file, n);
  3169. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  3170. }
  3171. if( dt.IsReadOnly() )
  3172. WriteError(TXT_PROPERTY_CANT_BE_CONST, file, n);
  3173. n2 = n2->next;
  3174. while( n2 )
  3175. {
  3176. name.Assign(&file->code[n2->tokenPos], n2->tokenLength);
  3177. // Add the property only if it doesn't already exist in the class
  3178. bool exists = false;
  3179. asCObjectType *ot = CastToObjectType(decl->typeInfo);
  3180. for( asUINT p = 0; p < ot->properties.GetLength(); p++ )
  3181. if( ot->properties[p]->name == name )
  3182. {
  3183. exists = true;
  3184. break;
  3185. }
  3186. if( !exists )
  3187. {
  3188. if( !decl->isExistingShared )
  3189. {
  3190. // It must not conflict with the name of methods
  3191. int r = CheckNameConflictMember(ot, name.AddressOf(), n2, file, true);
  3192. if( r < 0 )
  3193. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  3194. AddPropertyToClass(decl, name, dt, isPrivate, isProtected, false, file, n2);
  3195. }
  3196. else
  3197. {
  3198. // Verify that the property exists in the original declaration
  3199. bool found = false;
  3200. for( asUINT p = 0; p < ot->properties.GetLength(); p++ )
  3201. {
  3202. asCObjectProperty *prop = ot->properties[p];
  3203. if( prop->isPrivate == isPrivate &&
  3204. prop->isProtected == isProtected &&
  3205. prop->name == name &&
  3206. prop->type == dt )
  3207. {
  3208. found = true;
  3209. break;
  3210. }
  3211. }
  3212. if( !found )
  3213. {
  3214. asCString str;
  3215. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, ot->GetName());
  3216. WriteError(str, decl->script, decl->node);
  3217. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  3218. }
  3219. }
  3220. }
  3221. // Skip the initialization expression
  3222. if( n2->next && n2->next->nodeType != snIdentifier )
  3223. n2 = n2->next;
  3224. n2 = n2->next;
  3225. }
  3226. }
  3227. n = n->next;
  3228. }
  3229. }
  3230. node = node->next;
  3231. }
  3232. }
  3233. int asCBuilder::CreateVirtualFunction(asCScriptFunction *func, int idx)
  3234. {
  3235. asCScriptFunction *vf = asNEW(asCScriptFunction)(engine, module, asFUNC_VIRTUAL);
  3236. if( vf == 0 )
  3237. return asOUT_OF_MEMORY;
  3238. vf->name = func->name;
  3239. vf->nameSpace = func->nameSpace;
  3240. vf->returnType = func->returnType;
  3241. vf->parameterTypes = func->parameterTypes;
  3242. vf->inOutFlags = func->inOutFlags;
  3243. vf->id = engine->GetNextScriptFunctionId();
  3244. vf->objectType = func->objectType;
  3245. vf->objectType->AddRefInternal();
  3246. vf->signatureId = func->signatureId;
  3247. vf->vfTableIdx = idx;
  3248. vf->traits = func->traits;
  3249. // Clear the shared trait since the virtual function should not have that
  3250. vf->SetShared(false);
  3251. // It is not necessary to copy the default args, as they have no meaning in the virtual function
  3252. module->AddScriptFunction(vf);
  3253. // Add a dummy to the builder so that it doesn't mix up function ids
  3254. functions.PushLast(0);
  3255. return vf->id;
  3256. }
  3257. asCObjectProperty *asCBuilder::AddPropertyToClass(sClassDeclaration *decl, const asCString &name, const asCDataType &dt, bool isPrivate, bool isProtected, bool isInherited, asCScriptCode *file, asCScriptNode *node)
  3258. {
  3259. if( node )
  3260. {
  3261. asASSERT(!isInherited);
  3262. // Check if the property is allowed
  3263. if( !dt.CanBeInstantiated() )
  3264. {
  3265. if( file && node )
  3266. {
  3267. asCString str;
  3268. if( dt.IsAbstractClass() )
  3269. str.Format(TXT_ABSTRACT_CLASS_s_CANNOT_BE_INSTANTIATED, dt.Format(decl->typeInfo->nameSpace).AddressOf());
  3270. else if( dt.IsInterface() )
  3271. str.Format(TXT_INTERFACE_s_CANNOT_BE_INSTANTIATED, dt.Format(decl->typeInfo->nameSpace).AddressOf());
  3272. else
  3273. // TODO: Improve error message to explain why
  3274. str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format(decl->typeInfo->nameSpace).AddressOf());
  3275. WriteError(str, file, node);
  3276. }
  3277. return 0;
  3278. }
  3279. // Register the initialization expression (if any) to be compiled later
  3280. asCScriptNode *declNode = node;
  3281. asCScriptNode *initNode = 0;
  3282. if( node->next && node->next->nodeType != snIdentifier )
  3283. {
  3284. asASSERT( node->next->nodeType == snAssignment );
  3285. initNode = node->next;
  3286. }
  3287. sPropertyInitializer p(name, declNode, initNode, file);
  3288. decl->propInits.PushLast(p);
  3289. }
  3290. else
  3291. {
  3292. // If the declaration node is not given, then
  3293. // this property is inherited from a base class
  3294. asASSERT(isInherited);
  3295. }
  3296. // Add the property to the object type
  3297. return CastToObjectType(decl->typeInfo)->AddPropertyToClass(name, dt, isPrivate, isProtected, isInherited);
  3298. }
  3299. bool asCBuilder::DoesMethodExist(asCObjectType *objType, int methodId, asUINT *methodIndex)
  3300. {
  3301. asCScriptFunction *method = GetFunctionDescription(methodId);
  3302. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  3303. {
  3304. asCScriptFunction *m = GetFunctionDescription(objType->methods[n]);
  3305. if( m->name != method->name ) continue;
  3306. if( m->returnType != method->returnType ) continue;
  3307. if( m->IsReadOnly() != method->IsReadOnly() ) continue;
  3308. if( m->parameterTypes != method->parameterTypes ) continue;
  3309. if( m->inOutFlags != method->inOutFlags ) continue;
  3310. if( methodIndex )
  3311. *methodIndex = n;
  3312. return true;
  3313. }
  3314. return false;
  3315. }
  3316. void asCBuilder::AddDefaultConstructor(asCObjectType *objType, asCScriptCode *file)
  3317. {
  3318. int funcId = engine->GetNextScriptFunctionId();
  3319. asCDataType returnType = asCDataType::CreatePrimitive(ttVoid, false);
  3320. asCArray<asCDataType> parameterTypes;
  3321. asCArray<asETypeModifiers> inOutFlags;
  3322. asCArray<asCString *> defaultArgs;
  3323. asCArray<asCString> parameterNames;
  3324. // Add the script function
  3325. // TODO: declaredAt should be set to where the class has been declared
  3326. module->AddScriptFunction(file->idx, 0, funcId, objType->name, returnType, parameterTypes, parameterNames, inOutFlags, defaultArgs, false, objType, false, asSFunctionTraits(), objType->nameSpace);
  3327. // Set it as default constructor
  3328. if( objType->beh.construct )
  3329. engine->scriptFunctions[objType->beh.construct]->ReleaseInternal();
  3330. objType->beh.construct = funcId;
  3331. objType->beh.constructors[0] = funcId;
  3332. engine->scriptFunctions[funcId]->AddRefInternal();
  3333. // The bytecode for the default constructor will be generated
  3334. // only after the potential inheritance has been established
  3335. sFunctionDescription *func = asNEW(sFunctionDescription);
  3336. if( func == 0 )
  3337. {
  3338. // Out of memory
  3339. return;
  3340. }
  3341. functions.PushLast(func);
  3342. func->script = file;
  3343. func->node = 0;
  3344. func->name = objType->name;
  3345. func->objType = objType;
  3346. func->funcId = funcId;
  3347. func->isExistingShared = false;
  3348. // Add a default factory as well
  3349. funcId = engine->GetNextScriptFunctionId();
  3350. if( objType->beh.factory )
  3351. engine->scriptFunctions[objType->beh.factory]->ReleaseInternal();
  3352. objType->beh.factory = funcId;
  3353. objType->beh.factories[0] = funcId;
  3354. returnType = asCDataType::CreateObjectHandle(objType, false);
  3355. // TODO: should be the same as the constructor
  3356. module->AddScriptFunction(file->idx, 0, funcId, objType->name, returnType, parameterTypes, parameterNames, inOutFlags, defaultArgs, false);
  3357. functions.PushLast(0);
  3358. asCCompiler compiler(engine);
  3359. compiler.CompileFactory(this, file, engine->scriptFunctions[funcId]);
  3360. engine->scriptFunctions[funcId]->AddRefInternal();
  3361. // If the object is shared, then the factory must also be marked as shared
  3362. if( objType->flags & asOBJ_SHARED )
  3363. engine->scriptFunctions[funcId]->SetShared(true);
  3364. }
  3365. int asCBuilder::RegisterEnum(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  3366. {
  3367. // Is it a shared enum?
  3368. bool isShared = false;
  3369. bool isExternal = false;
  3370. asCEnumType *existingSharedType = 0;
  3371. asCScriptNode *tmp = node->firstChild;
  3372. while( tmp->nodeType == snIdentifier )
  3373. {
  3374. if (file->TokenEquals(tmp->tokenPos, tmp->tokenLength, SHARED_TOKEN))
  3375. isShared = true;
  3376. else if (file->TokenEquals(tmp->tokenPos, tmp->tokenLength, EXTERNAL_TOKEN))
  3377. isExternal = true;
  3378. else
  3379. break;
  3380. tmp = tmp->next;
  3381. }
  3382. // Grab the name of the enumeration
  3383. asCString name;
  3384. asASSERT(snDataType == tmp->nodeType);
  3385. asASSERT(snIdentifier == tmp->firstChild->nodeType);
  3386. name.Assign(&file->code[tmp->firstChild->tokenPos], tmp->firstChild->tokenLength);
  3387. if( isShared )
  3388. {
  3389. // Look for a pre-existing shared enum with the same signature
  3390. for( asUINT n = 0; n < engine->sharedScriptTypes.GetLength(); n++ )
  3391. {
  3392. asCTypeInfo *o = engine->sharedScriptTypes[n];
  3393. if( o &&
  3394. o->IsShared() &&
  3395. (o->flags & asOBJ_ENUM) &&
  3396. o->name == name &&
  3397. o->nameSpace == ns )
  3398. {
  3399. existingSharedType = CastToEnumType(o);
  3400. break;
  3401. }
  3402. }
  3403. }
  3404. // If the enum was declared as external then it must have been compiled in a different module first
  3405. if (isExternal && existingSharedType == 0)
  3406. {
  3407. asCString str;
  3408. str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, name.AddressOf());
  3409. WriteError(str, file, tmp);
  3410. }
  3411. // Remember if the type was declared as external so the saved bytecode can be flagged accordingly
  3412. if (isExternal && existingSharedType)
  3413. module->externalTypes.PushLast(existingSharedType);
  3414. // Check the name and add the enum
  3415. int r = CheckNameConflict(name.AddressOf(), tmp->firstChild, file, ns);
  3416. if( asSUCCESS == r )
  3417. {
  3418. asCEnumType *st;
  3419. if( existingSharedType )
  3420. {
  3421. st = existingSharedType;
  3422. st->AddRefInternal();
  3423. }
  3424. else
  3425. {
  3426. st = asNEW(asCEnumType)(engine);
  3427. if( st == 0 )
  3428. return asOUT_OF_MEMORY;
  3429. st->flags = asOBJ_ENUM;
  3430. if( isShared )
  3431. st->flags |= asOBJ_SHARED;
  3432. st->size = 4;
  3433. st->name = name;
  3434. st->nameSpace = ns;
  3435. st->module = module;
  3436. }
  3437. module->enumTypes.PushLast(st);
  3438. if( !existingSharedType && isShared )
  3439. {
  3440. engine->sharedScriptTypes.PushLast(st);
  3441. st->AddRefInternal();
  3442. }
  3443. // Store the location of this declaration for reference in name collisions
  3444. sClassDeclaration *decl = asNEW(sClassDeclaration);
  3445. if( decl == 0 )
  3446. return asOUT_OF_MEMORY;
  3447. decl->name = name;
  3448. decl->script = file;
  3449. decl->typeInfo = st;
  3450. namedTypeDeclarations.PushLast(decl);
  3451. asCDataType type = CreateDataTypeFromNode(tmp, file, ns);
  3452. asASSERT(!type.IsReference());
  3453. // External shared enums must not redeclare the enum values
  3454. if (isExternal && (tmp->next == 0 || tmp->next->tokenType != ttEndStatement) )
  3455. {
  3456. asCString str;
  3457. str.Format(TXT_EXTERNAL_SHARED_s_CANNOT_REDEF, name.AddressOf());
  3458. WriteError(str, file, tmp);
  3459. }
  3460. else if (!isExternal && tmp->next && tmp->next->tokenType == ttEndStatement)
  3461. {
  3462. asCString str;
  3463. str.Format(TXT_MISSING_DEFINITION_OF_s, name.AddressOf());
  3464. WriteError(str, file, tmp);
  3465. }
  3466. // Register the enum values
  3467. tmp = tmp->next;
  3468. while( tmp && tmp->nodeType == snIdentifier )
  3469. {
  3470. name.Assign(&file->code[tmp->tokenPos], tmp->tokenLength);
  3471. if( existingSharedType )
  3472. {
  3473. // If this is a pre-existent shared enum, then just double check
  3474. // that the value is already defined in the original declaration
  3475. bool found = false;
  3476. for( asUINT n = 0; n < st->enumValues.GetLength(); n++ )
  3477. if( st->enumValues[n]->name == name )
  3478. {
  3479. found = true;
  3480. break;
  3481. }
  3482. if( !found )
  3483. {
  3484. asCString str;
  3485. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, st->GetName());
  3486. WriteError(str, file, tmp);
  3487. break;
  3488. }
  3489. tmp = tmp->next;
  3490. if( tmp && tmp->nodeType == snAssignment )
  3491. tmp = tmp->next;
  3492. continue;
  3493. }
  3494. else
  3495. {
  3496. // Check for name conflict errors with other values in the enum
  3497. if( globVariables.GetFirst(ns, name, asCCompGlobVarType(type)) )
  3498. {
  3499. asCString str;
  3500. str.Format(TXT_NAME_CONFLICT_s_ALREADY_USED, name.AddressOf());
  3501. WriteError(str, file, tmp);
  3502. tmp = tmp->next;
  3503. if( tmp && tmp->nodeType == snAssignment )
  3504. tmp = tmp->next;
  3505. continue;
  3506. }
  3507. // Check for assignment
  3508. asCScriptNode *asnNode = tmp->next;
  3509. if( asnNode && snAssignment == asnNode->nodeType )
  3510. asnNode->DisconnectParent();
  3511. else
  3512. asnNode = 0;
  3513. // Create the global variable description so the enum value can be evaluated
  3514. sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription);
  3515. if( gvar == 0 )
  3516. return asOUT_OF_MEMORY;
  3517. gvar->script = file;
  3518. gvar->declaredAtNode = tmp;
  3519. tmp = tmp->next;
  3520. gvar->declaredAtNode->DisconnectParent();
  3521. gvar->initializationNode = asnNode;
  3522. gvar->name = name;
  3523. gvar->datatype = type;
  3524. gvar->ns = ns;
  3525. // No need to allocate space on the global memory stack since the values are stored in the asCObjectType
  3526. // Set the index to a negative to allow compiler to diferentiate from ordinary global var when compiling the initialization
  3527. gvar->index = -1;
  3528. gvar->isCompiled = false;
  3529. gvar->isPureConstant = true;
  3530. gvar->isEnumValue = true;
  3531. gvar->constantValue = 0xdeadbeef;
  3532. // Allocate dummy property so we can compile the value.
  3533. // This will be removed later on so we don't add it to the engine.
  3534. gvar->property = asNEW(asCGlobalProperty);
  3535. if( gvar->property == 0 )
  3536. return asOUT_OF_MEMORY;
  3537. gvar->property->name = name;
  3538. gvar->property->nameSpace = ns;
  3539. gvar->property->type = gvar->datatype;
  3540. gvar->property->id = 0;
  3541. globVariables.Put(gvar);
  3542. }
  3543. }
  3544. }
  3545. node->Destroy(engine);
  3546. return r;
  3547. }
  3548. int asCBuilder::RegisterTypedef(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  3549. {
  3550. // Get the native data type
  3551. asCScriptNode *tmp = node->firstChild;
  3552. asASSERT(NULL != tmp && snDataType == tmp->nodeType);
  3553. asCDataType dataType;
  3554. dataType.CreatePrimitive(tmp->tokenType, false);
  3555. dataType.SetTokenType(tmp->tokenType);
  3556. tmp = tmp->next;
  3557. // Grab the name of the typedef
  3558. asASSERT(NULL != tmp && NULL == tmp->next);
  3559. asCString name;
  3560. name.Assign(&file->code[tmp->tokenPos], tmp->tokenLength);
  3561. // If the name is not already in use add it
  3562. int r = CheckNameConflict(name.AddressOf(), tmp, file, ns);
  3563. asCTypedefType *st = 0;
  3564. if( asSUCCESS == r )
  3565. {
  3566. // Create the new type
  3567. st = asNEW(asCTypedefType)(engine);
  3568. if( st == 0 )
  3569. r = asOUT_OF_MEMORY;
  3570. }
  3571. if( asSUCCESS == r )
  3572. {
  3573. st->flags = asOBJ_TYPEDEF;
  3574. st->size = dataType.GetSizeInMemoryBytes();
  3575. st->name = name;
  3576. st->nameSpace = ns;
  3577. st->aliasForType = dataType;
  3578. st->module = module;
  3579. module->typeDefs.PushLast(st);
  3580. // Store the location of this declaration for reference in name collisions
  3581. sClassDeclaration *decl = asNEW(sClassDeclaration);
  3582. if( decl == 0 )
  3583. r = asOUT_OF_MEMORY;
  3584. else
  3585. {
  3586. decl->name = name;
  3587. decl->script = file;
  3588. decl->typeInfo = st;
  3589. namedTypeDeclarations.PushLast(decl);
  3590. }
  3591. }
  3592. node->Destroy(engine);
  3593. return r;
  3594. }
  3595. void asCBuilder::GetParsedFunctionDetails(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, asCString &name, asCDataType &returnType, asCArray<asCString> &parameterNames, asCArray<asCDataType> &parameterTypes, asCArray<asETypeModifiers> &inOutFlags, asCArray<asCString *> &defaultArgs, asSFunctionTraits &funcTraits, asSNameSpace *implicitNamespace)
  3596. {
  3597. node = node->firstChild;
  3598. // Is the function shared?
  3599. funcTraits.SetTrait(asTRAIT_SHARED, false);
  3600. funcTraits.SetTrait(asTRAIT_EXTERNAL, false);
  3601. while (node->tokenType == ttIdentifier)
  3602. {
  3603. if (file->TokenEquals(node->tokenPos, node->tokenLength, SHARED_TOKEN))
  3604. funcTraits.SetTrait(asTRAIT_SHARED, true);
  3605. else if (file->TokenEquals(node->tokenPos, node->tokenLength, EXTERNAL_TOKEN))
  3606. funcTraits.SetTrait(asTRAIT_EXTERNAL, true);
  3607. else
  3608. break;
  3609. node = node->next;
  3610. }
  3611. // Is the function a private or protected class method?
  3612. funcTraits.SetTrait(asTRAIT_PRIVATE, false);
  3613. funcTraits.SetTrait(asTRAIT_PROTECTED, false);
  3614. if( node->tokenType == ttPrivate )
  3615. {
  3616. funcTraits.SetTrait(asTRAIT_PRIVATE, true);
  3617. node = node->next;
  3618. }
  3619. else if( node->tokenType == ttProtected )
  3620. {
  3621. funcTraits.SetTrait(asTRAIT_PROTECTED, true);
  3622. node = node->next;
  3623. }
  3624. // Find the name
  3625. funcTraits.SetTrait(asTRAIT_CONSTRUCTOR, false);
  3626. funcTraits.SetTrait(asTRAIT_DESTRUCTOR, false);
  3627. asCScriptNode *n = 0;
  3628. if( node->nodeType == snDataType )
  3629. n = node->next->next;
  3630. else
  3631. {
  3632. // If the first node is a ~ token, then we know it is a destructor
  3633. if( node->tokenType == ttBitNot )
  3634. {
  3635. n = node->next;
  3636. funcTraits.SetTrait(asTRAIT_DESTRUCTOR, true);
  3637. }
  3638. else
  3639. {
  3640. n = node;
  3641. funcTraits.SetTrait(asTRAIT_CONSTRUCTOR, true);
  3642. }
  3643. }
  3644. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  3645. if( !funcTraits.GetTrait(asTRAIT_CONSTRUCTOR) && !funcTraits.GetTrait(asTRAIT_DESTRUCTOR) )
  3646. {
  3647. returnType = CreateDataTypeFromNode(node, file, implicitNamespace, false, objType);
  3648. returnType = ModifyDataTypeFromNode(returnType, node->next, file, 0, 0);
  3649. if( engine->ep.disallowValueAssignForRefType &&
  3650. returnType.GetTypeInfo() &&
  3651. (returnType.GetTypeInfo()->flags & asOBJ_REF) &&
  3652. !(returnType.GetTypeInfo()->flags & asOBJ_SCOPED) &&
  3653. !returnType.IsReference() &&
  3654. !returnType.IsObjectHandle() )
  3655. {
  3656. WriteError(TXT_REF_TYPE_CANT_BE_RETURNED_BY_VAL, file, node);
  3657. }
  3658. }
  3659. else
  3660. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  3661. funcTraits.SetTrait(asTRAIT_CONST, false);
  3662. funcTraits.SetTrait(asTRAIT_FINAL, false);
  3663. funcTraits.SetTrait(asTRAIT_OVERRIDE, false);
  3664. if( objType && n->next->next )
  3665. {
  3666. asCScriptNode *decorator = n->next->next;
  3667. // Is this a const method?
  3668. if( decorator->tokenType == ttConst )
  3669. {
  3670. funcTraits.SetTrait(asTRAIT_CONST, true);
  3671. decorator = decorator->next;
  3672. }
  3673. while( decorator )
  3674. {
  3675. if( decorator->tokenType == ttIdentifier && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, FINAL_TOKEN) )
  3676. funcTraits.SetTrait(asTRAIT_FINAL, true);
  3677. else if( decorator->tokenType == ttIdentifier && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, OVERRIDE_TOKEN) )
  3678. funcTraits.SetTrait(asTRAIT_OVERRIDE, true);
  3679. decorator = decorator->next;
  3680. }
  3681. }
  3682. // Count the number of parameters
  3683. int count = 0;
  3684. asCScriptNode *c = n->next->firstChild;
  3685. while( c )
  3686. {
  3687. count++;
  3688. c = c->next->next;
  3689. if( c && c->nodeType == snIdentifier )
  3690. c = c->next;
  3691. if( c && c->nodeType == snExpression )
  3692. c = c->next;
  3693. }
  3694. // Get the parameter types
  3695. parameterNames.Allocate(count, false);
  3696. parameterTypes.Allocate(count, false);
  3697. inOutFlags.Allocate(count, false);
  3698. defaultArgs.Allocate(count, false);
  3699. n = n->next->firstChild;
  3700. while( n )
  3701. {
  3702. asETypeModifiers inOutFlag;
  3703. asCDataType type = CreateDataTypeFromNode(n, file, implicitNamespace, false, objType);
  3704. type = ModifyDataTypeFromNode(type, n->next, file, &inOutFlag, 0);
  3705. if( engine->ep.disallowValueAssignForRefType &&
  3706. type.GetTypeInfo() &&
  3707. (type.GetTypeInfo()->flags & asOBJ_REF) &&
  3708. !(type.GetTypeInfo()->flags & asOBJ_SCOPED) &&
  3709. !type.IsReference() &&
  3710. !type.IsObjectHandle() )
  3711. {
  3712. WriteError(TXT_REF_TYPE_CANT_BE_PASSED_BY_VAL, file, node);
  3713. }
  3714. // Store the parameter type
  3715. parameterTypes.PushLast(type);
  3716. inOutFlags.PushLast(inOutFlag);
  3717. // Move to next parameter
  3718. n = n->next->next;
  3719. if( n && n->nodeType == snIdentifier )
  3720. {
  3721. asCString paramName(&file->code[n->tokenPos], n->tokenLength);
  3722. parameterNames.PushLast(paramName);
  3723. n = n->next;
  3724. }
  3725. else
  3726. {
  3727. // No name was given for the parameter
  3728. parameterNames.PushLast(asCString());
  3729. }
  3730. if( n && n->nodeType == snExpression )
  3731. {
  3732. // Strip out white space and comments to better share the string
  3733. asCString *defaultArgStr = asNEW(asCString);
  3734. if( defaultArgStr )
  3735. *defaultArgStr = GetCleanExpressionString(n, file);
  3736. defaultArgs.PushLast(defaultArgStr);
  3737. n = n->next;
  3738. }
  3739. else
  3740. defaultArgs.PushLast(0);
  3741. }
  3742. }
  3743. #endif
  3744. asCString asCBuilder::GetCleanExpressionString(asCScriptNode *node, asCScriptCode *file)
  3745. {
  3746. asASSERT(node && node->nodeType == snExpression);
  3747. asCString str;
  3748. str.Assign(file->code + node->tokenPos, node->tokenLength);
  3749. asCString cleanStr;
  3750. for( asUINT n = 0; n < str.GetLength(); )
  3751. {
  3752. asUINT len = 0;
  3753. asETokenClass tok = engine->ParseToken(str.AddressOf() + n, str.GetLength() - n, &len);
  3754. if( tok != asTC_COMMENT && tok != asTC_WHITESPACE )
  3755. {
  3756. if( cleanStr.GetLength() ) cleanStr += " ";
  3757. cleanStr.Concatenate(str.AddressOf() + n, len);
  3758. }
  3759. n += len;
  3760. }
  3761. return cleanStr;
  3762. }
  3763. #ifndef AS_NO_COMPILER
  3764. int asCBuilder::RegisterScriptFunctionFromNode(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared, bool isMixin)
  3765. {
  3766. asCString name;
  3767. asCDataType returnType;
  3768. asCArray<asCString> parameterNames;
  3769. asCArray<asCDataType> parameterTypes;
  3770. asCArray<asETypeModifiers> inOutFlags;
  3771. asCArray<asCString *> defaultArgs;
  3772. asSFunctionTraits funcTraits;
  3773. asASSERT( (objType && ns == 0) || isGlobalFunction || isMixin );
  3774. // Set the default namespace
  3775. if( ns == 0 )
  3776. {
  3777. if( objType )
  3778. ns = objType->nameSpace;
  3779. else
  3780. ns = engine->nameSpaces[0];
  3781. }
  3782. GetParsedFunctionDetails(node, file, objType, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, funcTraits, ns);
  3783. return RegisterScriptFunction(node, file, objType, isInterface, isGlobalFunction, ns, isExistingShared, isMixin, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, funcTraits);
  3784. }
  3785. asCScriptFunction *asCBuilder::RegisterLambda(asCScriptNode *node, asCScriptCode *file, asCScriptFunction *funcDef, const asCString &name, asSNameSpace *ns)
  3786. {
  3787. // Get the parameter names from the node
  3788. asCArray<asCString> parameterNames;
  3789. asCArray<asCString*> defaultArgs;
  3790. asCScriptNode *args = node->firstChild;
  3791. while( args && args->nodeType != snStatementBlock )
  3792. {
  3793. if (args->nodeType == snIdentifier)
  3794. {
  3795. asCString argName;
  3796. argName.Assign(&file->code[args->tokenPos], args->tokenLength);
  3797. parameterNames.PushLast(argName);
  3798. defaultArgs.PushLast(0);
  3799. }
  3800. args = args->next;
  3801. }
  3802. // The statement block for the function must be disconnected, as the builder is going to be the owner of it
  3803. args->DisconnectParent();
  3804. // Get the return and parameter types from the funcDef
  3805. asCString funcName = name;
  3806. int r = RegisterScriptFunction(args, file, 0, 0, true, ns, false, false, funcName, funcDef->returnType, parameterNames, funcDef->parameterTypes, funcDef->inOutFlags, defaultArgs, asSFunctionTraits());
  3807. if( r < 0 )
  3808. return 0;
  3809. // Return the function that was just created (but that will be compiled later)
  3810. return engine->scriptFunctions[functions[functions.GetLength()-1]->funcId];
  3811. }
  3812. int asCBuilder::RegisterScriptFunction(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared, bool isMixin, asCString &name, asCDataType &returnType, asCArray<asCString> &parameterNames, asCArray<asCDataType> &parameterTypes, asCArray<asETypeModifiers> &inOutFlags, asCArray<asCString *> &defaultArgs, asSFunctionTraits funcTraits)
  3813. {
  3814. // Determine default namespace if not specified
  3815. if( ns == 0 )
  3816. {
  3817. if( objType )
  3818. ns = objType->nameSpace;
  3819. else
  3820. ns = engine->nameSpaces[0];
  3821. }
  3822. if( isExistingShared )
  3823. {
  3824. asASSERT( objType );
  3825. // Should validate that the function really exists in the class/interface
  3826. bool found = false;
  3827. if(funcTraits.GetTrait(asTRAIT_CONSTRUCTOR) || funcTraits.GetTrait(asTRAIT_DESTRUCTOR) )
  3828. {
  3829. // TODO: shared: Should check the existance of these too
  3830. found = true;
  3831. }
  3832. else
  3833. {
  3834. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  3835. {
  3836. asCScriptFunction *func = engine->scriptFunctions[objType->methods[n]];
  3837. if( func->name == name &&
  3838. func->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, objType, funcTraits.GetTrait(asTRAIT_CONST)) )
  3839. {
  3840. // Add the shared function in this module too
  3841. module->AddScriptFunction(func);
  3842. found = true;
  3843. break;
  3844. }
  3845. }
  3846. }
  3847. if( !found )
  3848. {
  3849. asCString str;
  3850. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, objType->GetName());
  3851. WriteError(str, file, node);
  3852. }
  3853. // Free the default args
  3854. for( asUINT n = 0; n < defaultArgs.GetLength(); n++ )
  3855. if( defaultArgs[n] )
  3856. asDELETE(defaultArgs[n], asCString);
  3857. node->Destroy(engine);
  3858. return 0;
  3859. }
  3860. // Check for name conflicts
  3861. if( !funcTraits.GetTrait(asTRAIT_CONSTRUCTOR) && !funcTraits.GetTrait(asTRAIT_DESTRUCTOR) )
  3862. {
  3863. if( objType )
  3864. {
  3865. CheckNameConflictMember(objType, name.AddressOf(), node, file, false);
  3866. if( name == objType->name )
  3867. WriteError(TXT_METHOD_CANT_HAVE_NAME_OF_CLASS, file, node);
  3868. }
  3869. else
  3870. CheckNameConflict(name.AddressOf(), node, file, ns);
  3871. }
  3872. else
  3873. {
  3874. if( isMixin )
  3875. {
  3876. // Mixins cannot implement constructors/destructors
  3877. WriteError(TXT_MIXIN_CANNOT_HAVE_CONSTRUCTOR, file, node);
  3878. // Free the default args
  3879. for( asUINT n = 0; n < defaultArgs.GetLength(); n++ )
  3880. if( defaultArgs[n] )
  3881. asDELETE(defaultArgs[n], asCString);
  3882. node->Destroy(engine);
  3883. return 0;
  3884. }
  3885. // Verify that the name of the constructor/destructor is the same as the class
  3886. if( name != objType->name )
  3887. {
  3888. asCString str;
  3889. if(funcTraits.GetTrait(asTRAIT_DESTRUCTOR) )
  3890. str.Format(TXT_DESTRUCTOR_s_s_NAME_ERROR, objType->name.AddressOf(), name.AddressOf());
  3891. else
  3892. str.Format(TXT_METHOD_s_s_HAS_NO_RETURN_TYPE, objType->name.AddressOf(), name.AddressOf());
  3893. WriteError(str, file, node);
  3894. }
  3895. if(funcTraits.GetTrait(asTRAIT_DESTRUCTOR))
  3896. name = "~" + name;
  3897. }
  3898. isExistingShared = false;
  3899. int funcId = engine->GetNextScriptFunctionId();
  3900. if( !isInterface )
  3901. {
  3902. sFunctionDescription *func = asNEW(sFunctionDescription);
  3903. if( func == 0 )
  3904. {
  3905. // Free the default args
  3906. for( asUINT n = 0; n < defaultArgs.GetLength(); n++ )
  3907. if( defaultArgs[n] )
  3908. asDELETE(defaultArgs[n], asCString);
  3909. return asOUT_OF_MEMORY;
  3910. }
  3911. functions.PushLast(func);
  3912. func->script = file;
  3913. func->node = node;
  3914. func->name = name;
  3915. func->objType = objType;
  3916. func->funcId = funcId;
  3917. func->isExistingShared = false;
  3918. func->paramNames = parameterNames;
  3919. if(funcTraits.GetTrait(asTRAIT_SHARED))
  3920. {
  3921. // Look for a pre-existing shared function with the same signature
  3922. for( asUINT n = 0; n < engine->scriptFunctions.GetLength(); n++ )
  3923. {
  3924. asCScriptFunction *f = engine->scriptFunctions[n];
  3925. if( f &&
  3926. f->IsShared() &&
  3927. f->name == name &&
  3928. f->nameSpace == ns &&
  3929. f->objectType == objType &&
  3930. f->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, 0, false) )
  3931. {
  3932. funcId = func->funcId = f->id;
  3933. isExistingShared = func->isExistingShared = true;
  3934. break;
  3935. }
  3936. }
  3937. }
  3938. // Remember if the function was declared as external so the saved bytecode can be flagged accordingly
  3939. if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && func->isExistingShared)
  3940. module->externalFunctions.PushLast(engine->scriptFunctions[func->funcId]);
  3941. if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && !func->isExistingShared)
  3942. {
  3943. // Mark it as existing shared to avoid compiling it
  3944. func->isExistingShared = true;
  3945. asCString str;
  3946. str.Format(TXT_EXTERNAL_SHARED_s_NOT_FOUND, name.AddressOf());
  3947. WriteError(str, file, node);
  3948. }
  3949. // External shared function must not try to redefine the interface
  3950. if (funcTraits.GetTrait(asTRAIT_EXTERNAL) && !(node->tokenType == ttEndStatement || node->lastChild->tokenType == ttEndStatement))
  3951. {
  3952. asCString str;
  3953. str.Format(TXT_EXTERNAL_SHARED_s_CANNOT_REDEF, name.AddressOf());
  3954. WriteError(str, file, node);
  3955. }
  3956. else if (!funcTraits.GetTrait(asTRAIT_EXTERNAL) && !(node->nodeType == snStatementBlock || node->lastChild->nodeType == snStatementBlock) )
  3957. {
  3958. asCString str;
  3959. str.Format(TXT_MISSING_DEFINITION_OF_s, name.AddressOf());
  3960. WriteError(str, file, node);
  3961. }
  3962. }
  3963. // Destructors may not have any parameters
  3964. if (funcTraits.GetTrait(asTRAIT_DESTRUCTOR) && parameterTypes.GetLength() > 0)
  3965. WriteError(TXT_DESTRUCTOR_MAY_NOT_HAVE_PARM, file, node);
  3966. // If a function, class, or interface is shared then only shared types may be used in the signature
  3967. if( (objType && objType->IsShared()) || funcTraits.GetTrait(asTRAIT_SHARED))
  3968. {
  3969. asCTypeInfo *ti = returnType.GetTypeInfo();
  3970. if( ti && !ti->IsShared() )
  3971. {
  3972. asCString msg;
  3973. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ti->name.AddressOf());
  3974. WriteError(msg, file, node);
  3975. }
  3976. for( asUINT p = 0; p < parameterTypes.GetLength(); ++p )
  3977. {
  3978. ti = parameterTypes[p].GetTypeInfo();
  3979. if( ti && !ti->IsShared() )
  3980. {
  3981. asCString msg;
  3982. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ti->name.AddressOf());
  3983. WriteError(msg, file, node);
  3984. }
  3985. }
  3986. }
  3987. // Check that the same function hasn't been registered already in the namespace
  3988. asCArray<int> funcs;
  3989. if( objType )
  3990. GetObjectMethodDescriptions(name.AddressOf(), objType, funcs, false);
  3991. else
  3992. GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  3993. if( objType && (name == "opConv" || name == "opImplConv" || name == "opCast" || name == "opImplCast") && parameterTypes.GetLength() == 0 )
  3994. {
  3995. // opConv and opCast are special methods used for type casts
  3996. for( asUINT n = 0; n < funcs.GetLength(); ++n )
  3997. {
  3998. asCScriptFunction *func = GetFunctionDescription(funcs[n]);
  3999. if( func->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, objType, funcTraits.GetTrait(asTRAIT_CONST)) )
  4000. {
  4001. // TODO: clean up: Reuse the same error handling for both opConv and normal methods
  4002. if( isMixin )
  4003. {
  4004. // Clean up the memory, as the function will not be registered
  4005. if( node )
  4006. node->Destroy(engine);
  4007. sFunctionDescription *funcDesc = functions.PopLast();
  4008. asDELETE(funcDesc, sFunctionDescription);
  4009. // Free the default args
  4010. for( n = 0; n < defaultArgs.GetLength(); n++ )
  4011. if( defaultArgs[n] )
  4012. asDELETE(defaultArgs[n], asCString);
  4013. return 0;
  4014. }
  4015. WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
  4016. break;
  4017. }
  4018. }
  4019. }
  4020. else
  4021. {
  4022. for( asUINT n = 0; n < funcs.GetLength(); ++n )
  4023. {
  4024. asCScriptFunction *func = GetFunctionDescription(funcs[n]);
  4025. if( func->IsSignatureExceptNameAndReturnTypeEqual(parameterTypes, inOutFlags, objType, funcTraits.GetTrait(asTRAIT_CONST)) )
  4026. {
  4027. if( isMixin )
  4028. {
  4029. // Clean up the memory, as the function will not be registered
  4030. if( node )
  4031. node->Destroy(engine);
  4032. sFunctionDescription *funcDesc = functions.PopLast();
  4033. asDELETE(funcDesc, sFunctionDescription);
  4034. // Free the default args
  4035. for( n = 0; n < defaultArgs.GetLength(); n++ )
  4036. if( defaultArgs[n] )
  4037. asDELETE(defaultArgs[n], asCString);
  4038. return 0;
  4039. }
  4040. WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
  4041. break;
  4042. }
  4043. }
  4044. }
  4045. // Register the function
  4046. if( isExistingShared )
  4047. {
  4048. // Delete the default args as they won't be used anymore
  4049. for( asUINT n = 0; n < defaultArgs.GetLength(); n++ )
  4050. if( defaultArgs[n] )
  4051. asDELETE(defaultArgs[n], asCString);
  4052. asCScriptFunction *f = engine->scriptFunctions[funcId];
  4053. module->AddScriptFunction(f);
  4054. // TODO: clean up: This should be done by AddScriptFunction() itself
  4055. module->globalFunctions.Put(f);
  4056. }
  4057. else
  4058. {
  4059. int row = 0, col = 0;
  4060. if( node )
  4061. file->ConvertPosToRowCol(node->tokenPos, &row, &col);
  4062. module->AddScriptFunction(file->idx, (row&0xFFFFF)|((col&0xFFF)<<20), funcId, name, returnType, parameterTypes, parameterNames, inOutFlags, defaultArgs, isInterface, objType, isGlobalFunction, funcTraits, ns);
  4063. }
  4064. // Make sure the default args are declared correctly
  4065. ValidateDefaultArgs(file, node, engine->scriptFunctions[funcId]);
  4066. CheckForConflictsDueToDefaultArgs(file, node, engine->scriptFunctions[funcId], objType);
  4067. if( objType )
  4068. {
  4069. asASSERT( !isExistingShared );
  4070. engine->scriptFunctions[funcId]->AddRefInternal();
  4071. if(funcTraits.GetTrait(asTRAIT_CONSTRUCTOR))
  4072. {
  4073. int factoryId = engine->GetNextScriptFunctionId();
  4074. if( parameterTypes.GetLength() == 0 )
  4075. {
  4076. // Overload the default constructor
  4077. engine->scriptFunctions[objType->beh.construct]->ReleaseInternal();
  4078. objType->beh.construct = funcId;
  4079. objType->beh.constructors[0] = funcId;
  4080. // Register the default factory as well
  4081. engine->scriptFunctions[objType->beh.factory]->ReleaseInternal();
  4082. objType->beh.factory = factoryId;
  4083. objType->beh.factories[0] = factoryId;
  4084. }
  4085. else
  4086. {
  4087. // The copy constructor needs to be marked for easy finding
  4088. if (parameterTypes.GetLength() == 1 && parameterTypes[0].GetTypeInfo() == objType)
  4089. {
  4090. // Verify that there are not multiple options matching the copy constructor
  4091. // TODO: Need a better message, since the parameters can be slightly different, e.g. & vs @
  4092. if( objType->beh.copyconstruct )
  4093. WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
  4094. objType->beh.copyconstruct = funcId;
  4095. objType->beh.copyfactory = factoryId;
  4096. }
  4097. // Register as a normal constructor
  4098. objType->beh.constructors.PushLast(funcId);
  4099. // Register the factory as well
  4100. objType->beh.factories.PushLast(factoryId);
  4101. }
  4102. // We must copy the default arg strings to avoid deleting the same object multiple times
  4103. for( asUINT n = 0; n < defaultArgs.GetLength(); n++ )
  4104. if( defaultArgs[n] )
  4105. defaultArgs[n] = asNEW(asCString)(*defaultArgs[n]);
  4106. asCDataType dt = asCDataType::CreateObjectHandle(objType, false);
  4107. module->AddScriptFunction(file->idx, engine->scriptFunctions[funcId]->scriptData->declaredAt, factoryId, name, dt, parameterTypes, parameterNames, inOutFlags, defaultArgs, false, 0, false, funcTraits);
  4108. // If the object is shared, then the factory must also be marked as shared
  4109. if( objType->flags & asOBJ_SHARED )
  4110. engine->scriptFunctions[factoryId]->SetShared(true);
  4111. // Add a dummy function to the builder so that it doesn't mix up the fund Ids
  4112. functions.PushLast(0);
  4113. // Compile the factory immediately
  4114. asCCompiler compiler(engine);
  4115. compiler.CompileFactory(this, file, engine->scriptFunctions[factoryId]);
  4116. engine->scriptFunctions[factoryId]->AddRefInternal();
  4117. }
  4118. else if(funcTraits.GetTrait(asTRAIT_DESTRUCTOR))
  4119. objType->beh.destruct = funcId;
  4120. else
  4121. {
  4122. // If the method is the assignment operator we need to replace the default implementation
  4123. asCScriptFunction *f = engine->scriptFunctions[funcId];
  4124. if( f->name == "opAssign" && f->parameterTypes.GetLength() == 1 &&
  4125. f->parameterTypes[0].GetTypeInfo() == f->objectType &&
  4126. (f->inOutFlags[0] & asTM_INREF) )
  4127. {
  4128. engine->scriptFunctions[objType->beh.copy]->ReleaseInternal();
  4129. objType->beh.copy = funcId;
  4130. f->AddRefInternal();
  4131. }
  4132. objType->methods.PushLast(funcId);
  4133. }
  4134. }
  4135. // We need to delete the node already if this is an interface method
  4136. if( isInterface && node )
  4137. node->Destroy(engine);
  4138. return 0;
  4139. }
  4140. int asCBuilder::RegisterVirtualProperty(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared)
  4141. {
  4142. if( engine->ep.propertyAccessorMode != 2 )
  4143. {
  4144. WriteError(TXT_PROPERTY_ACCESSOR_DISABLED, file, node);
  4145. node->Destroy(engine);
  4146. return 0;
  4147. }
  4148. asASSERT( (objType && ns == 0) || isGlobalFunction );
  4149. if( ns == 0 )
  4150. {
  4151. if( objType )
  4152. ns = objType->nameSpace;
  4153. else
  4154. ns = engine->nameSpaces[0];
  4155. }
  4156. bool isPrivate = false, isProtected = false;
  4157. asCString emulatedName;
  4158. asCDataType emulatedType;
  4159. asCScriptNode *mainNode = node;
  4160. node = node->firstChild;
  4161. if( !isGlobalFunction && node->tokenType == ttPrivate )
  4162. {
  4163. isPrivate = true;
  4164. node = node->next;
  4165. }
  4166. else if( !isGlobalFunction && node->tokenType == ttProtected )
  4167. {
  4168. isProtected = true;
  4169. node = node->next;
  4170. }
  4171. emulatedType = CreateDataTypeFromNode(node, file, ns);
  4172. emulatedType = ModifyDataTypeFromNode(emulatedType, node->next, file, 0, 0);
  4173. node = node->next->next;
  4174. emulatedName.Assign(&file->code[node->tokenPos], node->tokenLength);
  4175. if( node->next == 0 )
  4176. WriteError(TXT_PROPERTY_WITHOUT_ACCESSOR, file, node);
  4177. node = node->next;
  4178. while (node)
  4179. {
  4180. asCScriptNode *next = node->next;
  4181. asCScriptNode *funcNode = 0;
  4182. bool success = false;
  4183. asSFunctionTraits funcTraits;
  4184. asCDataType returnType;
  4185. asCArray<asCString> paramNames;
  4186. asCArray<asCDataType> paramTypes;
  4187. asCArray<asETypeModifiers> paramModifiers;
  4188. asCArray<asCString*> defaultArgs;
  4189. asCString name;
  4190. funcTraits.SetTrait(asTRAIT_PRIVATE, isPrivate);
  4191. funcTraits.SetTrait(asTRAIT_PROTECTED, isProtected);
  4192. // TODO: getset: Allow private for individual property accessors
  4193. // TODO: getset: If the accessor uses its own name, then the property should be automatically declared
  4194. if (node->firstChild->nodeType == snIdentifier && file->TokenEquals(node->firstChild->tokenPos, node->firstChild->tokenLength, GET_TOKEN))
  4195. name = "get_";
  4196. else if (node->firstChild->nodeType == snIdentifier && file->TokenEquals(node->firstChild->tokenPos, node->firstChild->tokenLength, SET_TOKEN))
  4197. name = "set_";
  4198. else
  4199. WriteError(TXT_UNRECOGNIZED_VIRTUAL_PROPERTY_NODE, file, node);
  4200. if (name != "")
  4201. {
  4202. success = true;
  4203. funcNode = node->firstChild->next;
  4204. if (funcNode && funcNode->tokenType == ttConst)
  4205. {
  4206. funcTraits.SetTrait(asTRAIT_CONST, true);
  4207. funcNode = funcNode->next;
  4208. }
  4209. while (funcNode && funcNode->nodeType != snStatementBlock)
  4210. {
  4211. if (funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, FINAL_TOKEN))
  4212. funcTraits.SetTrait(asTRAIT_FINAL, true);
  4213. else if (funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, OVERRIDE_TOKEN))
  4214. funcTraits.SetTrait(asTRAIT_OVERRIDE, true);
  4215. funcNode = funcNode->next;
  4216. }
  4217. if (funcNode)
  4218. funcNode->DisconnectParent();
  4219. if (funcNode == 0 && (objType == 0 || !objType->IsInterface()))
  4220. {
  4221. // TODO: getset: If no implementation is supplied the builder should provide an automatically generated implementation
  4222. // The compiler needs to be able to handle the different types, primitive, value type, and handle
  4223. // The code is also different for global property accessors
  4224. WriteError(TXT_PROPERTY_ACCESSOR_MUST_BE_IMPLEMENTED, file, node);
  4225. }
  4226. if (name == "get_")
  4227. {
  4228. // Setup the signature for the get accessor method
  4229. returnType = emulatedType;
  4230. name = "get_" + emulatedName;
  4231. }
  4232. else if (name == "set_")
  4233. {
  4234. // Setup the signature for the set accessor method
  4235. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  4236. paramModifiers.PushLast(asTM_NONE);
  4237. paramNames.PushLast("value");
  4238. paramTypes.PushLast(emulatedType);
  4239. defaultArgs.PushLast(0);
  4240. name = "set_" + emulatedName;
  4241. }
  4242. }
  4243. if( success )
  4244. {
  4245. if( !isExistingShared )
  4246. RegisterScriptFunction(funcNode, file, objType, isInterface, isGlobalFunction, ns, false, false, name, returnType, paramNames, paramTypes, paramModifiers, defaultArgs, funcTraits);
  4247. else
  4248. {
  4249. // Free the funcNode as it won't be used
  4250. if( funcNode ) funcNode->Destroy(engine);
  4251. // Should validate that the function really exists in the class/interface
  4252. bool found = false;
  4253. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  4254. {
  4255. asCScriptFunction *func = engine->scriptFunctions[objType->methods[n]];
  4256. if( func->name == name &&
  4257. func->IsSignatureExceptNameEqual(returnType, paramTypes, paramModifiers, objType, funcTraits.GetTrait(asTRAIT_CONST)) )
  4258. {
  4259. found = true;
  4260. break;
  4261. }
  4262. }
  4263. if( !found )
  4264. {
  4265. asCString str;
  4266. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, objType->GetName());
  4267. WriteError(str, file, node);
  4268. }
  4269. }
  4270. }
  4271. node = next;
  4272. };
  4273. mainNode->Destroy(engine);
  4274. return 0;
  4275. }
  4276. int asCBuilder::RegisterImportedFunction(int importID, asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  4277. {
  4278. asCString name;
  4279. asCDataType returnType;
  4280. asCArray<asCString> parameterNames;
  4281. asCArray<asCDataType> parameterTypes;
  4282. asCArray<asETypeModifiers> inOutFlags;
  4283. asCArray<asCString *> defaultArgs;
  4284. asSFunctionTraits funcTraits;
  4285. if( ns == 0 )
  4286. ns = engine->nameSpaces[0];
  4287. GetParsedFunctionDetails(node->firstChild, file, 0, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, funcTraits, ns);
  4288. CheckNameConflict(name.AddressOf(), node, file, ns);
  4289. // Check that the same function hasn't been registered already in the namespace
  4290. asCArray<int> funcs;
  4291. GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  4292. for( asUINT n = 0; n < funcs.GetLength(); ++n )
  4293. {
  4294. asCScriptFunction *func = GetFunctionDescription(funcs[n]);
  4295. if( func->IsSignatureExceptNameAndReturnTypeEqual(parameterTypes, inOutFlags, 0, false) )
  4296. {
  4297. WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
  4298. break;
  4299. }
  4300. }
  4301. // Read the module name as well
  4302. asCScriptNode *nd = node->lastChild;
  4303. asASSERT( nd->nodeType == snConstant && nd->tokenType == ttStringConstant );
  4304. asCString moduleName;
  4305. moduleName.Assign(&file->code[nd->tokenPos+1], nd->tokenLength-2);
  4306. node->Destroy(engine);
  4307. // Register the function
  4308. module->AddImportedFunction(importID, name, returnType, parameterTypes, inOutFlags, defaultArgs, ns, moduleName);
  4309. return 0;
  4310. }
  4311. asCScriptFunction *asCBuilder::GetFunctionDescription(int id)
  4312. {
  4313. // TODO: import: This should be improved when the imported functions are removed
  4314. // Get the description from the engine
  4315. if( (id & FUNC_IMPORTED) == 0 )
  4316. return engine->scriptFunctions[id];
  4317. else
  4318. return engine->importedFunctions[id & ~FUNC_IMPORTED]->importedFunctionSignature;
  4319. }
  4320. void asCBuilder::GetFunctionDescriptions(const char *name, asCArray<int> &funcs, asSNameSpace *ns)
  4321. {
  4322. asUINT n;
  4323. // Get the script declared global functions
  4324. const asCArray<unsigned int> &idxs = module->globalFunctions.GetIndexes(ns, name);
  4325. for( n = 0; n < idxs.GetLength(); n++ )
  4326. {
  4327. const asCScriptFunction *f = module->globalFunctions.Get(idxs[n]);
  4328. asASSERT( f->objectType == 0 );
  4329. funcs.PushLast(f->id);
  4330. }
  4331. // Add the imported functions
  4332. // TODO: optimize: Linear search: This is probably not that critial. Also bindInformation will probably be removed in near future
  4333. for( n = 0; n < module->bindInformations.GetLength(); n++ )
  4334. {
  4335. if( module->bindInformations[n]->importedFunctionSignature->name == name &&
  4336. module->bindInformations[n]->importedFunctionSignature->nameSpace == ns )
  4337. funcs.PushLast(module->bindInformations[n]->importedFunctionSignature->id);
  4338. }
  4339. // Add the registered global functions
  4340. const asCArray<unsigned int> &idxs2 = engine->registeredGlobalFuncs.GetIndexes(ns, name);
  4341. for( n = 0; n < idxs2.GetLength(); n++ )
  4342. {
  4343. asCScriptFunction *f = engine->registeredGlobalFuncs.Get(idxs2[n]);
  4344. // Verify if the module has access to the function
  4345. if( module->accessMask & f->accessMask )
  4346. {
  4347. funcs.PushLast(f->id);
  4348. }
  4349. }
  4350. }
  4351. // scope is only informed when looking for a base class' method
  4352. void asCBuilder::GetObjectMethodDescriptions(const char *name, asCObjectType *objectType, asCArray<int> &methods, bool objIsConst, const asCString &scope, asCScriptNode *errNode, asCScriptCode *script)
  4353. {
  4354. asASSERT(objectType);
  4355. if( scope != "" )
  4356. {
  4357. // If searching with a scope informed, then the node and script must also be informed for potential error reporting
  4358. asASSERT( errNode && script );
  4359. // If the scope contains ::identifier, then use the last identifier as the class name and the rest of it as the namespace
  4360. // TODO: child funcdef: A scope can include a template type, e.g. array<ns::type>
  4361. int n = scope.FindLast("::");
  4362. asCString className = n >= 0 ? scope.SubString(n+2) : scope;
  4363. asCString nsName = n >= 0 ? scope.SubString(0, n) : "";
  4364. // If a namespace was specifically defined, then this must be used
  4365. asSNameSpace *ns = 0;
  4366. if (n >= 0)
  4367. {
  4368. if (nsName == "")
  4369. ns = engine->nameSpaces[0];
  4370. else
  4371. ns = GetNameSpaceByString(nsName, objectType->nameSpace, errNode, script, 0, false);
  4372. // If the namespace isn't found return silently and let the calling
  4373. // function report the error if it cannot resolve the symbol
  4374. if (ns == 0)
  4375. return;
  4376. }
  4377. // Find the base class with the specified scope
  4378. while (objectType)
  4379. {
  4380. // If the name and namespace matches it is the correct class. If no
  4381. // specific namespace was given, then don't compare the namespace
  4382. if (objectType->name == className && (ns == 0 || objectType->nameSpace == ns))
  4383. break;
  4384. objectType = objectType->derivedFrom;
  4385. }
  4386. // If the scope is not any of the base classes, then return no methods
  4387. if( objectType == 0 )
  4388. return;
  4389. }
  4390. // Find the methods in the object that match the name
  4391. // TODO: optimize: Improve linear search
  4392. for( asUINT n = 0; n < objectType->methods.GetLength(); n++ )
  4393. {
  4394. asCScriptFunction *func = engine->scriptFunctions[objectType->methods[n]];
  4395. if( func->name == name &&
  4396. (!objIsConst || func->IsReadOnly()) &&
  4397. (func->accessMask & module->accessMask) )
  4398. {
  4399. // When the scope is defined the returned methods should be the true methods, not the virtual method stubs
  4400. if( scope == "" )
  4401. methods.PushLast(engine->scriptFunctions[objectType->methods[n]]->id);
  4402. else
  4403. {
  4404. asCScriptFunction *virtFunc = engine->scriptFunctions[objectType->methods[n]];
  4405. asCScriptFunction *realFunc = objectType->virtualFunctionTable[virtFunc->vfTableIdx];
  4406. methods.PushLast(realFunc->id);
  4407. }
  4408. }
  4409. }
  4410. }
  4411. #endif
  4412. void asCBuilder::WriteInfo(const asCString &scriptname, const asCString &message, int r, int c, bool pre)
  4413. {
  4414. // Need to store the pre message in a structure
  4415. if( pre )
  4416. {
  4417. engine->preMessage.isSet = true;
  4418. engine->preMessage.c = c;
  4419. engine->preMessage.r = r;
  4420. engine->preMessage.message = message;
  4421. engine->preMessage.scriptname = scriptname;
  4422. }
  4423. else
  4424. {
  4425. engine->preMessage.isSet = false;
  4426. if( !silent )
  4427. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_INFORMATION, message.AddressOf());
  4428. }
  4429. }
  4430. void asCBuilder::WriteInfo(const asCString &message, asCScriptCode *file, asCScriptNode *node)
  4431. {
  4432. int r = 0, c = 0;
  4433. if( node )
  4434. file->ConvertPosToRowCol(node->tokenPos, &r, &c);
  4435. WriteInfo(file->name, message, r, c, false);
  4436. }
  4437. void asCBuilder::WriteError(const asCString &message, asCScriptCode *file, asCScriptNode *node)
  4438. {
  4439. int r = 0, c = 0;
  4440. if( node && file )
  4441. file->ConvertPosToRowCol(node->tokenPos, &r, &c);
  4442. WriteError(file ? file->name : asCString(""), message, r, c);
  4443. }
  4444. void asCBuilder::WriteError(const asCString &scriptname, const asCString &message, int r, int c)
  4445. {
  4446. numErrors++;
  4447. if( !silent )
  4448. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_ERROR, message.AddressOf());
  4449. }
  4450. void asCBuilder::WriteWarning(const asCString &scriptname, const asCString &message, int r, int c)
  4451. {
  4452. if( engine->ep.compilerWarnings )
  4453. {
  4454. numWarnings++;
  4455. if( !silent )
  4456. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_WARNING, message.AddressOf());
  4457. }
  4458. }
  4459. void asCBuilder::WriteWarning(const asCString &message, asCScriptCode *file, asCScriptNode *node)
  4460. {
  4461. int r = 0, c = 0;
  4462. if( node && file )
  4463. file->ConvertPosToRowCol(node->tokenPos, &r, &c);
  4464. WriteWarning(file ? file->name : asCString(""), message, r, c);
  4465. }
  4466. // TODO: child funcdef: Should try to eliminate this function. GetNameSpaceFromNode is more complete
  4467. asCString asCBuilder::GetScopeFromNode(asCScriptNode *node, asCScriptCode *script, asCScriptNode **next)
  4468. {
  4469. if (node->nodeType != snScope)
  4470. {
  4471. if (next)
  4472. *next = node;
  4473. return "";
  4474. }
  4475. asCString scope;
  4476. asCScriptNode *sn = node->firstChild;
  4477. if( sn->tokenType == ttScope )
  4478. {
  4479. scope = "::";
  4480. sn = sn->next;
  4481. }
  4482. // TODO: child funcdef: A scope can have a template type as the innermost
  4483. while( sn && sn->next && sn->next->tokenType == ttScope )
  4484. {
  4485. asCString tmp;
  4486. tmp.Assign(&script->code[sn->tokenPos], sn->tokenLength);
  4487. if( scope != "" && scope != "::" )
  4488. scope += "::";
  4489. scope += tmp;
  4490. sn = sn->next->next;
  4491. }
  4492. if( next )
  4493. *next = node->next;
  4494. return scope;
  4495. }
  4496. asSNameSpace *asCBuilder::GetNameSpaceFromNode(asCScriptNode *node, asCScriptCode *script, asSNameSpace *implicitNs, asCScriptNode **next, asCObjectType **objType)
  4497. {
  4498. if (objType)
  4499. *objType = 0;
  4500. // If no scope has been informed, then return the implicit namespace
  4501. if (node->nodeType != snScope)
  4502. {
  4503. if (next)
  4504. *next = node;
  4505. return implicitNs ? implicitNs : engine->nameSpaces[0];
  4506. }
  4507. if (next)
  4508. *next = node->next;
  4509. asCString scope;
  4510. asCScriptNode *sn = node->firstChild;
  4511. if (sn && sn->tokenType == ttScope)
  4512. {
  4513. scope = "::";
  4514. sn = sn->next;
  4515. }
  4516. while (sn)
  4517. {
  4518. if (sn->next->tokenType == ttScope)
  4519. {
  4520. asCString tmp;
  4521. tmp.Assign(&script->code[sn->tokenPos], sn->tokenLength);
  4522. if (scope != "" && scope != "::")
  4523. scope += "::";
  4524. scope += tmp;
  4525. sn = sn->next->next;
  4526. }
  4527. else
  4528. {
  4529. // This is a template type
  4530. asASSERT(sn->next->nodeType == snDataType);
  4531. asSNameSpace *ns = implicitNs;
  4532. if (scope != "")
  4533. ns = engine->FindNameSpace(scope.AddressOf());
  4534. asCString templateName(&script->code[sn->tokenPos], sn->tokenLength);
  4535. asCObjectType *templateType = GetObjectType(templateName.AddressOf(), ns);
  4536. if (templateType == 0 || (templateType->flags & asOBJ_TEMPLATE) == 0)
  4537. {
  4538. // TODO: child funcdef: Report error
  4539. return ns;
  4540. }
  4541. if (objType)
  4542. *objType = GetTemplateInstanceFromNode(sn, script, templateType, implicitNs, 0);
  4543. // Return no namespace, since this is an object type
  4544. return 0;
  4545. }
  4546. }
  4547. asCTypeInfo *ti = 0;
  4548. asSNameSpace *ns = GetNameSpaceByString(scope, implicitNs ? implicitNs : engine->nameSpaces[0], node, script, &ti);
  4549. if (ti && objType)
  4550. *objType = CastToObjectType(ti);
  4551. return ns;
  4552. }
  4553. asSNameSpace *asCBuilder::GetNameSpaceByString(const asCString &nsName, asSNameSpace *implicitNs, asCScriptNode *errNode, asCScriptCode *script, asCTypeInfo **scopeType, bool isRequired)
  4554. {
  4555. if( scopeType )
  4556. *scopeType = 0;
  4557. asSNameSpace *ns = implicitNs;
  4558. if( nsName == "::" )
  4559. ns = engine->nameSpaces[0];
  4560. else if( nsName != "" )
  4561. {
  4562. ns = engine->FindNameSpace(nsName.AddressOf());
  4563. if (ns == 0 && scopeType)
  4564. {
  4565. asCString typeName;
  4566. asCString searchNs;
  4567. // Split the scope with at the inner most ::
  4568. int pos = nsName.FindLast("::");
  4569. bool recursive = false;
  4570. if (pos >= 0)
  4571. {
  4572. // Fully qualified namespace
  4573. typeName = nsName.SubString(pos + 2);
  4574. searchNs = nsName.SubString(0, pos);
  4575. }
  4576. else
  4577. {
  4578. // Partially qualified, use the implicit namespace and then search recursively for the type
  4579. typeName = nsName;
  4580. searchNs = implicitNs->name;
  4581. recursive = true;
  4582. }
  4583. asSNameSpace *nsTmp = searchNs == "::" ? engine->nameSpaces[0] : engine->FindNameSpace(searchNs.AddressOf());
  4584. asCTypeInfo *ti = 0;
  4585. while( !ti && nsTmp )
  4586. {
  4587. // Check if the typeName is an existing type in the namespace
  4588. ti = GetType(typeName.AddressOf(), nsTmp, 0);
  4589. if (ti)
  4590. {
  4591. // The informed scope is not a namespace, but it does match a type
  4592. *scopeType = ti;
  4593. return 0;
  4594. }
  4595. nsTmp = recursive ? engine->GetParentNameSpace(nsTmp) : 0;
  4596. }
  4597. }
  4598. if (ns == 0 && isRequired)
  4599. {
  4600. asCString msg;
  4601. msg.Format(TXT_NAMESPACE_s_DOESNT_EXIST, nsName.AddressOf());
  4602. WriteError(msg, script, errNode);
  4603. }
  4604. }
  4605. return ns;
  4606. }
  4607. asCDataType asCBuilder::CreateDataTypeFromNode(asCScriptNode *node, asCScriptCode *file, asSNameSpace *implicitNamespace, bool acceptHandleForScope, asCObjectType *currentType, bool reportError, bool *isValid)
  4608. {
  4609. asASSERT(node->nodeType == snDataType || node->nodeType == snIdentifier || node->nodeType == snScope );
  4610. asCDataType dt;
  4611. asCScriptNode *n = node->firstChild;
  4612. if (isValid)
  4613. *isValid = true;
  4614. // If the informed node is an identifier or scope, then the
  4615. // datatype should be identified directly from that
  4616. if (node->nodeType != snDataType)
  4617. n = node;
  4618. bool isConst = false;
  4619. bool isImplicitHandle = false;
  4620. if( n->tokenType == ttConst )
  4621. {
  4622. isConst = true;
  4623. n = n->next;
  4624. }
  4625. // Determine namespace (or parent type) to search for the data type in
  4626. asCObjectType *parentType = 0;
  4627. asSNameSpace *ns = GetNameSpaceFromNode(n, file, implicitNamespace, &n, &parentType);
  4628. if( ns == 0 && parentType == 0 )
  4629. {
  4630. // The namespace and parent type doesn't exist. Return a dummy type instead.
  4631. dt = asCDataType::CreatePrimitive(ttInt, false);
  4632. if (isValid)
  4633. *isValid = false;
  4634. return dt;
  4635. }
  4636. if( n->tokenType == ttIdentifier )
  4637. {
  4638. bool found = false;
  4639. asCString str;
  4640. str.Assign(&file->code[n->tokenPos], n->tokenLength);
  4641. // Recursively search parent namespaces for matching type
  4642. asSNameSpace *origNs = ns;
  4643. asCObjectType *origParentType = parentType;
  4644. while( (ns || parentType) && !found )
  4645. {
  4646. asCTypeInfo *ti = 0;
  4647. if (currentType)
  4648. {
  4649. // If this is for a template type, then we must first determine if the
  4650. // identifier matches any of the template subtypes
  4651. if (currentType->flags & asOBJ_TEMPLATE)
  4652. {
  4653. for (asUINT subtypeIndex = 0; subtypeIndex < currentType->templateSubTypes.GetLength(); subtypeIndex++)
  4654. {
  4655. asCTypeInfo *type = currentType->templateSubTypes[subtypeIndex].GetTypeInfo();
  4656. if (type && str == type->name)
  4657. {
  4658. ti = type;
  4659. break;
  4660. }
  4661. }
  4662. }
  4663. if (ti == 0)
  4664. {
  4665. // Check if the type is a child type of the current type
  4666. ti = GetFuncDef(str.AddressOf(), 0, currentType);
  4667. if (ti)
  4668. {
  4669. dt = asCDataType::CreateType(ti, false);
  4670. found = true;
  4671. }
  4672. }
  4673. }
  4674. if( ti == 0 )
  4675. ti = GetType(str.AddressOf(), ns, parentType);
  4676. if( ti == 0 && !module && currentType )
  4677. ti = GetTypeFromTypesKnownByObject(str.AddressOf(), currentType);
  4678. if( ti && !found )
  4679. {
  4680. found = true;
  4681. if( ti->flags & asOBJ_IMPLICIT_HANDLE )
  4682. isImplicitHandle = true;
  4683. // Make sure the module has access to the object type
  4684. if( !module || (module->accessMask & ti->accessMask) )
  4685. {
  4686. if( asOBJ_TYPEDEF == (ti->flags & asOBJ_TYPEDEF) )
  4687. {
  4688. // TODO: typedef: A typedef should be considered different from the original type (though with implicit conversions between the two)
  4689. // Create primitive data type based on object flags
  4690. dt = CastToTypedefType(ti)->aliasForType;
  4691. dt.MakeReadOnly(isConst);
  4692. }
  4693. else
  4694. {
  4695. if( ti->flags & asOBJ_TEMPLATE )
  4696. {
  4697. ti = GetTemplateInstanceFromNode(n, file, CastToObjectType(ti), implicitNamespace, currentType, &n);
  4698. if (ti == 0)
  4699. {
  4700. if (isValid)
  4701. *isValid = false;
  4702. // Return a dummy
  4703. return asCDataType::CreatePrimitive(ttInt, false);
  4704. }
  4705. }
  4706. else if( n && n->next && n->next->nodeType == snDataType )
  4707. {
  4708. if (reportError)
  4709. {
  4710. asCString msg;
  4711. msg.Format(TXT_TYPE_s_NOT_TEMPLATE, ti->name.AddressOf());
  4712. WriteError(msg, file, n);
  4713. }
  4714. if (isValid)
  4715. *isValid = false;
  4716. }
  4717. // Create object data type
  4718. if( ti )
  4719. dt = asCDataType::CreateType(ti, isConst);
  4720. else
  4721. dt = asCDataType::CreatePrimitive(ttInt, isConst);
  4722. }
  4723. }
  4724. else
  4725. {
  4726. if (reportError)
  4727. {
  4728. asCString msg;
  4729. msg.Format(TXT_TYPE_s_NOT_AVAILABLE_FOR_MODULE, (const char *)str.AddressOf());
  4730. WriteError(msg, file, n);
  4731. }
  4732. dt.SetTokenType(ttInt);
  4733. if (isValid)
  4734. *isValid = false;
  4735. }
  4736. }
  4737. if( !found )
  4738. {
  4739. // Try to find it in the parent namespace
  4740. if( ns )
  4741. ns = engine->GetParentNameSpace(ns);
  4742. if (parentType)
  4743. parentType = 0;
  4744. }
  4745. }
  4746. if( !found )
  4747. {
  4748. if (reportError)
  4749. {
  4750. asCString msg;
  4751. if (origNs && origNs->name == "")
  4752. msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_GLOBAL_NS, str.AddressOf());
  4753. else if (origNs)
  4754. msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_NS_s, str.AddressOf(), origNs->name.AddressOf());
  4755. else
  4756. {
  4757. // TODO: child funcdef: Message should explain that the identifier is not a type of the parent type
  4758. asCDataType pt = asCDataType::CreateType(origParentType, false);
  4759. msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE_IN_NS_s, str.AddressOf(), pt.Format(origParentType->nameSpace, false).AddressOf());
  4760. }
  4761. WriteError(msg, file, n);
  4762. }
  4763. dt = asCDataType::CreatePrimitive(ttInt, isConst);
  4764. if (isValid)
  4765. *isValid = false;
  4766. return dt;
  4767. }
  4768. }
  4769. else if( n->tokenType == ttAuto )
  4770. {
  4771. dt = asCDataType::CreateAuto(isConst);
  4772. }
  4773. else
  4774. {
  4775. // Create primitive data type
  4776. dt = asCDataType::CreatePrimitive(n->tokenType, isConst);
  4777. }
  4778. // Determine array dimensions and object handles
  4779. n = n->next;
  4780. while( n && (n->tokenType == ttOpenBracket || n->tokenType == ttHandle) )
  4781. {
  4782. if( n->tokenType == ttOpenBracket )
  4783. {
  4784. // Make sure the sub type can be instantiated
  4785. if( !dt.CanBeInstantiated() )
  4786. {
  4787. if (reportError)
  4788. {
  4789. asCString str;
  4790. if (dt.IsAbstractClass())
  4791. str.Format(TXT_ABSTRACT_CLASS_s_CANNOT_BE_INSTANTIATED, dt.Format(ns).AddressOf());
  4792. else if (dt.IsInterface())
  4793. str.Format(TXT_INTERFACE_s_CANNOT_BE_INSTANTIATED, dt.Format(ns).AddressOf());
  4794. else
  4795. // TODO: Improve error message to explain why
  4796. str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format(ns).AddressOf());
  4797. WriteError(str, file, n);
  4798. }
  4799. if (isValid)
  4800. *isValid = false;
  4801. }
  4802. // Make the type an array (or multidimensional array)
  4803. if( dt.MakeArray(engine, module) < 0 )
  4804. {
  4805. if( reportError )
  4806. WriteError(TXT_NO_DEFAULT_ARRAY_TYPE, file, n);
  4807. if (isValid)
  4808. *isValid = false;
  4809. break;
  4810. }
  4811. }
  4812. else
  4813. {
  4814. // Make the type a handle
  4815. if( dt.IsObjectHandle() )
  4816. {
  4817. if( reportError )
  4818. WriteError(TXT_HANDLE_OF_HANDLE_IS_NOT_ALLOWED, file, n);
  4819. if (isValid)
  4820. *isValid = false;
  4821. break;
  4822. }
  4823. else if( dt.MakeHandle(true, acceptHandleForScope) < 0 )
  4824. {
  4825. if( reportError )
  4826. WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
  4827. if (isValid)
  4828. *isValid = false;
  4829. break;
  4830. }
  4831. }
  4832. n = n->next;
  4833. }
  4834. if( isImplicitHandle )
  4835. {
  4836. // Make the type a handle
  4837. if (dt.MakeHandle(true, acceptHandleForScope) < 0)
  4838. {
  4839. if( reportError )
  4840. WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
  4841. if (isValid)
  4842. *isValid = false;
  4843. }
  4844. }
  4845. return dt;
  4846. }
  4847. asCObjectType *asCBuilder::GetTemplateInstanceFromNode(asCScriptNode *node, asCScriptCode *file, asCObjectType *templateType, asSNameSpace *implicitNamespace, asCObjectType *currentType, asCScriptNode **next)
  4848. {
  4849. // Check if the subtype is a type or the template's subtype
  4850. // if it is the template's subtype then this is the actual template type,
  4851. // orderwise it is a template instance.
  4852. // Only do this for application registered interface, as the
  4853. // scripts cannot implement templates.
  4854. asCArray<asCDataType> subTypes;
  4855. asUINT subtypeIndex;
  4856. asCScriptNode *n = node;
  4857. while (n && n->next && n->next->nodeType == snDataType)
  4858. {
  4859. n = n->next;
  4860. // When parsing function definitions for template registrations (currentType != 0) it is necessary
  4861. // to pass in the current template type to the recursive call since it is this ones sub-template types
  4862. // that should be allowed.
  4863. asCDataType subType = CreateDataTypeFromNode(n, file, implicitNamespace, false, module ? 0 : (currentType ? currentType : templateType));
  4864. subTypes.PushLast(subType);
  4865. if (subType.IsReadOnly())
  4866. {
  4867. asCString msg;
  4868. msg.Format(TXT_TMPL_SUBTYPE_MUST_NOT_BE_READ_ONLY);
  4869. WriteError(msg, file, n);
  4870. // Return a dummy
  4871. return 0;
  4872. }
  4873. }
  4874. if (next)
  4875. *next = n;
  4876. if (subTypes.GetLength() != templateType->templateSubTypes.GetLength())
  4877. {
  4878. asCString msg;
  4879. msg.Format(TXT_TMPL_s_EXPECTS_d_SUBTYPES, templateType->name.AddressOf(), int(templateType->templateSubTypes.GetLength()));
  4880. WriteError(msg, file, node);
  4881. // Return a dummy
  4882. return 0;
  4883. }
  4884. // Check if any of the given subtypes are different from the template's declared subtypes
  4885. bool isDifferent = false;
  4886. for (subtypeIndex = 0; subtypeIndex < subTypes.GetLength(); subtypeIndex++)
  4887. {
  4888. if (subTypes[subtypeIndex].GetTypeInfo() != templateType->templateSubTypes[subtypeIndex].GetTypeInfo())
  4889. {
  4890. isDifferent = true;
  4891. break;
  4892. }
  4893. }
  4894. if (isDifferent)
  4895. {
  4896. // This is a template instance
  4897. // Need to find the correct object type
  4898. asCObjectType *otInstance = engine->GetTemplateInstanceType(templateType, subTypes, module);
  4899. if (otInstance && otInstance->scriptSectionIdx < 0)
  4900. {
  4901. // If this is the first time the template instance is used, store where it was declared from
  4902. otInstance->scriptSectionIdx = engine->GetScriptSectionNameIndex(file->name.AddressOf());
  4903. int row, column;
  4904. file->ConvertPosToRowCol(n->tokenPos, &row, &column);
  4905. otInstance->declaredAt = (row & 0xFFFFF) | (column << 20);
  4906. }
  4907. if (!otInstance)
  4908. {
  4909. asCString sub = subTypes[0].Format(templateType->nameSpace);
  4910. for (asUINT s = 1; s < subTypes.GetLength(); s++)
  4911. {
  4912. sub += ",";
  4913. sub += subTypes[s].Format(templateType->nameSpace);
  4914. }
  4915. asCString msg;
  4916. msg.Format(TXT_INSTANCING_INVLD_TMPL_TYPE_s_s, templateType->name.AddressOf(), sub.AddressOf());
  4917. WriteError(msg, file, n);
  4918. }
  4919. return otInstance;
  4920. }
  4921. return templateType;
  4922. }
  4923. asCDataType asCBuilder::ModifyDataTypeFromNode(const asCDataType &type, asCScriptNode *node, asCScriptCode *file, asETypeModifiers *inOutFlags, bool *autoHandle)
  4924. {
  4925. asCDataType dt = type;
  4926. if( inOutFlags ) *inOutFlags = asTM_NONE;
  4927. // Is the argument sent by reference?
  4928. asCScriptNode *n = node->firstChild;
  4929. if( n && n->tokenType == ttAmp )
  4930. {
  4931. if (dt.GetTokenType() == ttVoid)
  4932. {
  4933. asCString msg;
  4934. msg.Format(TXT_TYPE_s_CANNOT_BE_REFERENCE, type.Format(0).AddressOf());
  4935. WriteError(msg, file, node->firstChild);
  4936. return dt;
  4937. }
  4938. dt.MakeReference(true);
  4939. n = n->next;
  4940. if( n )
  4941. {
  4942. if( inOutFlags )
  4943. {
  4944. if( n->tokenType == ttIn )
  4945. *inOutFlags = asTM_INREF;
  4946. else if( n->tokenType == ttOut )
  4947. *inOutFlags = asTM_OUTREF;
  4948. else if( n->tokenType == ttInOut )
  4949. *inOutFlags = asTM_INOUTREF;
  4950. else
  4951. asASSERT(false);
  4952. }
  4953. n = n->next;
  4954. }
  4955. else
  4956. {
  4957. if( inOutFlags )
  4958. *inOutFlags = asTM_INOUTREF; // ttInOut
  4959. }
  4960. if( !engine->ep.allowUnsafeReferences &&
  4961. inOutFlags && *inOutFlags == asTM_INOUTREF &&
  4962. !(dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE)) )
  4963. {
  4964. // Verify that the base type support &inout parameter types
  4965. if( !dt.IsObject() || dt.IsObjectHandle() ||
  4966. !((dt.GetTypeInfo()->flags & asOBJ_NOCOUNT) || (CastToObjectType(dt.GetTypeInfo())->beh.addref && CastToObjectType(dt.GetTypeInfo())->beh.release)) )
  4967. WriteError(TXT_ONLY_OBJECTS_MAY_USE_REF_INOUT, file, node->firstChild);
  4968. }
  4969. }
  4970. if( autoHandle ) *autoHandle = false;
  4971. if( n && n->tokenType == ttPlus )
  4972. {
  4973. // Autohandles are not supported for types with NOCOUNT
  4974. // If the type is not a handle then there was an error with building the type, but
  4975. // this error would already have been reported so no need to report another error here
  4976. if( dt.IsObjectHandle() && (dt.GetTypeInfo()->flags & asOBJ_NOCOUNT) )
  4977. WriteError(TXT_AUTOHANDLE_CANNOT_BE_USED_FOR_NOCOUNT, file, node->firstChild);
  4978. if( autoHandle ) *autoHandle = true;
  4979. }
  4980. if (n && n->tokenType == ttIdentifier)
  4981. {
  4982. asCString str;
  4983. str.Assign(&file->code[n->tokenPos], n->tokenLength);
  4984. if (str == IF_HANDLE_TOKEN)
  4985. dt.SetIfHandleThenConst(true);
  4986. else
  4987. {
  4988. // TODO: Should give error if not currently parsing template registration
  4989. asCString msg;
  4990. msg.Format(TXT_UNEXPECTED_TOKEN_s, str.AddressOf());
  4991. WriteError(msg, file, node->firstChild);
  4992. }
  4993. }
  4994. return dt;
  4995. }
  4996. asCTypeInfo *asCBuilder::GetType(const char *type, asSNameSpace *ns, asCObjectType *parentType)
  4997. {
  4998. asASSERT((ns == 0 && parentType) || (ns && parentType == 0));
  4999. if (ns)
  5000. {
  5001. asCTypeInfo *ti = engine->GetRegisteredType(type, ns);
  5002. if (!ti && module)
  5003. ti = module->GetType(type, ns);
  5004. return ti;
  5005. }
  5006. else
  5007. {
  5008. // Recursively check base classes
  5009. asCObjectType *currType = parentType;
  5010. while (currType)
  5011. {
  5012. for (asUINT n = 0; n < currType->childFuncDefs.GetLength(); n++)
  5013. {
  5014. asCFuncdefType *funcDef = currType->childFuncDefs[n];
  5015. if (funcDef && funcDef->name == type)
  5016. return funcDef;
  5017. }
  5018. currType = currType->derivedFrom;
  5019. }
  5020. }
  5021. return 0;
  5022. }
  5023. asCObjectType *asCBuilder::GetObjectType(const char *type, asSNameSpace *ns)
  5024. {
  5025. return CastToObjectType(GetType(type, ns, 0));
  5026. }
  5027. #ifndef AS_NO_COMPILER
  5028. // This function will return true if there are any types in the engine or module
  5029. // with the given name. The namespace is ignored in this verification.
  5030. bool asCBuilder::DoesTypeExist(const asCString &type)
  5031. {
  5032. asUINT n;
  5033. // This function is only used when parsing expressions for building bytecode
  5034. // and this is only done after all types are known. For this reason the types
  5035. // can be safely cached in a map for quick lookup. Once the builder is released
  5036. // the cache will also be destroyed thus avoiding unnecessary memory consumption.
  5037. if( !hasCachedKnownTypes )
  5038. {
  5039. // Only do this once
  5040. hasCachedKnownTypes = true;
  5041. // Add registered types
  5042. asSMapNode<asSNameSpaceNamePair, asCTypeInfo*> *cursor;
  5043. engine->allRegisteredTypes.MoveFirst(&cursor);
  5044. while( cursor )
  5045. {
  5046. if( !knownTypes.MoveTo(0, cursor->key.name) )
  5047. knownTypes.Insert(cursor->key.name, true);
  5048. engine->allRegisteredTypes.MoveNext(&cursor, cursor);
  5049. }
  5050. if (module)
  5051. {
  5052. // Add script classes and interfaces
  5053. for (n = 0; n < module->classTypes.GetLength(); n++)
  5054. if (!knownTypes.MoveTo(0, module->classTypes[n]->name))
  5055. knownTypes.Insert(module->classTypes[n]->name, true);
  5056. // Add script enums
  5057. for (n = 0; n < module->enumTypes.GetLength(); n++)
  5058. if (!knownTypes.MoveTo(0, module->enumTypes[n]->name))
  5059. knownTypes.Insert(module->enumTypes[n]->name, true);
  5060. // Add script typedefs
  5061. for (n = 0; n < module->typeDefs.GetLength(); n++)
  5062. if (!knownTypes.MoveTo(0, module->typeDefs[n]->name))
  5063. knownTypes.Insert(module->typeDefs[n]->name, true);
  5064. // Add script funcdefs
  5065. for (n = 0; n < module->funcDefs.GetLength(); n++)
  5066. if (!knownTypes.MoveTo(0, module->funcDefs[n]->name))
  5067. knownTypes.Insert(module->funcDefs[n]->name, true);
  5068. }
  5069. }
  5070. // Check if the type is known
  5071. return knownTypes.MoveTo(0, type);
  5072. }
  5073. #endif
  5074. asCTypeInfo *asCBuilder::GetTypeFromTypesKnownByObject(const char *type, asCObjectType *currentType)
  5075. {
  5076. if (currentType->name == type)
  5077. return currentType;
  5078. asUINT n;
  5079. asCTypeInfo *found = 0;
  5080. for (n = 0; found == 0 && n < currentType->properties.GetLength(); n++)
  5081. if (currentType->properties[n]->type.GetTypeInfo() &&
  5082. currentType->properties[n]->type.GetTypeInfo()->name == type)
  5083. found = currentType->properties[n]->type.GetTypeInfo();
  5084. for (n = 0; found == 0 && n < currentType->methods.GetLength(); n++)
  5085. {
  5086. asCScriptFunction *func = engine->scriptFunctions[currentType->methods[n]];
  5087. if (func->returnType.GetTypeInfo() &&
  5088. func->returnType.GetTypeInfo()->name == type)
  5089. found = func->returnType.GetTypeInfo();
  5090. for (asUINT f = 0; found == 0 && f < func->parameterTypes.GetLength(); f++)
  5091. if (func->parameterTypes[f].GetTypeInfo() &&
  5092. func->parameterTypes[f].GetTypeInfo()->name == type)
  5093. found = func->parameterTypes[f].GetTypeInfo();
  5094. }
  5095. if (found)
  5096. {
  5097. // In case we find a template instance it mustn't be returned
  5098. // because it is not known if the subtype is really matching
  5099. if (found->flags & asOBJ_TEMPLATE)
  5100. return 0;
  5101. }
  5102. return found;
  5103. }
  5104. asCFuncdefType *asCBuilder::GetFuncDef(const char *type, asSNameSpace *ns, asCObjectType *parentType)
  5105. {
  5106. asASSERT((ns == 0 && parentType) || (ns && parentType == 0));
  5107. if (ns)
  5108. {
  5109. for (asUINT n = 0; n < engine->registeredFuncDefs.GetLength(); n++)
  5110. {
  5111. asCFuncdefType *funcDef = engine->registeredFuncDefs[n];
  5112. // TODO: access: Only return the definitions that the module has access to
  5113. if (funcDef && funcDef->nameSpace == ns && funcDef->name == type)
  5114. return funcDef;
  5115. }
  5116. if (module)
  5117. {
  5118. for (asUINT n = 0; n < module->funcDefs.GetLength(); n++)
  5119. {
  5120. asCFuncdefType *funcDef = module->funcDefs[n];
  5121. if (funcDef && funcDef->nameSpace == ns && funcDef->name == type)
  5122. return funcDef;
  5123. }
  5124. }
  5125. }
  5126. else
  5127. {
  5128. // Recursively check base classes
  5129. asCObjectType *currType = parentType;
  5130. while (currType)
  5131. {
  5132. for (asUINT n = 0; n < currType->childFuncDefs.GetLength(); n++)
  5133. {
  5134. asCFuncdefType *funcDef = currType->childFuncDefs[n];
  5135. if (funcDef && funcDef->name == type)
  5136. return funcDef;
  5137. }
  5138. currType = currType->derivedFrom;
  5139. }
  5140. }
  5141. return 0;
  5142. }
  5143. #ifndef AS_NO_COMPILER
  5144. int asCBuilder::GetEnumValueFromType(asCEnumType *type, const char *name, asCDataType &outDt, asDWORD &outValue)
  5145. {
  5146. if( !type || !(type->flags & asOBJ_ENUM) )
  5147. return 0;
  5148. for( asUINT n = 0; n < type->enumValues.GetLength(); ++n )
  5149. {
  5150. if( type->enumValues[n]->name == name )
  5151. {
  5152. outDt = asCDataType::CreateType(type, true);
  5153. outValue = type->enumValues[n]->value;
  5154. return 1;
  5155. }
  5156. }
  5157. return 0;
  5158. }
  5159. int asCBuilder::GetEnumValue(const char *name, asCDataType &outDt, asDWORD &outValue, asSNameSpace *ns)
  5160. {
  5161. bool found = false;
  5162. // Search all available enum types
  5163. asUINT t;
  5164. for( t = 0; t < engine->registeredEnums.GetLength(); t++ )
  5165. {
  5166. asCEnumType *et = engine->registeredEnums[t];
  5167. if( ns != et->nameSpace ) continue;
  5168. // Don't bother with types the module doesn't have access to
  5169. if( (et->accessMask & module->accessMask) == 0 )
  5170. continue;
  5171. if( GetEnumValueFromType(et, name, outDt, outValue) )
  5172. {
  5173. if( !found )
  5174. found = true;
  5175. else
  5176. {
  5177. // Found more than one value in different enum types
  5178. return 2;
  5179. }
  5180. }
  5181. }
  5182. for( t = 0; t < module->enumTypes.GetLength(); t++ )
  5183. {
  5184. asCEnumType *et = module->enumTypes[t];
  5185. if( ns != et->nameSpace ) continue;
  5186. if( GetEnumValueFromType(et, name, outDt, outValue) )
  5187. {
  5188. if( !found )
  5189. found = true;
  5190. else
  5191. {
  5192. // Found more than one value in different enum types
  5193. return 2;
  5194. }
  5195. }
  5196. }
  5197. if( found )
  5198. return 1;
  5199. // Didn't find any value
  5200. return 0;
  5201. }
  5202. #endif // AS_NO_COMPILER
  5203. END_AS_NAMESPACE