as_builder.cpp 178 KB

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