as_builder.cpp 185 KB

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