as_builder.cpp 174 KB

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