as_builder.cpp 186 KB

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