as_compiler.cpp 343 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2011 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. // Modified by Lasse Öörni for Urho3D
  24. //
  25. // as_compiler.cpp
  26. //
  27. // The class that does the actual compilation of the functions
  28. //
  29. #include <math.h> // fmodf()
  30. #include "as_config.h"
  31. #include "as_compiler.h"
  32. #include "as_tokendef.h"
  33. #include "as_tokenizer.h"
  34. #include "as_string_util.h"
  35. #include "as_texts.h"
  36. #include "as_parser.h"
  37. BEGIN_AS_NAMESPACE
  38. // TODO: I must correct the interpretation of a references to objects in the compiler.
  39. // A reference should mean that a pointer to the object is on the stack.
  40. // No expression should end up as non-references to objects, as the actual object is
  41. // never put on the stack.
  42. // Local variables are declared as non-references, but the expression should be a reference to the variable.
  43. // Function parameters of called functions can also be non-references, but in that case it means the
  44. // object will be passed by value (currently on the heap, which will be moved to the application stack).
  45. asCCompiler::asCCompiler(asCScriptEngine *engine) : byteCode(engine)
  46. {
  47. builder = 0;
  48. script = 0;
  49. variables = 0;
  50. isProcessingDeferredParams = false;
  51. isCompilingDefaultArg = false;
  52. noCodeOutput = 0;
  53. }
  54. asCCompiler::~asCCompiler()
  55. {
  56. while( variables )
  57. {
  58. asCVariableScope *var = variables;
  59. variables = variables->parent;
  60. asDELETE(var,asCVariableScope);
  61. }
  62. }
  63. void asCCompiler::Reset(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  64. {
  65. this->builder = builder;
  66. this->engine = builder->engine;
  67. this->script = script;
  68. this->outFunc = outFunc;
  69. hasCompileErrors = false;
  70. m_isConstructor = false;
  71. m_isConstructorCalled = false;
  72. nextLabel = 0;
  73. breakLabels.SetLength(0);
  74. continueLabels.SetLength(0);
  75. byteCode.ClearAll();
  76. }
  77. int asCCompiler::CompileDefaultConstructor(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  78. {
  79. Reset(builder, script, outFunc);
  80. // If the class is derived from another, then the base class' default constructor must be called
  81. if( outFunc->objectType->derivedFrom )
  82. {
  83. // Call the base class' default constructor
  84. byteCode.InstrSHORT(asBC_PSF, 0);
  85. byteCode.Instr(asBC_RDSPTR);
  86. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  87. }
  88. // Pop the object pointer from the stack
  89. byteCode.Ret(AS_PTR_SIZE);
  90. FinalizeFunction();
  91. #ifdef AS_DEBUG
  92. // DEBUG: output byte code
  93. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + "__dc.txt").AddressOf(), engine, outFunc);
  94. #endif
  95. return 0;
  96. }
  97. int asCCompiler::CompileFactory(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  98. {
  99. Reset(builder, script, outFunc);
  100. unsigned int n;
  101. // Find the corresponding constructor
  102. asCDataType dt = asCDataType::CreateObject(outFunc->returnType.GetObjectType(), false);
  103. int constructor = 0;
  104. for( n = 0; n < dt.GetBehaviour()->factories.GetLength(); n++ )
  105. {
  106. if( dt.GetBehaviour()->factories[n] == outFunc->id )
  107. {
  108. constructor = dt.GetBehaviour()->constructors[n];
  109. break;
  110. }
  111. }
  112. // Allocate the class and instanciate it with the constructor
  113. int varOffset = AllocateVariable(dt, true);
  114. byteCode.Push(AS_PTR_SIZE);
  115. byteCode.InstrSHORT(asBC_PSF, (short)varOffset);
  116. // Copy all arguments to the top of the stack
  117. int argDwords = (int)outFunc->GetSpaceNeededForArguments();
  118. for( int a = argDwords-1; a >= 0; a-- )
  119. byteCode.InstrSHORT(asBC_PshV4, short(-a));
  120. byteCode.Alloc(asBC_ALLOC, dt.GetObjectType(), constructor, argDwords + AS_PTR_SIZE);
  121. // Return a handle to the newly created object
  122. byteCode.InstrSHORT(asBC_LOADOBJ, (short)varOffset);
  123. byteCode.Ret(argDwords);
  124. FinalizeFunction();
  125. // Tell the virtual machine not to clean up parameters on exception
  126. outFunc->dontCleanUpOnException = true;
  127. /*
  128. #ifdef AS_DEBUG
  129. // DEBUG: output byte code
  130. asCString args;
  131. args.Format("%d", outFunc->parameterTypes.GetLength());
  132. byteCode.DebugOutput(("__" + outFunc->name + "__factory" + args + ".txt").AddressOf(), engine);
  133. #endif
  134. */
  135. return 0;
  136. }
  137. // Entry
  138. int asCCompiler::CompileTemplateFactoryStub(asCBuilder *builder, int trueFactoryId, asCObjectType *objType, asCScriptFunction *outFunc)
  139. {
  140. Reset(builder, 0, outFunc);
  141. asCScriptFunction *descr = builder->GetFunctionDescription(trueFactoryId);
  142. byteCode.InstrPTR(asBC_OBJTYPE, objType);
  143. byteCode.Call(asBC_CALLSYS, trueFactoryId, descr->GetSpaceNeededForArguments());
  144. byteCode.Ret(outFunc->GetSpaceNeededForArguments());
  145. FinalizeFunction();
  146. // Tell the virtual machine not to clean up the object on exception
  147. outFunc->dontCleanUpOnException = true;
  148. return 0;
  149. }
  150. // Entry
  151. int asCCompiler::CompileFunction(asCBuilder *builder, asCScriptCode *script, asCScriptNode *func, asCScriptFunction *outFunc)
  152. {
  153. Reset(builder, script, outFunc);
  154. int buildErrors = builder->numErrors;
  155. int stackPos = 0;
  156. if( outFunc->objectType )
  157. stackPos = -AS_PTR_SIZE; // The first parameter is the pointer to the object
  158. // Reserve a label for the cleanup code
  159. nextLabel++;
  160. // Add the first variable scope, which the parameters and
  161. // variables declared in the outermost statement block is
  162. // part of.
  163. AddVariableScope();
  164. // Skip the private keyword if it is there
  165. asCScriptNode *node = func->firstChild;
  166. if( node->nodeType == snUndefined && node->tokenType == ttPrivate )
  167. node = node->next;
  168. //----------------------------------------------
  169. // Examine return type
  170. bool isDestructor = false;
  171. asCDataType returnType;
  172. if( node->nodeType == snDataType )
  173. {
  174. returnType = builder->CreateDataTypeFromNode(node, script);
  175. returnType = builder->ModifyDataTypeFromNode(returnType, node->next, script, 0, 0);
  176. // Make sure the return type is instanciable or is void
  177. if( !returnType.CanBeInstanciated() &&
  178. returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  179. {
  180. asCString str;
  181. str.Format(TXT_DATA_TYPE_CANT_BE_s, returnType.Format().AddressOf());
  182. Error(str.AddressOf(), func->firstChild);
  183. }
  184. #ifndef AS_OLD
  185. // If the return type is a value type returned by value the address of the
  186. // location where the value will be stored is pushed on the stack before
  187. // the arguments
  188. if( outFunc->DoesReturnOnStack() )
  189. stackPos -= AS_PTR_SIZE;
  190. #endif
  191. }
  192. else
  193. {
  194. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  195. if( node->tokenType == ttBitNot )
  196. isDestructor = true;
  197. else
  198. m_isConstructor = true;
  199. }
  200. //----------------------------------------------
  201. // Declare parameters
  202. // Find first parameter
  203. while( node && node->nodeType != snParameterList )
  204. node = node->next;
  205. // Register parameters from last to first, otherwise they will be destroyed in the wrong order
  206. asCVariableScope vs(0);
  207. if( node ) node = node->firstChild;
  208. while( node )
  209. {
  210. // Get the parameter type
  211. asCDataType type = builder->CreateDataTypeFromNode(node, script);
  212. asETypeModifiers inoutFlag = asTM_NONE;
  213. type = builder->ModifyDataTypeFromNode(type, node->next, script, &inoutFlag, 0);
  214. // Is the data type allowed?
  215. if( (type.IsReference() && inoutFlag != asTM_INOUTREF && !type.CanBeInstanciated()) ||
  216. (!type.IsReference() && !type.CanBeInstanciated()) )
  217. {
  218. asCString str;
  219. str.Format(TXT_PARAMETER_CANT_BE_s, type.Format().AddressOf());
  220. Error(str.AddressOf(), node);
  221. }
  222. // If the parameter has a name then declare it as variable
  223. node = node->next->next;
  224. if( node && node->nodeType == snIdentifier )
  225. {
  226. asCString name(&script->code[node->tokenPos], node->tokenLength);
  227. if( vs.DeclareVariable(name.AddressOf(), type, stackPos, true) < 0 )
  228. Error(TXT_PARAMETER_ALREADY_DECLARED, node);
  229. // Add marker for variable declaration
  230. byteCode.VarDecl((int)outFunc->variables.GetLength());
  231. outFunc->AddVariable(name, type, stackPos);
  232. node = node->next;
  233. // Skip the default arg
  234. if( node && node->nodeType == snExpression )
  235. node = node->next;
  236. }
  237. else
  238. vs.DeclareVariable("", type, stackPos, true);
  239. // Move to next parameter
  240. stackPos -= type.GetSizeOnStackDWords();
  241. }
  242. int n;
  243. for( n = (int)vs.variables.GetLength() - 1; n >= 0; n-- )
  244. {
  245. variables->DeclareVariable(vs.variables[n]->name.AddressOf(), vs.variables[n]->type, vs.variables[n]->stackOffset, vs.variables[n]->onHeap);
  246. }
  247. // Is the return type allowed?
  248. if( (returnType.GetSizeOnStackDWords() == 0 && returnType != asCDataType::CreatePrimitive(ttVoid, false)) ||
  249. (returnType.IsReference() && !returnType.CanBeInstanciated()) )
  250. {
  251. asCString str;
  252. str.Format(TXT_RETURN_CANT_BE_s, returnType.Format().AddressOf());
  253. Error(str.AddressOf(), func);
  254. }
  255. variables->DeclareVariable("return", returnType, stackPos, true);
  256. //--------------------------------------------
  257. // Compile the statement block
  258. // We need to parse the statement block now
  259. // TODO: memory: We can parse the statement block one statement at a time, thus save even more memory
  260. asCParser parser(builder);
  261. int r = parser.ParseStatementBlock(script, func->lastChild);
  262. if( r < 0 ) return -1;
  263. asCScriptNode *block = parser.GetScriptNode();
  264. bool hasReturn;
  265. asCByteCode bc(engine);
  266. LineInstr(&bc, func->lastChild->tokenPos);
  267. CompileStatementBlock(block, false, &hasReturn, &bc);
  268. LineInstr(&bc, func->lastChild->tokenPos + func->lastChild->tokenLength);
  269. // Make sure there is a return in all paths (if not return type is void)
  270. if( returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  271. {
  272. if( hasReturn == false )
  273. Error(TXT_NOT_ALL_PATHS_RETURN, func->lastChild);
  274. }
  275. //------------------------------------------------
  276. // Concatenate the bytecode
  277. // Insert a JitEntry at the start of the function for JIT compilers
  278. byteCode.InstrPTR(asBC_JitEntry, 0);
  279. // Count total variable size
  280. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  281. byteCode.Push(varSize);
  282. if( outFunc->objectType )
  283. {
  284. // Call the base class' default constructor unless called manually in the code
  285. if( m_isConstructor && !m_isConstructorCalled && outFunc->objectType->derivedFrom )
  286. {
  287. byteCode.InstrSHORT(asBC_PSF, 0);
  288. byteCode.Instr(asBC_RDSPTR);
  289. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  290. }
  291. // Increase the reference for the object pointer, so that it is guaranteed to live during the entire call
  292. // TODO: optimize: This is probably not necessary for constructors as no outside reference to the object is created yet
  293. byteCode.InstrSHORT(asBC_PSF, 0);
  294. byteCode.Instr(asBC_RDSPTR);
  295. byteCode.Call(asBC_CALLSYS, outFunc->objectType->beh.addref, AS_PTR_SIZE);
  296. }
  297. // Add the code for the statement block
  298. byteCode.AddCode(&bc);
  299. // Deallocate all local variables
  300. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  301. {
  302. sVariable *v = variables->variables[n];
  303. if( v->stackOffset > 0 )
  304. {
  305. // Call variables destructors
  306. if( v->name != "return" && v->name != "return address" )
  307. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  308. DeallocateVariable(v->stackOffset);
  309. }
  310. }
  311. // This is the label that return statements jump to
  312. // in order to exit the function
  313. byteCode.Label(0);
  314. // Call destructors for function parameters
  315. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  316. {
  317. sVariable *v = variables->variables[n];
  318. if( v->stackOffset <= 0 )
  319. {
  320. // Call variable destructors here, for variables not yet destroyed
  321. if( v->name != "return" && v->name != "return address" )
  322. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  323. }
  324. // Do not deallocate parameters
  325. }
  326. // Release the object pointer again
  327. if( outFunc->objectType )
  328. {
  329. byteCode.InstrW_PTR(asBC_FREE, 0, outFunc->objectType);
  330. }
  331. // If there are compile errors, there is no reason to build the final code
  332. if( hasCompileErrors || builder->numErrors != buildErrors )
  333. return -1;
  334. // At this point there should be no variables allocated
  335. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  336. // Remove the variable scope
  337. RemoveVariableScope();
  338. // This POP is not necessary as the return will clean up the stack frame anyway.
  339. // The bytecode optimizer would remove this POP, however by not including it here
  340. // it is guaranteed it doesn't have to be adjusted by the asCRestore class when
  341. // a types are of a different size than originally compiled for.
  342. // byteCode.Pop(varSize);
  343. byteCode.Ret(-stackPos);
  344. FinalizeFunction();
  345. #ifdef AS_DEBUG
  346. // DEBUG: output byte code
  347. if( outFunc->objectType )
  348. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  349. else
  350. byteCode.DebugOutput(("__" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  351. #endif
  352. return 0;
  353. }
  354. int asCCompiler::CallCopyConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asSExprContext *arg, asCScriptNode *node, bool isGlobalVar, bool derefDest)
  355. {
  356. if( !type.IsObject() )
  357. return 0;
  358. // CallCopyConstructor should not be called for object handles.
  359. asASSERT(!type.IsObjectHandle() || (type.GetObjectType() && (type.GetObjectType()->flags & asOBJ_ASHANDLE)) );
  360. asCArray<asSExprContext*> args;
  361. args.PushLast(arg);
  362. // The reference parameter must be pushed on the stack
  363. asASSERT( arg->type.dataType.GetObjectType() == type.GetObjectType() );
  364. // Since we're calling the copy constructor, we have to trust the function to not do
  365. // anything stupid otherwise we will just enter a loop, as we try to make temporary
  366. // copies of the argument in order to guarantee safety.
  367. if( type.GetObjectType()->flags & asOBJ_REF )
  368. {
  369. asSExprContext ctx(engine);
  370. int func = 0;
  371. asSTypeBehaviour *beh = type.GetBehaviour();
  372. if( beh ) func = beh->copyfactory;
  373. if( func > 0 )
  374. {
  375. if( !isGlobalVar )
  376. {
  377. // Call factory and store the handle in the given variable
  378. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType(), true, offset);
  379. // Pop the reference left by the function call
  380. ctx.bc.Pop(AS_PTR_SIZE);
  381. }
  382. else
  383. {
  384. // Call factory
  385. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType());
  386. // Store the returned handle in the global variable
  387. ctx.bc.Instr(asBC_RDSPTR);
  388. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  389. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  390. ctx.bc.Pop(AS_PTR_SIZE);
  391. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  392. }
  393. bc->AddCode(&ctx.bc);
  394. return 0;
  395. }
  396. }
  397. else
  398. {
  399. asSTypeBehaviour *beh = type.GetBehaviour();
  400. int func = beh ? beh->copyconstruct : 0;
  401. if( func > 0 )
  402. {
  403. // Push the address where the object will be stored on the stack, before the argument
  404. // TODO: When the context is serializable this probably has to be changed, since this
  405. // pointer can remain on the stack while the context is suspended. There is no
  406. // risk the pointer becomes invalid though, there is just no easy way to serialize it.
  407. asCByteCode tmp(engine);
  408. if( isGlobalVar )
  409. tmp.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  410. else if( isObjectOnHeap )
  411. tmp.InstrSHORT(asBC_PSF, (short)offset);
  412. tmp.AddCode(bc);
  413. bc->AddCode(&tmp);
  414. // When the object is allocated on the stack the object pointer
  415. // must be pushed on the stack after the arguments
  416. if( !isObjectOnHeap )
  417. {
  418. asASSERT( !isGlobalVar );
  419. bc->InstrSHORT(asBC_PSF, (short)offset);
  420. if( derefDest )
  421. {
  422. // The variable is a reference to the real location, so we need to dereference it
  423. bc->Instr(asBC_RDSPTR);
  424. }
  425. }
  426. asSExprContext ctx(engine);
  427. PerformFunctionCall(func, &ctx, isObjectOnHeap, &args, type.GetObjectType());
  428. bc->AddCode(&ctx.bc);
  429. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  430. // Mark the object as initialized
  431. if( !isObjectOnHeap )
  432. bc->ObjInfo(offset, asOBJ_INIT);
  433. return 0;
  434. }
  435. }
  436. // Class has no copy constructor/factory.
  437. asCString str;
  438. str.Format(TXT_NO_COPY_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  439. Error(str.AddressOf(), node);
  440. return -1;
  441. }
  442. int asCCompiler::CallDefaultConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asCScriptNode *node, bool isGlobalVar, bool deferDest)
  443. {
  444. if( !type.IsObject() ||
  445. (type.IsObjectHandle() && !(type.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  446. return 0;
  447. if( type.GetObjectType()->flags & asOBJ_REF )
  448. {
  449. asSExprContext ctx(engine);
  450. ctx.exprNode = node;
  451. int func = 0;
  452. asSTypeBehaviour *beh = type.GetBehaviour();
  453. if( beh ) func = beh->factory;
  454. if( func > 0 )
  455. {
  456. if( !isGlobalVar )
  457. {
  458. // Call factory and store the handle in the given variable
  459. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType(), true, offset);
  460. // Pop the reference left by the function call
  461. ctx.bc.Pop(AS_PTR_SIZE);
  462. }
  463. else
  464. {
  465. // Call factory
  466. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  467. // Store the returned handle in the global variable
  468. ctx.bc.Instr(asBC_RDSPTR);
  469. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  470. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  471. ctx.bc.Pop(AS_PTR_SIZE);
  472. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  473. }
  474. bc->AddCode(&ctx.bc);
  475. return 0;
  476. }
  477. }
  478. else
  479. {
  480. asSTypeBehaviour *beh = type.GetBehaviour();
  481. int func = 0;
  482. if( beh ) func = beh->construct;
  483. // Allocate and initialize with the default constructor
  484. if( func != 0 || (type.GetObjectType()->flags & asOBJ_POD) )
  485. {
  486. if( !isObjectOnHeap )
  487. {
  488. asASSERT( !isGlobalVar );
  489. // There is nothing to do if there is no function,
  490. // as the memory is already allocated on the stack
  491. if( func )
  492. {
  493. // Call the constructor as a normal function
  494. bc->InstrSHORT(asBC_PSF, (short)offset);
  495. if( deferDest )
  496. bc->Instr(asBC_RDSPTR);
  497. asSExprContext ctx(engine);
  498. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  499. bc->AddCode(&ctx.bc);
  500. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  501. // Mark the object as initialized
  502. bc->ObjInfo(offset, asOBJ_INIT);
  503. }
  504. }
  505. else
  506. {
  507. if( isGlobalVar )
  508. bc->InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  509. else
  510. bc->InstrSHORT(asBC_PSF, (short)offset);
  511. bc->Alloc(asBC_ALLOC, type.GetObjectType(), func, AS_PTR_SIZE);
  512. }
  513. return 0;
  514. }
  515. }
  516. // Class has no default factory/constructor.
  517. asCString str;
  518. // TODO: funcdef: asCDataType should have a GetTypeName()
  519. if( type.GetFuncDef() )
  520. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetFuncDef()->GetName());
  521. else
  522. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  523. Error(str.AddressOf(), node);
  524. return -1;
  525. }
  526. void asCCompiler::CallDestructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc)
  527. {
  528. if( !type.IsReference() )
  529. {
  530. // Call destructor for the data type
  531. if( type.IsObject() )
  532. {
  533. // ASHANDLE is really a value type and shouldn't be deallocated. Just the destructor should be called
  534. if( isObjectOnHeap || (type.IsObjectHandle() && !(type.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  535. {
  536. // Free the memory
  537. bc->InstrW_PTR(asBC_FREE, (short)offset, type.GetObjectType());
  538. }
  539. else
  540. {
  541. asASSERT( type.GetObjectType()->GetFlags() & asOBJ_VALUE );
  542. if( type.GetBehaviour()->destruct )
  543. {
  544. // Call the destructor as a regular function
  545. bc->InstrSHORT(asBC_PSF, (short)offset);
  546. asSExprContext ctx(engine);
  547. PerformFunctionCall(type.GetBehaviour()->destruct, &ctx);
  548. bc->AddCode(&ctx.bc);
  549. }
  550. // TODO: Value on stack: This probably needs to be done in PerformFunctionCall
  551. // Mark the object as destroyed
  552. bc->ObjInfo(offset, asOBJ_UNINIT);
  553. }
  554. }
  555. }
  556. }
  557. void asCCompiler::LineInstr(asCByteCode *bc, size_t pos)
  558. {
  559. int r, c;
  560. script->ConvertPosToRowCol(pos, &r, &c);
  561. bc->Line(r, c);
  562. }
  563. void asCCompiler::CompileStatementBlock(asCScriptNode *block, bool ownVariableScope, bool *hasReturn, asCByteCode *bc)
  564. {
  565. *hasReturn = false;
  566. bool isFinished = false;
  567. bool hasWarned = false;
  568. if( ownVariableScope )
  569. {
  570. bc->Block(true);
  571. AddVariableScope();
  572. }
  573. asCScriptNode *node = block->firstChild;
  574. while( node )
  575. {
  576. if( !hasWarned && (*hasReturn || isFinished) )
  577. {
  578. hasWarned = true;
  579. Warning(TXT_UNREACHABLE_CODE, node);
  580. }
  581. if( node->nodeType == snBreak || node->nodeType == snContinue )
  582. isFinished = true;
  583. asCByteCode statement(engine);
  584. if( node->nodeType == snDeclaration )
  585. CompileDeclaration(node, &statement);
  586. else
  587. CompileStatement(node, hasReturn, &statement);
  588. LineInstr(bc, node->tokenPos);
  589. bc->AddCode(&statement);
  590. if( !hasCompileErrors )
  591. asASSERT( tempVariables.GetLength() == 0 );
  592. node = node->next;
  593. }
  594. if( ownVariableScope )
  595. {
  596. // Deallocate variables in this block, in reverse order
  597. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  598. {
  599. sVariable *v = variables->variables[n];
  600. // Call variable destructors here, for variables not yet destroyed
  601. // If the block is terminated with a break, continue, or
  602. // return the variables are already destroyed
  603. if( !isFinished && !*hasReturn )
  604. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  605. // Don't deallocate function parameters
  606. if( v->stackOffset > 0 )
  607. DeallocateVariable(v->stackOffset);
  608. }
  609. RemoveVariableScope();
  610. bc->Block(false);
  611. }
  612. }
  613. // Entry
  614. int asCCompiler::CompileGlobalVariable(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, sGlobalVariableDescription *gvar, asCScriptFunction *outFunc)
  615. {
  616. Reset(builder, script, outFunc);
  617. // Add a variable scope (even though variables can't be declared)
  618. AddVariableScope();
  619. asSExprContext ctx(engine);
  620. gvar->isPureConstant = false;
  621. // Parse the initialization nodes
  622. asCParser parser(builder);
  623. if( node )
  624. {
  625. int r = parser.ParseGlobalVarInit(script, node);
  626. if( r < 0 )
  627. return r;
  628. node = parser.GetScriptNode();
  629. }
  630. // Compile the expression
  631. if( node && node->nodeType == snArgList )
  632. {
  633. // Make sure that it is a registered type, and that it isn't a pointer
  634. if( gvar->datatype.GetObjectType() == 0 || gvar->datatype.IsObjectHandle() )
  635. {
  636. Error(TXT_MUST_BE_OBJECT, node);
  637. }
  638. else
  639. {
  640. // Compile the arguments
  641. asCArray<asSExprContext *> args;
  642. if( CompileArgumentList(node, args) >= 0 )
  643. {
  644. // Find all constructors
  645. asCArray<int> funcs;
  646. asSTypeBehaviour *beh = gvar->datatype.GetBehaviour();
  647. if( beh )
  648. {
  649. if( gvar->datatype.GetObjectType()->flags & asOBJ_REF )
  650. funcs = beh->factories;
  651. else
  652. funcs = beh->constructors;
  653. }
  654. asCString str = gvar->datatype.Format();
  655. MatchFunctions(funcs, args, node, str.AddressOf());
  656. if( funcs.GetLength() == 1 )
  657. {
  658. int r = asSUCCESS;
  659. // Add the default values for arguments not explicitly supplied
  660. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  661. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  662. r = CompileDefaultArgs(node, args, func);
  663. if( r == asSUCCESS )
  664. {
  665. if( gvar->datatype.GetObjectType()->flags & asOBJ_REF )
  666. {
  667. MakeFunctionCall(&ctx, funcs[0], 0, args, node);
  668. // Store the returned handle in the global variable
  669. ctx.bc.Instr(asBC_RDSPTR);
  670. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  671. ctx.bc.InstrPTR(asBC_REFCPY, gvar->datatype.GetObjectType());
  672. ctx.bc.Pop(AS_PTR_SIZE);
  673. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  674. }
  675. else
  676. {
  677. // Push the address of the location where the variable will be stored on the stack.
  678. // This reference is safe, because the addresses of the global variables cannot change.
  679. // TODO: When serialization of the context is implemented this will probably have to change,
  680. // because this pointer may be on the stack while the context is suspended, and may
  681. // be difficult to serialize as the context doesn't know that the value represents a
  682. // pointer.
  683. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  684. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  685. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  686. PerformFunctionCall(funcs[0], &ctx, true, &args, gvar->datatype.GetObjectType());
  687. }
  688. }
  689. }
  690. }
  691. // Cleanup
  692. for( asUINT n = 0; n < args.GetLength(); n++ )
  693. if( args[n] )
  694. {
  695. asDELETE(args[n],asSExprContext);
  696. }
  697. }
  698. }
  699. else if( node && node->nodeType == snInitList )
  700. {
  701. asCTypeInfo ti;
  702. ti.Set(gvar->datatype);
  703. ti.isVariable = false;
  704. ti.isTemporary = false;
  705. ti.stackOffset = (short)gvar->index;
  706. ti.isLValue = true;
  707. CompileInitList(&ti, node, &ctx.bc);
  708. node = node->next;
  709. }
  710. else if( node )
  711. {
  712. // Compile the right hand expression
  713. asSExprContext expr(engine);
  714. int r = CompileAssignment(node, &expr); if( r < 0 ) return r;
  715. // Assign the value to the variable
  716. if( gvar->datatype.IsPrimitive() )
  717. {
  718. if( gvar->datatype.IsReadOnly() && expr.type.isConstant )
  719. {
  720. ImplicitConversion(&expr, gvar->datatype, node, asIC_IMPLICIT_CONV);
  721. gvar->isPureConstant = true;
  722. gvar->constantValue = expr.type.qwordValue;
  723. }
  724. asSExprContext lctx(engine);
  725. lctx.type.Set(gvar->datatype);
  726. lctx.type.dataType.MakeReference(true);
  727. lctx.type.dataType.MakeReadOnly(false);
  728. lctx.type.isLValue = true;
  729. // If it is an enum value that is being compiled, then
  730. // we skip this, as the bytecode won't be used anyway
  731. if( !gvar->isEnumValue )
  732. lctx.bc.InstrPTR(asBC_LDG, engine->globalProperties[gvar->index]->GetAddressOfValue());
  733. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  734. }
  735. else
  736. {
  737. // TODO: optimize: Here we should look for the best matching constructor, instead of
  738. // just the copy constructor. Only if no appropriate constructor is
  739. // available should the assignment operator be used.
  740. if( (!gvar->datatype.IsObjectHandle() || gvar->datatype.GetObjectType()->flags & asOBJ_ASHANDLE) )
  741. {
  742. // Call the default constructor to have a valid object for the assignment
  743. CallDefaultConstructor(gvar->datatype, gvar->index, true, &ctx.bc, gvar->idNode, true);
  744. }
  745. asSExprContext lexpr(engine);
  746. lexpr.type.Set(gvar->datatype);
  747. lexpr.type.dataType.MakeReference(true);
  748. lexpr.type.dataType.MakeReadOnly(false);
  749. lexpr.type.stackOffset = -1;
  750. lexpr.type.isLValue = true;
  751. if( gvar->datatype.IsObjectHandle() )
  752. lexpr.type.isExplicitHandle = true;
  753. lexpr.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  754. // If left expression resolves into a registered type
  755. // check if the assignment operator is overloaded, and check
  756. // the type of the right hand expression. If none is found
  757. // the default action is a direct copy if it is the same type
  758. // and a simple assignment.
  759. bool assigned = false;
  760. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  761. {
  762. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  763. if( assigned )
  764. {
  765. // Pop the resulting value
  766. ctx.bc.Pop(ctx.type.dataType.GetSizeOnStackDWords());
  767. // Release the argument
  768. ProcessDeferredParams(&ctx);
  769. }
  770. }
  771. if( !assigned )
  772. {
  773. PrepareForAssignment(&lexpr.type.dataType, &expr, node, false);
  774. // If the expression is constant and the variable also is constant
  775. // then mark the variable as pure constant. This will allow the compiler
  776. // to optimize expressions with this variable.
  777. if( gvar->datatype.IsReadOnly() && expr.type.isConstant )
  778. {
  779. gvar->isPureConstant = true;
  780. gvar->constantValue = expr.type.qwordValue;
  781. }
  782. // Add expression code to bytecode
  783. MergeExprBytecode(&ctx, &expr);
  784. // Add byte code for storing value of expression in variable
  785. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  786. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, node);
  787. // Release temporary variables used by expression
  788. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  789. ctx.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  790. }
  791. }
  792. }
  793. else if( gvar->datatype.IsObject() && (!gvar->datatype.IsObjectHandle() || gvar->datatype.GetObjectType()->flags & asOBJ_ASHANDLE) )
  794. {
  795. // Call the default constructor in case no explicit initialization is given
  796. CallDefaultConstructor(gvar->datatype, gvar->index, true, &ctx.bc, gvar->idNode, true);
  797. }
  798. // Concatenate the bytecode
  799. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  800. // Add information on the line number for the global variable
  801. size_t pos = 0;
  802. if( gvar->idNode )
  803. pos = gvar->idNode->tokenPos;
  804. else if( gvar->nextNode )
  805. pos = gvar->nextNode->tokenPos;
  806. LineInstr(&byteCode, pos);
  807. // We need to push zeroes on the stack to guarantee
  808. // that temporary object handles are clear
  809. int n;
  810. for( n = 0; n < varSize; n++ )
  811. byteCode.InstrINT(asBC_PshC4, 0);
  812. byteCode.AddCode(&ctx.bc);
  813. // Deallocate variables in this block, in reverse order
  814. for( n = (int)variables->variables.GetLength() - 1; n >= 0; --n )
  815. {
  816. sVariable *v = variables->variables[n];
  817. // Call variable destructors here, for variables not yet destroyed
  818. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  819. DeallocateVariable(v->stackOffset);
  820. }
  821. if( hasCompileErrors ) return -1;
  822. // At this point there should be no variables allocated
  823. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  824. // Remove the variable scope again
  825. RemoveVariableScope();
  826. byteCode.Ret(0);
  827. FinalizeFunction();
  828. #ifdef AS_DEBUG
  829. // DEBUG: output byte code
  830. byteCode.DebugOutput(("___init_" + gvar->name + ".txt").AddressOf(), engine, outFunc);
  831. #endif
  832. return 0;
  833. }
  834. void asCCompiler::FinalizeFunction()
  835. {
  836. asUINT n;
  837. // Tell the bytecode which variables are temporary
  838. for( n = 0; n < variableIsTemporary.GetLength(); n++ )
  839. {
  840. if( variableIsTemporary[n] )
  841. byteCode.DefineTemporaryVariable(GetVariableOffset(n));
  842. }
  843. // Finalize the bytecode
  844. byteCode.Finalize();
  845. byteCode.ExtractObjectVariableInfo(outFunc);
  846. // Compile the list of object variables for the exception handler
  847. for( n = 0; n < variableAllocations.GetLength(); n++ )
  848. {
  849. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  850. {
  851. outFunc->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  852. outFunc->objVariablePos.PushLast(GetVariableOffset(n));
  853. outFunc->objVariableIsOnHeap.PushLast(variableIsOnHeap[n]);
  854. }
  855. }
  856. // Copy byte code to the function
  857. outFunc->byteCode.SetLength(byteCode.GetSize());
  858. byteCode.Output(outFunc->byteCode.AddressOf());
  859. outFunc->AddReferences();
  860. outFunc->stackNeeded = byteCode.largestStackUsed;
  861. outFunc->lineNumbers = byteCode.lineNumbers;
  862. }
  863. void asCCompiler::PrepareArgument(asCDataType *paramType, asSExprContext *ctx, asCScriptNode *node, bool isFunction, int refType, asCArray<int> *reservedVars, bool /* forceOnHeap */)
  864. {
  865. asCDataType param = *paramType;
  866. if( paramType->GetTokenType() == ttQuestion )
  867. {
  868. // Since the function is expecting a var type ?, then we don't want to convert the argument to anything else
  869. param = ctx->type.dataType;
  870. param.MakeHandle(ctx->type.isExplicitHandle);
  871. param.MakeReference(paramType->IsReference());
  872. param.MakeReadOnly(paramType->IsReadOnly());
  873. }
  874. else
  875. param = *paramType;
  876. asCDataType dt = param;
  877. // Need to protect arguments by reference
  878. if( isFunction && dt.IsReference() )
  879. {
  880. if( paramType->GetTokenType() == ttQuestion )
  881. {
  882. asCByteCode tmpBC(engine);
  883. // Place the type id on the stack as a hidden parameter
  884. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  885. // Insert the code before the expression code
  886. tmpBC.AddCode(&ctx->bc);
  887. ctx->bc.AddCode(&tmpBC);
  888. }
  889. // Allocate a temporary variable of the same type as the argument
  890. dt.MakeReference(false);
  891. dt.MakeReadOnly(false);
  892. int offset;
  893. if( refType == 1 ) // &in
  894. {
  895. ProcessPropertyGetAccessor(ctx, node);
  896. // If the reference is const, then it is not necessary to make a copy if the value already is a variable
  897. // Even if the same variable is passed in another argument as non-const then there is no problem
  898. if( dt.IsPrimitive() || dt.IsNullHandle() )
  899. {
  900. IsVariableInitialized(&ctx->type, node);
  901. if( ctx->type.dataType.IsReference() ) ConvertToVariableNotIn(ctx, reservedVars);
  902. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true, reservedVars);
  903. if( !(param.IsReadOnly() && ctx->type.isVariable) )
  904. ConvertToTempVariableNotIn(ctx, reservedVars);
  905. PushVariableOnStack(ctx, true);
  906. ctx->type.dataType.MakeReadOnly(param.IsReadOnly());
  907. }
  908. else
  909. {
  910. IsVariableInitialized(&ctx->type, node);
  911. ImplicitConversion(ctx, param, node, asIC_IMPLICIT_CONV, true, reservedVars);
  912. if( !ctx->type.dataType.IsEqualExceptRef(param) )
  913. {
  914. asCString str;
  915. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), param.Format().AddressOf());
  916. Error(str.AddressOf(), node);
  917. ctx->type.Set(param);
  918. }
  919. // If the argument already is a temporary
  920. // variable we don't need to allocate another
  921. // If the parameter is read-only and the object already is a local
  922. // variable then it is not necessary to make a copy either
  923. if( !ctx->type.isTemporary && !(param.IsReadOnly() && ctx->type.isVariable) )
  924. {
  925. // Make sure the variable is not used in the expression
  926. asCArray<int> vars;
  927. ctx->bc.GetVarsUsed(vars);
  928. if( reservedVars ) vars.Concatenate(*reservedVars);
  929. offset = AllocateVariableNotIn(dt, true, &vars);
  930. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  931. // Allocate and construct the temporary object
  932. asCByteCode tmpBC(engine);
  933. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  934. // Insert the code before the expression code
  935. tmpBC.AddCode(&ctx->bc);
  936. ctx->bc.AddCode(&tmpBC);
  937. // Assign the evaluated expression to the temporary variable
  938. PrepareForAssignment(&dt, ctx, node, true);
  939. dt.MakeReference(IsVariableOnHeap(offset));
  940. asCTypeInfo type;
  941. type.Set(dt);
  942. type.isTemporary = true;
  943. type.stackOffset = (short)offset;
  944. if( dt.IsObjectHandle() )
  945. type.isExplicitHandle = true;
  946. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  947. PerformAssignment(&type, &ctx->type, &ctx->bc, node);
  948. ctx->bc.Pop(ctx->type.dataType.GetSizeOnStackDWords());
  949. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  950. ctx->type = type;
  951. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  952. if( dt.IsObject() && !dt.IsObjectHandle() )
  953. ctx->bc.Instr(asBC_RDSPTR);
  954. if( paramType->IsReadOnly() )
  955. ctx->type.dataType.MakeReadOnly(true);
  956. }
  957. }
  958. }
  959. else if( refType == 2 ) // &out
  960. {
  961. // Make sure the variable is not used in the expression
  962. asCArray<int> vars;
  963. ctx->bc.GetVarsUsed(vars);
  964. if( reservedVars ) vars.Concatenate(*reservedVars);
  965. offset = AllocateVariableNotIn(dt, true, &vars);
  966. if( dt.IsPrimitive() )
  967. {
  968. ctx->type.SetVariable(dt, offset, true);
  969. PushVariableOnStack(ctx, true);
  970. }
  971. else
  972. {
  973. // Allocate and construct the temporary object
  974. asCByteCode tmpBC(engine);
  975. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  976. // Insert the code before the expression code
  977. tmpBC.AddCode(&ctx->bc);
  978. ctx->bc.AddCode(&tmpBC);
  979. dt.MakeReference((!dt.IsObject() || dt.IsObjectHandle()));
  980. asCTypeInfo type;
  981. type.Set(dt);
  982. type.isTemporary = true;
  983. type.stackOffset = (short)offset;
  984. ctx->type = type;
  985. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  986. if( dt.IsObject() && !dt.IsObjectHandle() )
  987. ctx->bc.Instr(asBC_RDSPTR);
  988. }
  989. // After the function returns the temporary variable will
  990. // be assigned to the expression, if it is a valid lvalue
  991. }
  992. else if( refType == asTM_INOUTREF )
  993. {
  994. ProcessPropertyGetAccessor(ctx, node);
  995. // Literal constants cannot be passed to inout ref arguments
  996. if( !ctx->type.isVariable && ctx->type.isConstant )
  997. {
  998. Error(TXT_NOT_VALID_REFERENCE, node);
  999. }
  1000. // Only objects that support object handles
  1001. // can be guaranteed to be safe. Local variables are
  1002. // already safe, so there is no need to add an extra
  1003. // references
  1004. if( !engine->ep.allowUnsafeReferences &&
  1005. !ctx->type.isVariable &&
  1006. ctx->type.dataType.IsObject() &&
  1007. !ctx->type.dataType.IsObjectHandle() &&
  1008. ctx->type.dataType.GetBehaviour()->addref &&
  1009. ctx->type.dataType.GetBehaviour()->release )
  1010. {
  1011. // Store a handle to the object as local variable
  1012. asSExprContext tmp(engine);
  1013. asCDataType dt = ctx->type.dataType;
  1014. dt.MakeHandle(true);
  1015. dt.MakeReference(false);
  1016. asCArray<int> vars;
  1017. ctx->bc.GetVarsUsed(vars);
  1018. if( reservedVars ) vars.Concatenate(*reservedVars);
  1019. offset = AllocateVariableNotIn(dt, true, &vars);
  1020. // Copy the handle
  1021. if( !ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReference() )
  1022. ctx->bc.Instr(asBC_RDSPTR);
  1023. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1024. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  1025. ctx->bc.Pop(AS_PTR_SIZE);
  1026. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1027. dt.MakeHandle(false);
  1028. dt.MakeReference(true);
  1029. // Release previous temporary variable stored in the context (if any)
  1030. if( ctx->type.isTemporary )
  1031. {
  1032. ReleaseTemporaryVariable(ctx->type.stackOffset, &ctx->bc);
  1033. }
  1034. ctx->type.SetVariable(dt, offset, true);
  1035. }
  1036. // Make sure the reference to the value is on the stack
  1037. if( ctx->type.dataType.IsObject() && ctx->type.dataType.IsReference() )
  1038. Dereference(ctx, true);
  1039. else if( ctx->type.isVariable && !ctx->type.dataType.IsObject() )
  1040. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  1041. else if( ctx->type.dataType.IsPrimitive() )
  1042. ctx->bc.Instr(asBC_PshRPtr);
  1043. }
  1044. }
  1045. else
  1046. {
  1047. ProcessPropertyGetAccessor(ctx, node);
  1048. if( dt.IsPrimitive() )
  1049. {
  1050. IsVariableInitialized(&ctx->type, node);
  1051. if( ctx->type.dataType.IsReference() ) ConvertToVariableNotIn(ctx, reservedVars);
  1052. // Implicitly convert primitives to the parameter type
  1053. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true, reservedVars);
  1054. if( ctx->type.isVariable )
  1055. {
  1056. PushVariableOnStack(ctx, dt.IsReference());
  1057. }
  1058. else if( ctx->type.isConstant )
  1059. {
  1060. ConvertToVariableNotIn(ctx, reservedVars);
  1061. PushVariableOnStack(ctx, dt.IsReference());
  1062. }
  1063. }
  1064. else
  1065. {
  1066. IsVariableInitialized(&ctx->type, node);
  1067. // Implicitly convert primitives to the parameter type
  1068. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true, reservedVars);
  1069. // Was the conversion successful?
  1070. if( !ctx->type.dataType.IsEqualExceptRef(dt) )
  1071. {
  1072. asCString str;
  1073. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), dt.Format().AddressOf());
  1074. Error(str.AddressOf(), node);
  1075. ctx->type.Set(dt);
  1076. }
  1077. if( dt.IsObjectHandle() )
  1078. ctx->type.isExplicitHandle = true;
  1079. if( dt.IsObject() )
  1080. {
  1081. if( !dt.IsReference() )
  1082. {
  1083. // Objects passed by value must be placed in temporary variables
  1084. // so that they are guaranteed to not be referenced anywhere else.
  1085. // The object must also be allocated on the heap, as the memory will
  1086. // be deleted by in as_callfunc_xxx.
  1087. // TODO: value on stack: How can we avoid this unnecessary allocation?
  1088. PrepareTemporaryObject(node, ctx, reservedVars, true);
  1089. // The implicit conversion shouldn't convert the object to
  1090. // non-reference yet. It will be dereferenced just before the call.
  1091. // Otherwise the object might be missed by the exception handler.
  1092. dt.MakeReference(true);
  1093. }
  1094. else
  1095. {
  1096. // An object passed by reference should place the pointer to
  1097. // the object on the stack.
  1098. dt.MakeReference(false);
  1099. }
  1100. }
  1101. }
  1102. }
  1103. // Don't put any pointer on the stack yet
  1104. if( param.IsReference() || param.IsObject() )
  1105. {
  1106. // &inout parameter may leave the reference on the stack already
  1107. if( refType != 3 )
  1108. {
  1109. ctx->bc.Pop(AS_PTR_SIZE);
  1110. ctx->bc.InstrSHORT(asBC_VAR, ctx->type.stackOffset);
  1111. }
  1112. ProcessDeferredParams(ctx);
  1113. }
  1114. }
  1115. void asCCompiler::PrepareFunctionCall(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args)
  1116. {
  1117. // When a match has been found, compile the final byte code using correct parameter types
  1118. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1119. // Add code for arguments
  1120. asSExprContext e(engine);
  1121. int n;
  1122. for( n = (int)args.GetLength()-1; n >= 0; n-- )
  1123. {
  1124. // Make sure PrepareArgument doesn't use any variable that is already
  1125. // being used by any of the following argument expressions
  1126. asCArray<int> reservedVars;
  1127. for( int m = n-1; m >= 0; m-- )
  1128. args[m]->bc.GetVarsUsed(reservedVars);
  1129. PrepareArgument2(&e, args[n], &descr->parameterTypes[n], true, descr->inOutFlags[n], &reservedVars);
  1130. }
  1131. bc->AddCode(&e.bc);
  1132. }
  1133. void asCCompiler::MoveArgsToStack(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args, bool addOneToOffset)
  1134. {
  1135. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1136. int offset = 0;
  1137. if( addOneToOffset )
  1138. offset += AS_PTR_SIZE;
  1139. #ifndef AS_OLD
  1140. // The address of where the return value should be stored is push on top of the arguments
  1141. if( descr->DoesReturnOnStack() )
  1142. offset += AS_PTR_SIZE;
  1143. #endif
  1144. // Move the objects that are sent by value to the stack just before the call
  1145. for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
  1146. {
  1147. if( descr->parameterTypes[n].IsReference() )
  1148. {
  1149. if( descr->parameterTypes[n].IsObject() && !descr->parameterTypes[n].IsObjectHandle() )
  1150. {
  1151. if( descr->inOutFlags[n] != asTM_INOUTREF )
  1152. {
  1153. if( (args[n]->type.isVariable || args[n]->type.isTemporary) &&
  1154. !IsVariableOnHeap(args[n]->type.stackOffset) )
  1155. // TODO: optimize: Actually the reference can be pushed on the stack directly
  1156. // as the value allocated on the stack is guaranteed to be safe
  1157. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1158. else
  1159. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1160. }
  1161. if( args[n]->type.dataType.IsObjectHandle() )
  1162. bc->InstrWORD(asBC_ChkNullS, (asWORD)offset);
  1163. }
  1164. else if( descr->inOutFlags[n] != asTM_INOUTREF )
  1165. {
  1166. if( descr->parameterTypes[n].GetTokenType() == ttQuestion &&
  1167. args[n]->type.dataType.IsObject() && !args[n]->type.dataType.IsObjectHandle() )
  1168. {
  1169. // Send the object as a reference to the object,
  1170. // and not to the variable holding the object
  1171. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1172. // TODO: optimize: Actually the reference can be pushed on the stack directly
  1173. // as the value allocated on the stack is guaranteed to be safe
  1174. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1175. else
  1176. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1177. }
  1178. else
  1179. {
  1180. if( args[n]->type.dataType.GetObjectType() &&
  1181. (args[n]->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) &&
  1182. args[n]->type.isVariable &&
  1183. IsVariableOnHeap(args[n]->type.stackOffset) )
  1184. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1185. else
  1186. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1187. }
  1188. }
  1189. }
  1190. else if( descr->parameterTypes[n].IsObject() )
  1191. {
  1192. // TODO: value on stack: What can we do to avoid this unnecessary allocation?
  1193. // The object must be allocated on the heap, because this memory will be deleted in as_callfunc_xxx
  1194. asASSERT(IsVariableOnHeap(args[n]->type.stackOffset));
  1195. bc->InstrWORD(asBC_GETOBJ, (asWORD)offset);
  1196. // The temporary variable must not be freed as it will no longer hold an object
  1197. DeallocateVariable(args[n]->type.stackOffset);
  1198. args[n]->type.isTemporary = false;
  1199. }
  1200. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  1201. }
  1202. }
  1203. int asCCompiler::CompileArgumentList(asCScriptNode *node, asCArray<asSExprContext*> &args)
  1204. {
  1205. asASSERT(node->nodeType == snArgList);
  1206. // Count arguments
  1207. asCScriptNode *arg = node->firstChild;
  1208. int argCount = 0;
  1209. while( arg )
  1210. {
  1211. argCount++;
  1212. arg = arg->next;
  1213. }
  1214. // Prepare the arrays
  1215. args.SetLength(argCount);
  1216. int n;
  1217. for( n = 0; n < argCount; n++ )
  1218. args[n] = 0;
  1219. n = argCount-1;
  1220. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1221. bool anyErrors = false;
  1222. arg = node->lastChild;
  1223. while( arg )
  1224. {
  1225. asSExprContext expr(engine);
  1226. int r = CompileAssignment(arg, &expr);
  1227. if( r < 0 ) anyErrors = true;
  1228. args[n] = asNEW(asSExprContext)(engine);
  1229. MergeExprBytecodeAndType(args[n], &expr);
  1230. n--;
  1231. arg = arg->prev;
  1232. }
  1233. return anyErrors ? -1 : 0;
  1234. }
  1235. int asCCompiler::CompileDefaultArgs(asCScriptNode *node, asCArray<asSExprContext*> &args, asCScriptFunction *func)
  1236. {
  1237. bool anyErrors = false;
  1238. asCArray<int> varsUsed;
  1239. int explicitArgs = (int)args.GetLength();
  1240. for( int p = 0; p < explicitArgs; p++ )
  1241. args[p]->bc.GetVarsUsed(varsUsed);
  1242. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1243. args.SetLength(func->parameterTypes.GetLength());
  1244. for( asUINT c = explicitArgs; c < args.GetLength(); c++ )
  1245. args[c] = 0;
  1246. for( int n = (int)func->parameterTypes.GetLength() - 1; n >= explicitArgs; n-- )
  1247. {
  1248. if( func->defaultArgs[n] == 0 ) { anyErrors = true; continue; }
  1249. // Parse the default arg string
  1250. asCParser parser(builder);
  1251. asCScriptCode code;
  1252. code.SetCode("default arg", func->defaultArgs[n]->AddressOf(), false);
  1253. int r = parser.ParseExpression(&code);
  1254. if( r < 0 ) { anyErrors = true; continue; }
  1255. asCScriptNode *arg = parser.GetScriptNode();
  1256. // Temporarily set the script code to the default arg expression
  1257. asCScriptCode *origScript = script;
  1258. script = &code;
  1259. // Don't allow the expression to access local variables
  1260. // TODO: namespace: The default arg should see the symbols declared in the same scope as the function
  1261. isCompilingDefaultArg = true;
  1262. asSExprContext expr(engine);
  1263. r = CompileExpression(arg, &expr);
  1264. isCompilingDefaultArg = false;
  1265. script = origScript;
  1266. if( r < 0 )
  1267. {
  1268. asCString msg;
  1269. msg.Format(TXT_FAILED_TO_COMPILE_DEF_ARG_d_IN_FUNC_s, n, func->GetDeclaration());
  1270. Error(msg.AddressOf(), node);
  1271. anyErrors = true;
  1272. continue;
  1273. }
  1274. args[n] = asNEW(asSExprContext)(engine);
  1275. MergeExprBytecodeAndType(args[n], &expr);
  1276. // Make sure the default arg expression doesn't end up
  1277. // with a variable that is used in a previous expression
  1278. if( args[n]->type.isVariable )
  1279. {
  1280. int offset = args[n]->type.stackOffset;
  1281. if( varsUsed.Exists(offset) )
  1282. {
  1283. // Release the current temporary variable
  1284. ReleaseTemporaryVariable(args[n]->type, 0);
  1285. asCDataType dt = args[n]->type.dataType;
  1286. dt.MakeReference(false);
  1287. int newOffset = AllocateVariableNotIn(dt, true, &varsUsed, IsVariableOnHeap(offset));
  1288. asASSERT( IsVariableOnHeap(offset) == IsVariableOnHeap(newOffset) );
  1289. args[n]->bc.ExchangeVar(offset, newOffset);
  1290. args[n]->type.stackOffset = (short)newOffset;
  1291. args[n]->type.isTemporary = true;
  1292. args[n]->type.isVariable = true;
  1293. }
  1294. }
  1295. }
  1296. return anyErrors ? -1 : 0;
  1297. }
  1298. void asCCompiler::MatchFunctions(asCArray<int> &funcs, asCArray<asSExprContext*> &args, asCScriptNode *node, const char *name, asCObjectType *objectType, bool isConstMethod, bool silent, bool allowObjectConstruct, const asCString &scope)
  1299. {
  1300. asCArray<int> origFuncs = funcs; // Keep the original list for error message
  1301. asUINT n;
  1302. if( funcs.GetLength() > 0 )
  1303. {
  1304. // Check the number of parameters in the found functions
  1305. for( n = 0; n < funcs.GetLength(); ++n )
  1306. {
  1307. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  1308. if( desc->parameterTypes.GetLength() != args.GetLength() )
  1309. {
  1310. bool noMatch = true;
  1311. if( args.GetLength() < desc->parameterTypes.GetLength() )
  1312. {
  1313. // Count the number of default args
  1314. asUINT defaultArgs = 0;
  1315. for( asUINT d = 0; d < desc->defaultArgs.GetLength(); d++ )
  1316. if( desc->defaultArgs[d] )
  1317. defaultArgs++;
  1318. if( args.GetLength() >= desc->parameterTypes.GetLength() - defaultArgs )
  1319. noMatch = false;
  1320. }
  1321. if( noMatch )
  1322. {
  1323. // remove it from the list
  1324. if( n == funcs.GetLength()-1 )
  1325. funcs.PopLast();
  1326. else
  1327. funcs[n] = funcs.PopLast();
  1328. n--;
  1329. }
  1330. }
  1331. }
  1332. // Match functions with the parameters, and discard those that do not match
  1333. asCArray<int> matchingFuncs = funcs;
  1334. for( n = 0; n < args.GetLength(); ++n )
  1335. {
  1336. asCArray<int> tempFuncs;
  1337. MatchArgument(funcs, tempFuncs, &args[n]->type, n, allowObjectConstruct);
  1338. // Intersect the found functions with the list of matching functions
  1339. for( asUINT f = 0; f < matchingFuncs.GetLength(); f++ )
  1340. {
  1341. asUINT c;
  1342. for( c = 0; c < tempFuncs.GetLength(); c++ )
  1343. {
  1344. if( matchingFuncs[f] == tempFuncs[c] )
  1345. break;
  1346. }
  1347. // Was the function a match?
  1348. if( c == tempFuncs.GetLength() )
  1349. {
  1350. // No, remove it from the list
  1351. if( f == matchingFuncs.GetLength()-1 )
  1352. matchingFuncs.PopLast();
  1353. else
  1354. matchingFuncs[f] = matchingFuncs.PopLast();
  1355. f--;
  1356. }
  1357. }
  1358. }
  1359. funcs = matchingFuncs;
  1360. }
  1361. if( !isConstMethod )
  1362. FilterConst(funcs);
  1363. if( funcs.GetLength() != 1 && !silent )
  1364. {
  1365. // Build a readable string of the function with parameter types
  1366. asCString str;
  1367. if( scope != "" )
  1368. {
  1369. if( scope == "::" )
  1370. str = scope;
  1371. else
  1372. str = scope + "::";
  1373. }
  1374. str += name;
  1375. str += "(";
  1376. if( args.GetLength() )
  1377. str += args[0]->type.dataType.Format();
  1378. for( n = 1; n < args.GetLength(); n++ )
  1379. str += ", " + args[n]->type.dataType.Format();
  1380. str += ")";
  1381. if( isConstMethod )
  1382. str += " const";
  1383. if( objectType && scope == "" )
  1384. str = objectType->name + "::" + str;
  1385. if( funcs.GetLength() == 0 )
  1386. {
  1387. str.Format(TXT_NO_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1388. Error(str.AddressOf(), node);
  1389. // Print the list of candidates
  1390. if( origFuncs.GetLength() > 0 )
  1391. {
  1392. int r = 0, c = 0;
  1393. asASSERT( node );
  1394. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  1395. builder->WriteInfo(script->name.AddressOf(), TXT_CANDIDATES_ARE, r, c, false);
  1396. PrintMatchingFuncs(origFuncs, node);
  1397. }
  1398. }
  1399. else
  1400. {
  1401. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1402. Error(str.AddressOf(), node);
  1403. PrintMatchingFuncs(funcs, node);
  1404. }
  1405. }
  1406. }
  1407. void asCCompiler::CompileDeclaration(asCScriptNode *decl, asCByteCode *bc)
  1408. {
  1409. // Get the data type
  1410. asCDataType type = builder->CreateDataTypeFromNode(decl->firstChild, script);
  1411. // Declare all variables in this declaration
  1412. asCScriptNode *node = decl->firstChild->next;
  1413. while( node )
  1414. {
  1415. // Is the type allowed?
  1416. if( !type.CanBeInstanciated() )
  1417. {
  1418. asCString str;
  1419. // TODO: Change to "'type' cannot be declared as variable"
  1420. str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format().AddressOf());
  1421. Error(str.AddressOf(), node);
  1422. // Use int instead to avoid further problems
  1423. type = asCDataType::CreatePrimitive(ttInt, false);
  1424. }
  1425. // A shared object may not declare variables of non-shared types
  1426. if( outFunc->objectType && outFunc->objectType->IsShared() )
  1427. {
  1428. asCObjectType *ot = type.GetObjectType();
  1429. if( ot && !ot->IsShared() )
  1430. {
  1431. asCString msg;
  1432. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  1433. Error(msg.AddressOf(), decl);
  1434. }
  1435. }
  1436. // Get the name of the identifier
  1437. asCString name(&script->code[node->tokenPos], node->tokenLength);
  1438. // Verify that the name isn't used by a dynamic data type
  1439. if( engine->GetObjectType(name.AddressOf()) != 0 )
  1440. {
  1441. asCString str;
  1442. str.Format(TXT_ILLEGAL_VARIABLE_NAME_s, name.AddressOf());
  1443. Error(str.AddressOf(), node);
  1444. }
  1445. int offset = AllocateVariable(type, false);
  1446. if( variables->DeclareVariable(name.AddressOf(), type, offset, IsVariableOnHeap(offset)) < 0 )
  1447. {
  1448. asCString str;
  1449. str.Format(TXT_s_ALREADY_DECLARED, name.AddressOf());
  1450. Error(str.AddressOf(), node);
  1451. // Don't continue after this error, as it will just
  1452. // lead to more errors that are likely false
  1453. return;
  1454. }
  1455. // Add marker that the variable has been declared
  1456. bc->VarDecl((int)outFunc->variables.GetLength());
  1457. outFunc->AddVariable(name, type, offset);
  1458. // Keep the node for the variable decl
  1459. asCScriptNode *varNode = node;
  1460. node = node->next;
  1461. if( node && node->nodeType == snArgList )
  1462. {
  1463. // Make sure that it is a registered type, and that is isn't a pointer
  1464. if( type.GetObjectType() == 0 || type.IsObjectHandle() )
  1465. {
  1466. Error(TXT_MUST_BE_OBJECT, node);
  1467. }
  1468. else
  1469. {
  1470. // Compile the arguments
  1471. asCArray<asSExprContext *> args;
  1472. if( CompileArgumentList(node, args) >= 0 )
  1473. {
  1474. // Find all constructors
  1475. asCArray<int> funcs;
  1476. asSTypeBehaviour *beh = type.GetBehaviour();
  1477. if( beh )
  1478. {
  1479. if( type.GetObjectType()->flags & asOBJ_REF )
  1480. funcs = beh->factories;
  1481. else
  1482. funcs = beh->constructors;
  1483. }
  1484. asCString str = type.Format();
  1485. MatchFunctions(funcs, args, node, str.AddressOf());
  1486. if( funcs.GetLength() == 1 )
  1487. {
  1488. int r = asSUCCESS;
  1489. // Add the default values for arguments not explicitly supplied
  1490. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  1491. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  1492. r = CompileDefaultArgs(node, args, func);
  1493. if( r == asSUCCESS )
  1494. {
  1495. sVariable *v = variables->GetVariable(name.AddressOf());
  1496. asSExprContext ctx(engine);
  1497. if( v->type.GetObjectType() && (v->type.GetObjectType()->flags & asOBJ_REF) )
  1498. {
  1499. MakeFunctionCall(&ctx, funcs[0], 0, args, node, true, v->stackOffset);
  1500. // Pop the reference left by the function call
  1501. ctx.bc.Pop(AS_PTR_SIZE);
  1502. }
  1503. else
  1504. {
  1505. // When the object is allocated on the heap, the address where the
  1506. // reference will be stored must be pushed on the stack before the
  1507. // arguments. This reference on the stack is safe, even if the script
  1508. // is suspended during the evaluation of the arguments.
  1509. if( v->onHeap )
  1510. ctx.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1511. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  1512. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  1513. // When the object is allocated on the stack, the address to the
  1514. // object is pushed on the stack after the arguments as the object pointer
  1515. if( !v->onHeap )
  1516. ctx.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1517. PerformFunctionCall(funcs[0], &ctx, v->onHeap, &args, type.GetObjectType());
  1518. // TODO: value on stack: This probably has to be done in PerformFunctionCall
  1519. // Mark the object as initialized
  1520. ctx.bc.ObjInfo(v->stackOffset, asOBJ_INIT);
  1521. }
  1522. bc->AddCode(&ctx.bc);
  1523. }
  1524. }
  1525. }
  1526. // Cleanup
  1527. for( asUINT n = 0; n < args.GetLength(); n++ )
  1528. if( args[n] )
  1529. {
  1530. asDELETE(args[n],asSExprContext);
  1531. }
  1532. }
  1533. node = node->next;
  1534. }
  1535. else if( node && node->nodeType == snInitList )
  1536. {
  1537. sVariable *v = variables->GetVariable(name.AddressOf());
  1538. asCTypeInfo ti;
  1539. ti.Set(type);
  1540. ti.isVariable = true;
  1541. ti.isTemporary = false;
  1542. ti.stackOffset = (short)v->stackOffset;
  1543. ti.isLValue = true;
  1544. CompileInitList(&ti, node, bc);
  1545. node = node->next;
  1546. }
  1547. else if( node && node->nodeType == snAssignment )
  1548. {
  1549. asSExprContext ctx(engine);
  1550. // TODO: copy: Here we should look for the best matching constructor, instead of
  1551. // just the copy constructor. Only if no appropriate constructor is
  1552. // available should the assignment operator be used.
  1553. // Call the default constructor here
  1554. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), &ctx.bc, varNode);
  1555. // Compile the expression
  1556. asSExprContext expr(engine);
  1557. int r = CompileAssignment(node, &expr);
  1558. if( r >= 0 )
  1559. {
  1560. if( type.IsPrimitive() )
  1561. {
  1562. if( type.IsReadOnly() && expr.type.isConstant )
  1563. {
  1564. ImplicitConversion(&expr, type, node, asIC_IMPLICIT_CONV);
  1565. sVariable *v = variables->GetVariable(name.AddressOf());
  1566. v->isPureConstant = true;
  1567. v->constantValue = expr.type.qwordValue;
  1568. }
  1569. asSExprContext lctx(engine);
  1570. lctx.type.SetVariable(type, offset, false);
  1571. lctx.type.dataType.MakeReadOnly(false);
  1572. lctx.type.isLValue = true;
  1573. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  1574. ProcessDeferredParams(&ctx);
  1575. }
  1576. else
  1577. {
  1578. // TODO: optimize: We can use a copy constructor here
  1579. sVariable *v = variables->GetVariable(name.AddressOf());
  1580. asSExprContext lexpr(engine);
  1581. lexpr.type.Set(type);
  1582. lexpr.type.dataType.MakeReference(v->onHeap);
  1583. // Allow initialization of constant variables
  1584. lexpr.type.dataType.MakeReadOnly(false);
  1585. if( type.IsObjectHandle() )
  1586. lexpr.type.isExplicitHandle = true;
  1587. lexpr.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1588. lexpr.type.stackOffset = (short)v->stackOffset;
  1589. lexpr.type.isVariable = true;
  1590. lexpr.type.isLValue = true;
  1591. // If left expression resolves into a registered type
  1592. // check if the assignment operator is overloaded, and check
  1593. // the type of the right hand expression. If none is found
  1594. // the default action is a direct copy if it is the same type
  1595. // and a simple assignment.
  1596. bool assigned = false;
  1597. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  1598. {
  1599. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  1600. if( assigned )
  1601. {
  1602. // Pop the resulting value
  1603. ctx.bc.Pop(ctx.type.dataType.GetSizeOnStackDWords());
  1604. // Release the argument
  1605. ProcessDeferredParams(&ctx);
  1606. // Release temporary variable that may be allocated by the overloaded operator
  1607. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1608. }
  1609. }
  1610. if( !assigned )
  1611. {
  1612. PrepareForAssignment(&lexpr.type.dataType, &expr, node, false);
  1613. // If the expression is constant and the variable also is constant
  1614. // then mark the variable as pure constant. This will allow the compiler
  1615. // to optimize expressions with this variable.
  1616. if( v->type.IsReadOnly() && expr.type.isConstant )
  1617. {
  1618. v->isPureConstant = true;
  1619. v->constantValue = expr.type.qwordValue;
  1620. }
  1621. // Add expression code to bytecode
  1622. MergeExprBytecode(&ctx, &expr);
  1623. // Add byte code for storing value of expression in variable
  1624. ctx.bc.AddCode(&lexpr.bc);
  1625. lexpr.type.stackOffset = (short)v->stackOffset;
  1626. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, node->prev);
  1627. // Release temporary variables used by expression
  1628. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  1629. ctx.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  1630. ProcessDeferredParams(&ctx);
  1631. }
  1632. }
  1633. }
  1634. node = node->next;
  1635. bc->AddCode(&ctx.bc);
  1636. // TODO: Can't this leave deferred output params without being compiled?
  1637. }
  1638. else
  1639. {
  1640. // Call the default constructor here if no explicit initialization is done
  1641. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), bc, varNode);
  1642. }
  1643. }
  1644. }
  1645. void asCCompiler::CompileInitList(asCTypeInfo *var, asCScriptNode *node, asCByteCode *bc)
  1646. {
  1647. // Check if the type supports initialization lists
  1648. if( var->dataType.GetObjectType() == 0 ||
  1649. var->dataType.GetBehaviour()->listFactory == 0 ||
  1650. var->dataType.IsObjectHandle() )
  1651. {
  1652. asCString str;
  1653. str.Format(TXT_INIT_LIST_CANNOT_BE_USED_WITH_s, var->dataType.Format().AddressOf());
  1654. Error(str.AddressOf(), node);
  1655. return;
  1656. }
  1657. // Count the number of elements and initialize the array with the correct size
  1658. int countElements = 0;
  1659. asCScriptNode *el = node->firstChild;
  1660. while( el )
  1661. {
  1662. countElements++;
  1663. el = el->next;
  1664. }
  1665. // Construct the array with the size elements
  1666. // TODO: value on stack: This needs to support value types on the stack as well
  1667. // Find the list factory
  1668. // TODO: initlist: Add support for value types as well
  1669. int funcId = var->dataType.GetBehaviour()->listFactory;
  1670. asCArray<asSExprContext *> args;
  1671. asSExprContext arg1(engine);
  1672. arg1.bc.InstrDWORD(asBC_PshC4, countElements);
  1673. arg1.type.Set(asCDataType::CreatePrimitive(ttUInt, false));
  1674. args.PushLast(&arg1);
  1675. asSExprContext ctx(engine);
  1676. PrepareFunctionCall(funcId, &ctx.bc, args);
  1677. MoveArgsToStack(funcId, &ctx.bc, args, false);
  1678. if( var->isVariable )
  1679. {
  1680. // Call factory and store the handle in the given variable
  1681. PerformFunctionCall(funcId, &ctx, false, &args, 0, true, var->stackOffset);
  1682. ctx.bc.Pop(AS_PTR_SIZE);
  1683. }
  1684. else
  1685. {
  1686. PerformFunctionCall(funcId, &ctx, false, &args);
  1687. // Store the returned handle in the global variable
  1688. ctx.bc.Instr(asBC_RDSPTR);
  1689. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  1690. ctx.bc.InstrPTR(asBC_REFCPY, var->dataType.GetObjectType());
  1691. ctx.bc.Pop(AS_PTR_SIZE);
  1692. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  1693. }
  1694. bc->AddCode(&ctx.bc);
  1695. // TODO: initlist: Should we have a special indexing operator for this? How can we support
  1696. // initialization lists with different types for different elements? Maybe
  1697. // by using the variable arguments the initialization can be done with one
  1698. // call, passing all the elements as arguments. The registered function can
  1699. // then traverse them however it wants.
  1700. // Find the indexing operator that is not read-only that will be used for all elements
  1701. asCDataType retType;
  1702. retType = var->dataType.GetSubType();
  1703. retType.MakeReference(true);
  1704. retType.MakeReadOnly(false);
  1705. funcId = 0;
  1706. for( asUINT n = 0; n < var->dataType.GetObjectType()->methods.GetLength(); n++ )
  1707. {
  1708. asCScriptFunction *desc = builder->GetFunctionDescription(var->dataType.GetObjectType()->methods[n]);
  1709. if( !desc->isReadOnly &&
  1710. desc->parameterTypes.GetLength() == 1 &&
  1711. (desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttUInt, false) ||
  1712. desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttInt, false)) &&
  1713. desc->returnType == retType &&
  1714. desc->name == "opIndex" )
  1715. {
  1716. funcId = var->dataType.GetObjectType()->methods[n];
  1717. break;
  1718. }
  1719. }
  1720. if( funcId == 0 )
  1721. {
  1722. Error(TXT_NO_APPROPRIATE_INDEX_OPERATOR, node);
  1723. return;
  1724. }
  1725. asUINT index = 0;
  1726. el = node->firstChild;
  1727. while( el )
  1728. {
  1729. if( el->nodeType == snAssignment || el->nodeType == snInitList )
  1730. {
  1731. asSExprContext lctx(engine);
  1732. asSExprContext rctx(engine);
  1733. if( el->nodeType == snAssignment )
  1734. {
  1735. // Compile the assignment expression
  1736. CompileAssignment(el, &rctx);
  1737. }
  1738. else if( el->nodeType == snInitList )
  1739. {
  1740. int offset = AllocateVariable(var->dataType.GetSubType(), true);
  1741. rctx.type.Set(var->dataType.GetSubType());
  1742. rctx.type.isVariable = true;
  1743. rctx.type.isTemporary = true;
  1744. rctx.type.stackOffset = (short)offset;
  1745. CompileInitList(&rctx.type, el, &rctx.bc);
  1746. // Put the object on the stack
  1747. rctx.bc.InstrSHORT(asBC_PSF, rctx.type.stackOffset);
  1748. // It is a reference that we place on the stack
  1749. rctx.type.dataType.MakeReference(true);
  1750. }
  1751. // Compile the lvalue
  1752. lctx.bc.InstrDWORD(asBC_PshC4, index);
  1753. if( var->isVariable )
  1754. lctx.bc.InstrSHORT(asBC_PSF, var->stackOffset);
  1755. else
  1756. lctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  1757. lctx.bc.Instr(asBC_RDSPTR);
  1758. lctx.bc.Call(asBC_CALLSYS, funcId, 1+AS_PTR_SIZE);
  1759. if( !var->dataType.GetSubType().IsPrimitive() )
  1760. lctx.bc.Instr(asBC_PshRPtr);
  1761. lctx.type.Set(var->dataType.GetSubType());
  1762. if( !lctx.type.dataType.IsObject() || lctx.type.dataType.IsObjectHandle() )
  1763. lctx.type.dataType.MakeReference(true);
  1764. // If the element type is handles, then we're expected to do handle assignments
  1765. if( lctx.type.dataType.IsObjectHandle() )
  1766. lctx.type.isExplicitHandle = true;
  1767. lctx.type.isLValue = true;
  1768. asSExprContext ctx(engine);
  1769. DoAssignment(&ctx, &lctx, &rctx, el, el, ttAssignment, el);
  1770. if( !lctx.type.dataType.IsPrimitive() )
  1771. ctx.bc.Pop(AS_PTR_SIZE);
  1772. // Release temporary variables used by expression
  1773. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1774. ProcessDeferredParams(&ctx);
  1775. bc->AddCode(&ctx.bc);
  1776. }
  1777. el = el->next;
  1778. index++;
  1779. }
  1780. }
  1781. void asCCompiler::CompileStatement(asCScriptNode *statement, bool *hasReturn, asCByteCode *bc)
  1782. {
  1783. *hasReturn = false;
  1784. if( statement->nodeType == snStatementBlock )
  1785. CompileStatementBlock(statement, true, hasReturn, bc);
  1786. else if( statement->nodeType == snIf )
  1787. CompileIfStatement(statement, hasReturn, bc);
  1788. else if( statement->nodeType == snFor )
  1789. CompileForStatement(statement, bc);
  1790. else if( statement->nodeType == snWhile )
  1791. CompileWhileStatement(statement, bc);
  1792. else if( statement->nodeType == snDoWhile )
  1793. CompileDoWhileStatement(statement, bc);
  1794. else if( statement->nodeType == snExpressionStatement )
  1795. CompileExpressionStatement(statement, bc);
  1796. else if( statement->nodeType == snBreak )
  1797. CompileBreakStatement(statement, bc);
  1798. else if( statement->nodeType == snContinue )
  1799. CompileContinueStatement(statement, bc);
  1800. else if( statement->nodeType == snSwitch )
  1801. CompileSwitchStatement(statement, hasReturn, bc);
  1802. else if( statement->nodeType == snReturn )
  1803. {
  1804. CompileReturnStatement(statement, bc);
  1805. *hasReturn = true;
  1806. }
  1807. }
  1808. void asCCompiler::CompileSwitchStatement(asCScriptNode *snode, bool *, asCByteCode *bc)
  1809. {
  1810. // TODO: inheritance: Must guarantee that all options in the switch case call a constructor, or that none call it.
  1811. // Reserve label for break statements
  1812. int breakLabel = nextLabel++;
  1813. breakLabels.PushLast(breakLabel);
  1814. // Add a variable scope that will be used by CompileBreak
  1815. // to know where to stop deallocating variables
  1816. AddVariableScope(true, false);
  1817. //---------------------------
  1818. // Compile the switch expression
  1819. //-------------------------------
  1820. // Compile the switch expression
  1821. asSExprContext expr(engine);
  1822. CompileAssignment(snode->firstChild, &expr);
  1823. // Verify that the expression is a primitive type
  1824. if( !expr.type.dataType.IsIntegerType() && !expr.type.dataType.IsUnsignedType() && !expr.type.dataType.IsEnumType() )
  1825. {
  1826. Error(TXT_SWITCH_MUST_BE_INTEGRAL, snode->firstChild);
  1827. return;
  1828. }
  1829. ProcessPropertyGetAccessor(&expr, snode);
  1830. // TODO: Need to support 64bit integers
  1831. // Convert the expression to a 32bit variable
  1832. asCDataType to;
  1833. if( expr.type.dataType.IsIntegerType() || expr.type.dataType.IsEnumType() )
  1834. to.SetTokenType(ttInt);
  1835. else if( expr.type.dataType.IsUnsignedType() )
  1836. to.SetTokenType(ttUInt);
  1837. // Make sure the value is in a variable
  1838. if( expr.type.dataType.IsReference() )
  1839. ConvertToVariable(&expr);
  1840. ImplicitConversion(&expr, to, snode->firstChild, asIC_IMPLICIT_CONV, true);
  1841. ConvertToVariable(&expr);
  1842. int offset = expr.type.stackOffset;
  1843. ProcessDeferredParams(&expr);
  1844. //-------------------------------
  1845. // Determine case values and labels
  1846. //--------------------------------
  1847. // Remember the first label so that we can later pass the
  1848. // correct label to each CompileCase()
  1849. int firstCaseLabel = nextLabel;
  1850. int defaultLabel = 0;
  1851. asCArray<int> caseValues;
  1852. asCArray<int> caseLabels;
  1853. // Compile all case comparisons and make them jump to the right label
  1854. asCScriptNode *cnode = snode->firstChild->next;
  1855. while( cnode )
  1856. {
  1857. // Each case should have a constant expression
  1858. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  1859. {
  1860. // Compile expression
  1861. asSExprContext c(engine);
  1862. CompileExpression(cnode->firstChild, &c);
  1863. // Verify that the result is a constant
  1864. if( !c.type.isConstant )
  1865. Error(TXT_SWITCH_CASE_MUST_BE_CONSTANT, cnode->firstChild);
  1866. // Verify that the result is an integral number
  1867. if( !c.type.dataType.IsIntegerType() && !c.type.dataType.IsUnsignedType() && !c.type.dataType.IsEnumType() )
  1868. Error(TXT_SWITCH_MUST_BE_INTEGRAL, cnode->firstChild);
  1869. ImplicitConversion(&c, to, cnode->firstChild, asIC_IMPLICIT_CONV, true);
  1870. // Has this case been declared already?
  1871. if( caseValues.IndexOf(c.type.intValue) >= 0 )
  1872. {
  1873. Error(TXT_DUPLICATE_SWITCH_CASE, cnode->firstChild);
  1874. }
  1875. // TODO: Optimize: We can insert the numbers sorted already
  1876. // Store constant for later use
  1877. caseValues.PushLast(c.type.intValue);
  1878. // Reserve label for this case
  1879. caseLabels.PushLast(nextLabel++);
  1880. }
  1881. else
  1882. {
  1883. // Is default the last case?
  1884. if( cnode->next )
  1885. {
  1886. Error(TXT_DEFAULT_MUST_BE_LAST, cnode);
  1887. break;
  1888. }
  1889. // Reserve label for this case
  1890. defaultLabel = nextLabel++;
  1891. }
  1892. cnode = cnode->next;
  1893. }
  1894. // check for empty switch
  1895. if (caseValues.GetLength() == 0)
  1896. {
  1897. Error(TXT_EMPTY_SWITCH, snode);
  1898. return;
  1899. }
  1900. if( defaultLabel == 0 )
  1901. defaultLabel = breakLabel;
  1902. //---------------------------------
  1903. // Output the optimized case comparisons
  1904. // with jumps to the case code
  1905. //------------------------------------
  1906. // Sort the case values by increasing value. Do the sort together with the labels
  1907. // A simple bubble sort is sufficient since we don't expect a huge number of values
  1908. for( asUINT fwd = 1; fwd < caseValues.GetLength(); fwd++ )
  1909. {
  1910. for( int bck = fwd - 1; bck >= 0; bck-- )
  1911. {
  1912. int bckp = bck + 1;
  1913. if( caseValues[bck] > caseValues[bckp] )
  1914. {
  1915. // Swap the values in both arrays
  1916. int swap = caseValues[bckp];
  1917. caseValues[bckp] = caseValues[bck];
  1918. caseValues[bck] = swap;
  1919. swap = caseLabels[bckp];
  1920. caseLabels[bckp] = caseLabels[bck];
  1921. caseLabels[bck] = swap;
  1922. }
  1923. else
  1924. break;
  1925. }
  1926. }
  1927. // Find ranges of consecutive numbers
  1928. asCArray<int> ranges;
  1929. ranges.PushLast(0);
  1930. asUINT n;
  1931. for( n = 1; n < caseValues.GetLength(); ++n )
  1932. {
  1933. // We can join numbers that are less than 5 numbers
  1934. // apart since the output code will still be smaller
  1935. if( caseValues[n] > caseValues[n-1] + 5 )
  1936. ranges.PushLast(n);
  1937. }
  1938. // If the value is larger than the largest case value, jump to default
  1939. int tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1940. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[caseValues.GetLength()-1]);
  1941. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  1942. expr.bc.InstrDWORD(asBC_JP, defaultLabel);
  1943. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1944. // TODO: optimize: We could possibly optimize this even more by doing a
  1945. // binary search instead of a linear search through the ranges
  1946. // For each range
  1947. int range;
  1948. for( range = 0; range < (int)ranges.GetLength(); range++ )
  1949. {
  1950. // Find the largest value in this range
  1951. int maxRange = caseValues[ranges[range]];
  1952. int index = ranges[range];
  1953. for( ; (index < (int)caseValues.GetLength()) && (caseValues[index] <= maxRange + 5); index++ )
  1954. maxRange = caseValues[index];
  1955. // If there are only 2 numbers then it is better to compare them directly
  1956. if( index - ranges[range] > 2 )
  1957. {
  1958. // If the value is smaller than the smallest case value in the range, jump to default
  1959. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1960. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  1961. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  1962. expr.bc.InstrDWORD(asBC_JS, defaultLabel);
  1963. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1964. int nextRangeLabel = nextLabel++;
  1965. // If this is the last range we don't have to make this test
  1966. if( range < (int)ranges.GetLength() - 1 )
  1967. {
  1968. // If the value is larger than the largest case value in the range, jump to the next range
  1969. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1970. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, maxRange);
  1971. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  1972. expr.bc.InstrDWORD(asBC_JP, nextRangeLabel);
  1973. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1974. }
  1975. // Jump forward according to the value
  1976. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1977. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  1978. expr.bc.InstrW_W_W(asBC_SUBi, tmpOffset, offset, tmpOffset);
  1979. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1980. expr.bc.JmpP(tmpOffset, maxRange - caseValues[ranges[range]]);
  1981. // Add the list of jumps to the correct labels (any holes, jump to default)
  1982. index = ranges[range];
  1983. for( int n = caseValues[index]; n <= maxRange; n++ )
  1984. {
  1985. if( caseValues[index] == n )
  1986. expr.bc.InstrINT(asBC_JMP, caseLabels[index++]);
  1987. else
  1988. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  1989. }
  1990. expr.bc.Label((short)nextRangeLabel);
  1991. }
  1992. else
  1993. {
  1994. // Simply make a comparison with each value
  1995. int n;
  1996. for( n = ranges[range]; n < index; ++n )
  1997. {
  1998. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1999. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[n]);
  2000. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2001. expr.bc.InstrDWORD(asBC_JZ, caseLabels[n]);
  2002. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2003. }
  2004. }
  2005. }
  2006. // Catch any value that falls trough
  2007. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  2008. // Release the temporary variable previously stored
  2009. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2010. //----------------------------------
  2011. // Output case implementations
  2012. //----------------------------------
  2013. // Compile case implementations, each one with the label before it
  2014. cnode = snode->firstChild->next;
  2015. while( cnode )
  2016. {
  2017. // Each case should have a constant expression
  2018. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  2019. {
  2020. expr.bc.Label((short)firstCaseLabel++);
  2021. CompileCase(cnode->firstChild->next, &expr.bc);
  2022. }
  2023. else
  2024. {
  2025. expr.bc.Label((short)defaultLabel);
  2026. // Is default the last case?
  2027. if( cnode->next )
  2028. {
  2029. // We've already reported this error
  2030. break;
  2031. }
  2032. CompileCase(cnode->firstChild, &expr.bc);
  2033. }
  2034. cnode = cnode->next;
  2035. }
  2036. //--------------------------------
  2037. bc->AddCode(&expr.bc);
  2038. // Add break label
  2039. bc->Label((short)breakLabel);
  2040. breakLabels.PopLast();
  2041. RemoveVariableScope();
  2042. }
  2043. void asCCompiler::CompileCase(asCScriptNode *node, asCByteCode *bc)
  2044. {
  2045. bool isFinished = false;
  2046. bool hasReturn = false;
  2047. while( node )
  2048. {
  2049. if( hasReturn || isFinished )
  2050. {
  2051. Warning(TXT_UNREACHABLE_CODE, node);
  2052. break;
  2053. }
  2054. if( node->nodeType == snBreak || node->nodeType == snContinue )
  2055. isFinished = true;
  2056. asCByteCode statement(engine);
  2057. if( node->nodeType == snDeclaration )
  2058. {
  2059. Error(TXT_DECL_IN_SWITCH, node);
  2060. // Compile it anyway to avoid further compiler errors
  2061. CompileDeclaration(node, &statement);
  2062. }
  2063. else
  2064. CompileStatement(node, &hasReturn, &statement);
  2065. LineInstr(bc, node->tokenPos);
  2066. bc->AddCode(&statement);
  2067. if( !hasCompileErrors )
  2068. asASSERT( tempVariables.GetLength() == 0 );
  2069. node = node->next;
  2070. }
  2071. }
  2072. void asCCompiler::CompileIfStatement(asCScriptNode *inode, bool *hasReturn, asCByteCode *bc)
  2073. {
  2074. // We will use one label for the if statement
  2075. // and possibly another for the else statement
  2076. int afterLabel = nextLabel++;
  2077. // Compile the expression
  2078. asSExprContext expr(engine);
  2079. CompileAssignment(inode->firstChild, &expr);
  2080. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2081. {
  2082. Error(TXT_EXPR_MUST_BE_BOOL, inode->firstChild);
  2083. expr.type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 1);
  2084. }
  2085. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2086. ProcessDeferredParams(&expr);
  2087. if( !expr.type.isConstant )
  2088. {
  2089. ProcessPropertyGetAccessor(&expr, inode);
  2090. ConvertToVariable(&expr);
  2091. // Add byte code from the expression
  2092. bc->AddCode(&expr.bc);
  2093. // Add a test
  2094. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2095. bc->Instr(asBC_ClrHi);
  2096. bc->InstrDWORD(asBC_JZ, afterLabel);
  2097. ReleaseTemporaryVariable(expr.type, bc);
  2098. }
  2099. else if( expr.type.dwordValue == 0 )
  2100. {
  2101. // Jump to the else case
  2102. bc->InstrINT(asBC_JMP, afterLabel);
  2103. // TODO: Should we warn that the expression will always go to the else?
  2104. }
  2105. // Compile the if statement
  2106. bool origIsConstructorCalled = m_isConstructorCalled;
  2107. bool hasReturn1;
  2108. asCByteCode ifBC(engine);
  2109. CompileStatement(inode->firstChild->next, &hasReturn1, &ifBC);
  2110. // Add the byte code
  2111. LineInstr(bc, inode->firstChild->next->tokenPos);
  2112. bc->AddCode(&ifBC);
  2113. if( inode->firstChild->next->nodeType == snExpressionStatement && inode->firstChild->next->firstChild == 0 )
  2114. {
  2115. // Don't allow if( expr );
  2116. Error(TXT_IF_WITH_EMPTY_STATEMENT, inode->firstChild->next);
  2117. }
  2118. // If one of the statements call the constructor, the other must as well
  2119. // otherwise it is possible the constructor is never called
  2120. bool constructorCall1 = false;
  2121. bool constructorCall2 = false;
  2122. if( !origIsConstructorCalled && m_isConstructorCalled )
  2123. constructorCall1 = true;
  2124. // Do we have an else statement?
  2125. if( inode->firstChild->next != inode->lastChild )
  2126. {
  2127. // Reset the constructor called flag so the else statement can call the constructor too
  2128. m_isConstructorCalled = origIsConstructorCalled;
  2129. int afterElse = 0;
  2130. if( !hasReturn1 )
  2131. {
  2132. afterElse = nextLabel++;
  2133. // Add jump to after the else statement
  2134. bc->InstrINT(asBC_JMP, afterElse);
  2135. }
  2136. // Add label for the else statement
  2137. bc->Label((short)afterLabel);
  2138. bool hasReturn2;
  2139. asCByteCode elseBC(engine);
  2140. CompileStatement(inode->lastChild, &hasReturn2, &elseBC);
  2141. // Add byte code for the else statement
  2142. LineInstr(bc, inode->lastChild->tokenPos);
  2143. bc->AddCode(&elseBC);
  2144. if( inode->lastChild->nodeType == snExpressionStatement && inode->lastChild->firstChild == 0 )
  2145. {
  2146. // Don't allow if( expr ) {} else;
  2147. Error(TXT_ELSE_WITH_EMPTY_STATEMENT, inode->lastChild);
  2148. }
  2149. if( !hasReturn1 )
  2150. {
  2151. // Add label for the end of else statement
  2152. bc->Label((short)afterElse);
  2153. }
  2154. // The if statement only has return if both alternatives have
  2155. *hasReturn = hasReturn1 && hasReturn2;
  2156. if( !origIsConstructorCalled && m_isConstructorCalled )
  2157. constructorCall2 = true;
  2158. }
  2159. else
  2160. {
  2161. // Add label for the end of if statement
  2162. bc->Label((short)afterLabel);
  2163. *hasReturn = false;
  2164. }
  2165. // Make sure both or neither conditions call a constructor
  2166. if( (constructorCall1 && !constructorCall2) ||
  2167. (constructorCall2 && !constructorCall1) )
  2168. {
  2169. Error(TXT_BOTH_CONDITIONS_MUST_CALL_CONSTRUCTOR, inode);
  2170. }
  2171. m_isConstructorCalled = origIsConstructorCalled || constructorCall1 || constructorCall2;
  2172. }
  2173. void asCCompiler::CompileForStatement(asCScriptNode *fnode, asCByteCode *bc)
  2174. {
  2175. // TODO: optimize: We should be able to remove the static JMP to the beginning of the loop by rearranging the
  2176. // byte code a bit.
  2177. //
  2178. // init
  2179. // jump to before
  2180. // begin:
  2181. // statements
  2182. // continue:
  2183. // next
  2184. // before:
  2185. // condition
  2186. // if loop jump to begin
  2187. // break:
  2188. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2189. AddVariableScope(true, true);
  2190. // We will use three labels for the for loop
  2191. int beforeLabel = nextLabel++;
  2192. int afterLabel = nextLabel++;
  2193. int continueLabel = nextLabel++;
  2194. continueLabels.PushLast(continueLabel);
  2195. breakLabels.PushLast(afterLabel);
  2196. //---------------------------------------
  2197. // Compile the initialization statement
  2198. asCByteCode initBC(engine);
  2199. if( fnode->firstChild->nodeType == snDeclaration )
  2200. CompileDeclaration(fnode->firstChild, &initBC);
  2201. else
  2202. CompileExpressionStatement(fnode->firstChild, &initBC);
  2203. //-----------------------------------
  2204. // Compile the condition statement
  2205. asSExprContext expr(engine);
  2206. asCScriptNode *second = fnode->firstChild->next;
  2207. if( second->firstChild )
  2208. {
  2209. int r = CompileAssignment(second->firstChild, &expr);
  2210. if( r >= 0 )
  2211. {
  2212. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2213. Error(TXT_EXPR_MUST_BE_BOOL, second);
  2214. else
  2215. {
  2216. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2217. ProcessDeferredParams(&expr);
  2218. ProcessPropertyGetAccessor(&expr, second);
  2219. // If expression is false exit the loop
  2220. ConvertToVariable(&expr);
  2221. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2222. expr.bc.Instr(asBC_ClrHi);
  2223. expr.bc.InstrDWORD(asBC_JZ, afterLabel);
  2224. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2225. }
  2226. }
  2227. }
  2228. //---------------------------
  2229. // Compile the increment statement
  2230. asCByteCode nextBC(engine);
  2231. asCScriptNode *third = second->next;
  2232. if( third->nodeType == snExpressionStatement )
  2233. CompileExpressionStatement(third, &nextBC);
  2234. //------------------------------
  2235. // Compile loop statement
  2236. bool hasReturn;
  2237. asCByteCode forBC(engine);
  2238. CompileStatement(fnode->lastChild, &hasReturn, &forBC);
  2239. //-------------------------------
  2240. // Join the code pieces
  2241. bc->AddCode(&initBC);
  2242. bc->Label((short)beforeLabel);
  2243. // Add a suspend bytecode inside the loop to guarantee
  2244. // that the application can suspend the execution
  2245. bc->Instr(asBC_SUSPEND);
  2246. bc->InstrPTR(asBC_JitEntry, 0);
  2247. bc->AddCode(&expr.bc);
  2248. LineInstr(bc, fnode->lastChild->tokenPos);
  2249. bc->AddCode(&forBC);
  2250. bc->Label((short)continueLabel);
  2251. bc->AddCode(&nextBC);
  2252. bc->InstrINT(asBC_JMP, beforeLabel);
  2253. bc->Label((short)afterLabel);
  2254. continueLabels.PopLast();
  2255. breakLabels.PopLast();
  2256. // Deallocate variables in this block, in reverse order
  2257. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  2258. {
  2259. sVariable *v = variables->variables[n];
  2260. // Call variable destructors here, for variables not yet destroyed
  2261. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  2262. // Don't deallocate function parameters
  2263. if( v->stackOffset > 0 )
  2264. DeallocateVariable(v->stackOffset);
  2265. }
  2266. RemoveVariableScope();
  2267. }
  2268. void asCCompiler::CompileWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2269. {
  2270. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2271. AddVariableScope(true, true);
  2272. // We will use two labels for the while loop
  2273. int beforeLabel = nextLabel++;
  2274. int afterLabel = nextLabel++;
  2275. continueLabels.PushLast(beforeLabel);
  2276. breakLabels.PushLast(afterLabel);
  2277. // Add label before the expression
  2278. bc->Label((short)beforeLabel);
  2279. // Compile expression
  2280. asSExprContext expr(engine);
  2281. CompileAssignment(wnode->firstChild, &expr);
  2282. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2283. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2284. else
  2285. {
  2286. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2287. ProcessDeferredParams(&expr);
  2288. ProcessPropertyGetAccessor(&expr, wnode);
  2289. // Add byte code for the expression
  2290. ConvertToVariable(&expr);
  2291. bc->AddCode(&expr.bc);
  2292. // Jump to end of statement if expression is false
  2293. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2294. bc->Instr(asBC_ClrHi);
  2295. bc->InstrDWORD(asBC_JZ, afterLabel);
  2296. ReleaseTemporaryVariable(expr.type, bc);
  2297. }
  2298. // Add a suspend bytecode inside the loop to guarantee
  2299. // that the application can suspend the execution
  2300. bc->Instr(asBC_SUSPEND);
  2301. bc->InstrPTR(asBC_JitEntry, 0);
  2302. // Compile statement
  2303. bool hasReturn;
  2304. asCByteCode whileBC(engine);
  2305. CompileStatement(wnode->lastChild, &hasReturn, &whileBC);
  2306. // Add byte code for the statement
  2307. LineInstr(bc, wnode->lastChild->tokenPos);
  2308. bc->AddCode(&whileBC);
  2309. // Jump to the expression
  2310. bc->InstrINT(asBC_JMP, beforeLabel);
  2311. // Add label after the statement
  2312. bc->Label((short)afterLabel);
  2313. continueLabels.PopLast();
  2314. breakLabels.PopLast();
  2315. RemoveVariableScope();
  2316. }
  2317. void asCCompiler::CompileDoWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2318. {
  2319. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2320. AddVariableScope(true, true);
  2321. // We will use two labels for the while loop
  2322. int beforeLabel = nextLabel++;
  2323. int beforeTest = nextLabel++;
  2324. int afterLabel = nextLabel++;
  2325. continueLabels.PushLast(beforeTest);
  2326. breakLabels.PushLast(afterLabel);
  2327. // Add label before the statement
  2328. bc->Label((short)beforeLabel);
  2329. // Compile statement
  2330. bool hasReturn;
  2331. asCByteCode whileBC(engine);
  2332. CompileStatement(wnode->firstChild, &hasReturn, &whileBC);
  2333. // Add byte code for the statement
  2334. LineInstr(bc, wnode->firstChild->tokenPos);
  2335. bc->AddCode(&whileBC);
  2336. // Add label before the expression
  2337. bc->Label((short)beforeTest);
  2338. // Add a suspend bytecode inside the loop to guarantee
  2339. // that the application can suspend the execution
  2340. bc->Instr(asBC_SUSPEND);
  2341. bc->InstrPTR(asBC_JitEntry, 0);
  2342. // Add a line instruction
  2343. LineInstr(bc, wnode->lastChild->tokenPos);
  2344. // Compile expression
  2345. asSExprContext expr(engine);
  2346. CompileAssignment(wnode->lastChild, &expr);
  2347. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2348. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2349. else
  2350. {
  2351. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2352. ProcessDeferredParams(&expr);
  2353. ProcessPropertyGetAccessor(&expr, wnode);
  2354. // Add byte code for the expression
  2355. ConvertToVariable(&expr);
  2356. bc->AddCode(&expr.bc);
  2357. // Jump to next iteration if expression is true
  2358. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2359. bc->Instr(asBC_ClrHi);
  2360. bc->InstrDWORD(asBC_JNZ, beforeLabel);
  2361. ReleaseTemporaryVariable(expr.type, bc);
  2362. }
  2363. // Add label after the statement
  2364. bc->Label((short)afterLabel);
  2365. continueLabels.PopLast();
  2366. breakLabels.PopLast();
  2367. RemoveVariableScope();
  2368. }
  2369. void asCCompiler::CompileBreakStatement(asCScriptNode *node, asCByteCode *bc)
  2370. {
  2371. if( breakLabels.GetLength() == 0 )
  2372. {
  2373. Error(TXT_INVALID_BREAK, node);
  2374. return;
  2375. }
  2376. // Add destructor calls for all variables that will go out of scope
  2377. // Put this clean up in a block to allow exception handler to understand them
  2378. bc->Block(true);
  2379. asCVariableScope *vs = variables;
  2380. while( !vs->isBreakScope )
  2381. {
  2382. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2383. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2384. vs = vs->parent;
  2385. }
  2386. bc->Block(false);
  2387. bc->InstrINT(asBC_JMP, breakLabels[breakLabels.GetLength()-1]);
  2388. }
  2389. void asCCompiler::CompileContinueStatement(asCScriptNode *node, asCByteCode *bc)
  2390. {
  2391. if( continueLabels.GetLength() == 0 )
  2392. {
  2393. Error(TXT_INVALID_CONTINUE, node);
  2394. return;
  2395. }
  2396. // Add destructor calls for all variables that will go out of scope
  2397. // Put this clean up in a block to allow exception handler to understand them
  2398. bc->Block(true);
  2399. asCVariableScope *vs = variables;
  2400. while( !vs->isContinueScope )
  2401. {
  2402. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2403. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2404. vs = vs->parent;
  2405. }
  2406. bc->Block(false);
  2407. bc->InstrINT(asBC_JMP, continueLabels[continueLabels.GetLength()-1]);
  2408. }
  2409. void asCCompiler::CompileExpressionStatement(asCScriptNode *enode, asCByteCode *bc)
  2410. {
  2411. if( enode->firstChild )
  2412. {
  2413. // Compile the expression
  2414. asSExprContext expr(engine);
  2415. CompileAssignment(enode->firstChild, &expr);
  2416. // Pop the value from the stack
  2417. if( !expr.type.dataType.IsPrimitive() )
  2418. expr.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  2419. // Release temporary variables used by expression
  2420. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2421. ProcessDeferredParams(&expr);
  2422. bc->AddCode(&expr.bc);
  2423. }
  2424. }
  2425. void asCCompiler::PrepareTemporaryObject(asCScriptNode *node, asSExprContext *ctx, asCArray<int> *reservedVars, bool forceOnHeap)
  2426. {
  2427. // If the object already is stored in temporary variable then nothing needs to be done
  2428. // Note, a type can be temporary without being a variable, in which case it is holding off
  2429. // on releasing a previously used object.
  2430. if( ctx->type.isTemporary && ctx->type.isVariable &&
  2431. !(forceOnHeap && !IsVariableOnHeap(ctx->type.stackOffset)) )
  2432. {
  2433. // If the temporary object is currently not a reference
  2434. // the expression needs to be reevaluated to a reference
  2435. if( !ctx->type.dataType.IsReference() )
  2436. {
  2437. ctx->bc.Pop(AS_PTR_SIZE);
  2438. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  2439. ctx->type.dataType.MakeReference(true);
  2440. }
  2441. return;
  2442. }
  2443. // Allocate temporary variable
  2444. asCDataType dt = ctx->type.dataType;
  2445. dt.MakeReference(false);
  2446. dt.MakeReadOnly(false);
  2447. int offset = AllocateVariableNotIn(dt, true, reservedVars, forceOnHeap);
  2448. // Objects stored on the stack are not considered references
  2449. dt.MakeReference(IsVariableOnHeap(offset));
  2450. asCTypeInfo lvalue;
  2451. lvalue.Set(dt);
  2452. lvalue.isTemporary = true;
  2453. lvalue.stackOffset = (short)offset;
  2454. lvalue.isVariable = true;
  2455. lvalue.isExplicitHandle = ctx->type.isExplicitHandle;
  2456. if( (!dt.IsObjectHandle() || (dt.GetObjectType() && (dt.GetObjectType()->flags & asOBJ_ASHANDLE))) &&
  2457. dt.GetObjectType() && (dt.GetBehaviour()->copyconstruct || dt.GetBehaviour()->copyfactory) )
  2458. {
  2459. PrepareForAssignment(&lvalue.dataType, ctx, node, true);
  2460. // Use the copy constructor/factory when available
  2461. CallCopyConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, ctx, node);
  2462. }
  2463. else
  2464. {
  2465. // Allocate and construct the temporary object
  2466. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, node);
  2467. // Assign the object to the temporary variable
  2468. PrepareForAssignment(&lvalue.dataType, ctx, node, true);
  2469. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2470. PerformAssignment(&lvalue, &ctx->type, &ctx->bc, node);
  2471. // Pop the original reference
  2472. ctx->bc.Pop(AS_PTR_SIZE);
  2473. }
  2474. // If the expression was holding off on releasing a
  2475. // previously used object, we need to release it now
  2476. if( ctx->type.isTemporary )
  2477. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  2478. // Push the reference to the temporary variable on the stack
  2479. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2480. lvalue.dataType.MakeReference(IsVariableOnHeap(offset));
  2481. ctx->type = lvalue;
  2482. }
  2483. void asCCompiler::CompileReturnStatement(asCScriptNode *rnode, asCByteCode *bc)
  2484. {
  2485. // Get return type and location
  2486. sVariable *v = variables->GetVariable("return");
  2487. // Basic validations
  2488. if( v->type.GetSizeOnStackDWords() > 0 && !rnode->firstChild )
  2489. {
  2490. Error(TXT_MUST_RETURN_VALUE, rnode);
  2491. return;
  2492. }
  2493. else if( v->type.GetSizeOnStackDWords() == 0 && rnode->firstChild )
  2494. {
  2495. Error(TXT_CANT_RETURN_VALUE, rnode);
  2496. return;
  2497. }
  2498. // Compile the expression
  2499. if( rnode->firstChild )
  2500. {
  2501. // Compile the expression
  2502. asSExprContext expr(engine);
  2503. int r = CompileAssignment(rnode->firstChild, &expr);
  2504. if( r < 0 ) return;
  2505. if( v->type.IsReference() )
  2506. {
  2507. // The expression that gives the reference must not use any of the
  2508. // variables that must be destroyed upon exit, because then it means
  2509. // reference will stay alive while the clean-up is done, which could
  2510. // potentially mean that the reference is invalidated by the clean-up.
  2511. //
  2512. // When the function is returning a reference, the clean-up of the
  2513. // variables must be done before the evaluation of the expression.
  2514. //
  2515. // A reference to a global variable, or a class member for class methods
  2516. // should be allowed to be returned.
  2517. if( !(expr.type.dataType.IsReference() ||
  2518. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle())) )
  2519. {
  2520. // Clean up the potential deferred parameters
  2521. ProcessDeferredParams(&expr);
  2522. Error(TXT_NOT_VALID_REFERENCE, rnode);
  2523. return;
  2524. }
  2525. // No references to local variables, temporary variables, or parameters
  2526. // are allowed to be returned, since they go out of scope when the function
  2527. // returns. Even reference parameters are disallowed, since it is not possible
  2528. // to know the scope of them. The exception is the 'this' pointer, which
  2529. // is treated by the compiler as a local variable, but isn't really so.
  2530. if( (expr.type.isVariable && !(expr.type.stackOffset == 0 && outFunc->objectType)) || expr.type.isTemporary )
  2531. {
  2532. // Clean up the potential deferred parameters
  2533. ProcessDeferredParams(&expr);
  2534. Error(TXT_CANNOT_RETURN_REF_TO_LOCAL, rnode);
  2535. return;
  2536. }
  2537. // The type must match exactly as we cannot convert
  2538. // the reference without loosing the original value
  2539. if( !(v->type == expr.type.dataType ||
  2540. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle() && v->type.IsEqualExceptRef(expr.type.dataType))) )
  2541. {
  2542. // Clean up the potential deferred parameters
  2543. ProcessDeferredParams(&expr);
  2544. asCString str;
  2545. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2546. Error(str.AddressOf(), rnode);
  2547. return;
  2548. }
  2549. // The expression must not have any deferred expressions, because the evaluation
  2550. // of these cannot be done without keeping the reference which is not safe
  2551. if( expr.deferredParams.GetLength() )
  2552. {
  2553. // Clean up the potential deferred parameters
  2554. ProcessDeferredParams(&expr);
  2555. Error(TXT_REF_CANT_BE_RETURNED_DEFERRED_PARAM, rnode);
  2556. return;
  2557. }
  2558. // Make sure the expression isn't using any local variables that
  2559. // will need to be cleaned up before the function completes
  2560. asCArray<int> usedVars;
  2561. expr.bc.GetVarsUsed(usedVars);
  2562. for( asUINT n = 0; n < usedVars.GetLength(); n++ )
  2563. {
  2564. int var = GetVariableSlot(usedVars[n]);
  2565. if( var != -1 )
  2566. {
  2567. asCDataType dt = variableAllocations[var];
  2568. if( dt.IsObject() )
  2569. {
  2570. ProcessDeferredParams(&expr);
  2571. Error(TXT_REF_CANT_BE_RETURNED_LOCAL_VARS, rnode);
  2572. return;
  2573. }
  2574. }
  2575. }
  2576. // All objects in the function must be cleaned up before the expression
  2577. // is evaluated, otherwise there is a possibility that the cleanup will
  2578. // invalidate the reference.
  2579. // Destroy the local variables before loading
  2580. // the reference into the register. This will
  2581. // be done before the expression is evaluated.
  2582. DestroyVariables(bc);
  2583. // For primitives the reference is already in the register,
  2584. // but for non-primitives the reference is on the stack so we
  2585. // need to load it into the register
  2586. if( !expr.type.dataType.IsPrimitive() )
  2587. {
  2588. if( (!expr.type.dataType.IsObjectHandle() || (expr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) &&
  2589. expr.type.dataType.IsReference() )
  2590. expr.bc.Instr(asBC_RDSPTR);
  2591. expr.bc.Instr(asBC_PopRPtr);
  2592. }
  2593. // There are no temporaries to release so we're done
  2594. }
  2595. else // if( !v->type.IsReference() )
  2596. {
  2597. ProcessPropertyGetAccessor(&expr, rnode);
  2598. // Prepare the value for assignment
  2599. IsVariableInitialized(&expr.type, rnode->firstChild);
  2600. if( v->type.IsPrimitive() )
  2601. {
  2602. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2603. // Implicitly convert the value to the return type
  2604. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  2605. // Verify that the conversion was successful
  2606. if( expr.type.dataType != v->type )
  2607. {
  2608. asCString str;
  2609. str.Format(TXT_NO_CONVERSION_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2610. Error(str.AddressOf(), rnode);
  2611. return;
  2612. }
  2613. else
  2614. {
  2615. ConvertToVariable(&expr);
  2616. // Clean up the local variables and process deferred parameters
  2617. DestroyVariables(&expr.bc);
  2618. ProcessDeferredParams(&expr);
  2619. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2620. // Load the variable in the register
  2621. if( v->type.GetSizeOnStackDWords() == 1 )
  2622. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2623. else
  2624. expr.bc.InstrSHORT(asBC_CpyVtoR8, expr.type.stackOffset);
  2625. }
  2626. }
  2627. else if( v->type.IsObject() )
  2628. {
  2629. #ifndef AS_OLD
  2630. // Value types are returned on the stack, in a location
  2631. // that has been reserved by the calling function.
  2632. if( outFunc->DoesReturnOnStack() )
  2633. {
  2634. // TODO: optimize: If the return type has a constructor that takes the type of the expression,
  2635. // it should be called directly instead of first converting the expression and
  2636. // then copy the value.
  2637. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  2638. {
  2639. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  2640. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  2641. {
  2642. asCString str;
  2643. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2644. Error(str.AddressOf(), rnode->firstChild);
  2645. return;
  2646. }
  2647. }
  2648. int offset = outFunc->objectType ? -AS_PTR_SIZE : 0;
  2649. if( v->type.GetObjectType()->beh.copyconstruct )
  2650. {
  2651. PrepareForAssignment(&v->type, &expr, rnode->firstChild, false);
  2652. CallCopyConstructor(v->type, offset, false, &expr.bc, &expr, rnode->firstChild, false, true);
  2653. }
  2654. else
  2655. {
  2656. // If the copy constructor doesn't exist, then a manual assignment needs to be done instead.
  2657. CallDefaultConstructor(v->type, offset, false, &expr.bc, rnode->firstChild, false, true);
  2658. PrepareForAssignment(&v->type, &expr, rnode->firstChild, false);
  2659. expr.bc.InstrSHORT(asBC_PSF, (short)offset);
  2660. expr.bc.Instr(asBC_RDSPTR);
  2661. asSExprContext lexpr(engine);
  2662. lexpr.type.Set(v->type);
  2663. lexpr.type.isLValue = true;
  2664. PerformAssignment(&lexpr.type, &expr.type, &expr.bc, rnode->firstChild);
  2665. expr.bc.Pop(AS_PTR_SIZE);
  2666. // Release any temporary variable
  2667. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2668. }
  2669. // Clean up the local variables and process deferred parameters
  2670. DestroyVariables(&expr.bc);
  2671. ProcessDeferredParams(&expr);
  2672. }
  2673. else
  2674. #endif
  2675. {
  2676. #ifndef AS_OLD
  2677. asASSERT( v->type.GetObjectType()->flags & asOBJ_REF );
  2678. #endif
  2679. // Prepare the expression to be loaded into the object
  2680. // register. This will place the reference in local variable
  2681. PrepareArgument(&v->type, &expr, rnode->firstChild, false, 0, 0, true);
  2682. // Pop the reference to the temporary variable
  2683. expr.bc.Pop(AS_PTR_SIZE);
  2684. // Clean up the local variables and process deferred parameters
  2685. DestroyVariables(&expr.bc);
  2686. ProcessDeferredParams(&expr);
  2687. // Load the object pointer into the object register
  2688. // LOADOBJ also clears the address in the variable
  2689. expr.bc.InstrSHORT(asBC_LOADOBJ, expr.type.stackOffset);
  2690. // LOADOBJ cleared the address in the variable so the object will not be freed
  2691. // here, but the temporary variable must still be freed so the slot can be reused
  2692. // By releasing without the bytecode we do just that.
  2693. ReleaseTemporaryVariable(expr.type, 0);
  2694. }
  2695. }
  2696. }
  2697. bc->AddCode(&expr.bc);
  2698. }
  2699. else
  2700. {
  2701. // For functions that don't return anything
  2702. // we just detroy the local variables
  2703. DestroyVariables(bc);
  2704. }
  2705. // Jump to the end of the function
  2706. bc->InstrINT(asBC_JMP, 0);
  2707. }
  2708. void asCCompiler::DestroyVariables(asCByteCode *bc)
  2709. {
  2710. // Call destructor on all variables except for the function parameters
  2711. // Put the clean-up in a block to allow exception handler to understand this
  2712. bc->Block(true);
  2713. asCVariableScope *vs = variables;
  2714. while( vs )
  2715. {
  2716. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2717. if( vs->variables[n]->stackOffset > 0 )
  2718. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2719. vs = vs->parent;
  2720. }
  2721. bc->Block(false);
  2722. }
  2723. void asCCompiler::AddVariableScope(bool isBreakScope, bool isContinueScope)
  2724. {
  2725. variables = asNEW(asCVariableScope)(variables);
  2726. variables->isBreakScope = isBreakScope;
  2727. variables->isContinueScope = isContinueScope;
  2728. }
  2729. void asCCompiler::RemoveVariableScope()
  2730. {
  2731. if( variables )
  2732. {
  2733. asCVariableScope *var = variables;
  2734. variables = variables->parent;
  2735. asDELETE(var,asCVariableScope);
  2736. }
  2737. }
  2738. void asCCompiler::Error(const char *msg, asCScriptNode *node)
  2739. {
  2740. asCString str;
  2741. int r = 0, c = 0;
  2742. asASSERT( node );
  2743. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2744. builder->WriteError(script->name.AddressOf(), msg, r, c);
  2745. hasCompileErrors = true;
  2746. }
  2747. void asCCompiler::Warning(const char *msg, asCScriptNode *node)
  2748. {
  2749. asCString str;
  2750. int r = 0, c = 0;
  2751. asASSERT( node );
  2752. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2753. builder->WriteWarning(script->name.AddressOf(), msg, r, c);
  2754. }
  2755. void asCCompiler::Information(const char *msg, asCScriptNode *node)
  2756. {
  2757. asCString str;
  2758. int r = 0, c = 0;
  2759. asASSERT( node );
  2760. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2761. builder->WriteInfo(script->name.AddressOf(), msg, r, c, false);
  2762. }
  2763. void asCCompiler::PrintMatchingFuncs(asCArray<int> &funcs, asCScriptNode *node)
  2764. {
  2765. int r = 0, c = 0;
  2766. asASSERT( node );
  2767. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2768. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  2769. {
  2770. asIScriptFunction *func = builder->GetFunctionDescription(funcs[n]);
  2771. builder->WriteInfo(script->name.AddressOf(), func->GetDeclaration(true), r, c, false);
  2772. }
  2773. }
  2774. int asCCompiler::AllocateVariable(const asCDataType &type, bool isTemporary, bool forceOnHeap)
  2775. {
  2776. return AllocateVariableNotIn(type, isTemporary, 0, forceOnHeap);
  2777. }
  2778. int asCCompiler::AllocateVariableNotIn(const asCDataType &type, bool isTemporary, asCArray<int> *vars, bool forceOnHeap)
  2779. {
  2780. asCDataType t(type);
  2781. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 1 )
  2782. t.SetTokenType(ttInt);
  2783. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 2 )
  2784. t.SetTokenType(ttDouble);
  2785. // Only null handles have the token type unrecognized token
  2786. asASSERT( t.IsObjectHandle() || t.GetTokenType() != ttUnrecognizedToken );
  2787. bool isOnHeap = true;
  2788. // TODO: Remove this once the bugs with value types on stack is fixed
  2789. // forceOnHeap = true;
  2790. if( t.IsPrimitive() ||
  2791. (t.GetObjectType() && (t.GetObjectType()->GetFlags() & asOBJ_VALUE) && !forceOnHeap) )
  2792. {
  2793. // Primitives and value types (unless overridden) are allocated on the stack
  2794. isOnHeap = false;
  2795. }
  2796. // Find a free location with the same type
  2797. for( asUINT n = 0; n < freeVariables.GetLength(); n++ )
  2798. {
  2799. int slot = freeVariables[n];
  2800. if( variableAllocations[slot].IsEqualExceptConst(t) &&
  2801. variableIsTemporary[slot] == isTemporary &&
  2802. variableIsOnHeap[slot] == isOnHeap )
  2803. {
  2804. // We can't return by slot, must count variable sizes
  2805. int offset = GetVariableOffset(slot);
  2806. // Verify that it is not in the list of used variables
  2807. bool isUsed = false;
  2808. if( vars )
  2809. {
  2810. for( asUINT m = 0; m < vars->GetLength(); m++ )
  2811. {
  2812. if( offset == (*vars)[m] )
  2813. {
  2814. isUsed = true;
  2815. break;
  2816. }
  2817. }
  2818. }
  2819. if( !isUsed )
  2820. {
  2821. if( n != freeVariables.GetLength() - 1 )
  2822. freeVariables[n] = freeVariables.PopLast();
  2823. else
  2824. freeVariables.PopLast();
  2825. if( isTemporary )
  2826. tempVariables.PushLast(offset);
  2827. return offset;
  2828. }
  2829. }
  2830. }
  2831. variableAllocations.PushLast(t);
  2832. variableIsTemporary.PushLast(isTemporary);
  2833. variableIsOnHeap.PushLast(isOnHeap);
  2834. int offset = GetVariableOffset((int)variableAllocations.GetLength()-1);
  2835. if( isTemporary )
  2836. tempVariables.PushLast(offset);
  2837. return offset;
  2838. }
  2839. int asCCompiler::GetVariableOffset(int varIndex)
  2840. {
  2841. // Return offset to the last dword on the stack
  2842. int varOffset = 1;
  2843. for( int n = 0; n < varIndex; n++ )
  2844. {
  2845. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  2846. varOffset += variableAllocations[n].GetSizeInMemoryDWords();
  2847. else
  2848. varOffset += variableAllocations[n].GetSizeOnStackDWords();
  2849. }
  2850. if( varIndex < (int)variableAllocations.GetLength() )
  2851. {
  2852. int size;
  2853. if( !variableIsOnHeap[varIndex] && variableAllocations[varIndex].IsObject() )
  2854. size = variableAllocations[varIndex].GetSizeInMemoryDWords();
  2855. else
  2856. size = variableAllocations[varIndex].GetSizeOnStackDWords();
  2857. if( size > 1 )
  2858. varOffset += size-1;
  2859. }
  2860. return varOffset;
  2861. }
  2862. int asCCompiler::GetVariableSlot(int offset)
  2863. {
  2864. int varOffset = 1;
  2865. for( asUINT n = 0; n < variableAllocations.GetLength(); n++ )
  2866. {
  2867. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  2868. varOffset += -1 + variableAllocations[n].GetSizeInMemoryDWords();
  2869. else
  2870. varOffset += -1 + variableAllocations[n].GetSizeOnStackDWords();
  2871. if( varOffset == offset )
  2872. return n;
  2873. varOffset++;
  2874. }
  2875. return -1;
  2876. }
  2877. bool asCCompiler::IsVariableOnHeap(int offset)
  2878. {
  2879. int varSlot = GetVariableSlot(offset);
  2880. if( varSlot < 0 )
  2881. {
  2882. // This happens for function arguments that are considered as on the heap
  2883. return true;
  2884. }
  2885. return variableIsOnHeap[varSlot];
  2886. }
  2887. void asCCompiler::DeallocateVariable(int offset)
  2888. {
  2889. // Remove temporary variable
  2890. int n;
  2891. for( n = 0; n < (int)tempVariables.GetLength(); n++ )
  2892. {
  2893. if( offset == tempVariables[n] )
  2894. {
  2895. if( n == (int)tempVariables.GetLength()-1 )
  2896. tempVariables.PopLast();
  2897. else
  2898. tempVariables[n] = tempVariables.PopLast();
  2899. break;
  2900. }
  2901. }
  2902. n = GetVariableSlot(offset);
  2903. if( n != -1 )
  2904. {
  2905. freeVariables.PushLast(n);
  2906. return;
  2907. }
  2908. // We might get here if the variable was implicitly declared
  2909. // because it was use before a formal declaration, in this case
  2910. // the offset is 0x7FFF
  2911. asASSERT(offset == 0x7FFF);
  2912. }
  2913. void asCCompiler::ReleaseTemporaryVariable(asCTypeInfo &t, asCByteCode *bc)
  2914. {
  2915. if( t.isTemporary )
  2916. {
  2917. ReleaseTemporaryVariable(t.stackOffset, bc);
  2918. t.isTemporary = false;
  2919. }
  2920. }
  2921. void asCCompiler::ReleaseTemporaryVariable(int offset, asCByteCode *bc)
  2922. {
  2923. if( bc )
  2924. {
  2925. // We need to call the destructor on the true variable type
  2926. int n = GetVariableSlot(offset);
  2927. asASSERT( n >= 0 );
  2928. if( n >= 0 )
  2929. {
  2930. asCDataType dt = variableAllocations[n];
  2931. bool isOnHeap = variableIsOnHeap[n];
  2932. // Call destructor
  2933. CallDestructor(dt, offset, isOnHeap, bc);
  2934. }
  2935. }
  2936. DeallocateVariable(offset);
  2937. }
  2938. void asCCompiler::Dereference(asSExprContext *ctx, bool generateCode)
  2939. {
  2940. if( ctx->type.dataType.IsReference() )
  2941. {
  2942. if( ctx->type.dataType.IsObject() )
  2943. {
  2944. ctx->type.dataType.MakeReference(false);
  2945. if( generateCode )
  2946. {
  2947. ctx->bc.Instr(asBC_CHKREF);
  2948. ctx->bc.Instr(asBC_RDSPTR);
  2949. }
  2950. }
  2951. else
  2952. {
  2953. // This should never happen as primitives are treated differently
  2954. asASSERT(false);
  2955. }
  2956. }
  2957. }
  2958. bool asCCompiler::IsVariableInitialized(asCTypeInfo *type, asCScriptNode *node)
  2959. {
  2960. // Temporary variables are assumed to be initialized
  2961. if( type->isTemporary ) return true;
  2962. // Verify that it is a variable
  2963. if( !type->isVariable ) return true;
  2964. // Find the variable
  2965. sVariable *v = variables->GetVariableByOffset(type->stackOffset);
  2966. // The variable isn't found if it is a constant, in which case it is guaranteed to be initialized
  2967. if( v == 0 ) return true;
  2968. if( v->isInitialized ) return true;
  2969. // Complex types don't need this test
  2970. if( v->type.IsObject() ) return true;
  2971. // Mark as initialized so that the user will not be bothered again
  2972. v->isInitialized = true;
  2973. // Write warning
  2974. asCString str;
  2975. str.Format(TXT_s_NOT_INITIALIZED, (const char *)v->name.AddressOf());
  2976. Warning(str.AddressOf(), node);
  2977. return false;
  2978. }
  2979. void asCCompiler::PrepareOperand(asSExprContext *ctx, asCScriptNode *node)
  2980. {
  2981. // Check if the variable is initialized (if it indeed is a variable)
  2982. IsVariableInitialized(&ctx->type, node);
  2983. asCDataType to = ctx->type.dataType;
  2984. to.MakeReference(false);
  2985. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  2986. ProcessDeferredParams(ctx);
  2987. }
  2988. void asCCompiler::PrepareForAssignment(asCDataType *lvalue, asSExprContext *rctx, asCScriptNode *node, bool toTemporary, asSExprContext *lvalueExpr)
  2989. {
  2990. ProcessPropertyGetAccessor(rctx, node);
  2991. // Make sure the rvalue is initialized if it is a variable
  2992. IsVariableInitialized(&rctx->type, node);
  2993. if( lvalue->IsPrimitive() )
  2994. {
  2995. if( rctx->type.dataType.IsPrimitive() )
  2996. {
  2997. if( rctx->type.dataType.IsReference() )
  2998. {
  2999. // Cannot do implicit conversion of references so we first convert the reference to a variable
  3000. ConvertToVariableNotIn(rctx, lvalueExpr);
  3001. }
  3002. }
  3003. // Implicitly convert the value to the right type
  3004. asCArray<int> usedVars;
  3005. if( lvalueExpr ) lvalueExpr->bc.GetVarsUsed(usedVars);
  3006. ImplicitConversion(rctx, *lvalue, node, asIC_IMPLICIT_CONV, true, &usedVars);
  3007. // Check data type
  3008. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  3009. {
  3010. asCString str;
  3011. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  3012. Error(str.AddressOf(), node);
  3013. rctx->type.SetDummy();
  3014. }
  3015. // Make sure the rvalue is a variable
  3016. if( !rctx->type.isVariable )
  3017. ConvertToVariableNotIn(rctx, lvalueExpr);
  3018. }
  3019. else
  3020. {
  3021. asCDataType to = *lvalue;
  3022. to.MakeReference(false);
  3023. // TODO: ImplicitConversion should know to do this by itself
  3024. // First convert to a handle which will do a reference cast
  3025. if( !lvalue->IsObjectHandle() &&
  3026. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  3027. to.MakeHandle(true);
  3028. // Don't allow the implicit conversion to create an object
  3029. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, 0, !toTemporary);
  3030. if( !lvalue->IsObjectHandle() &&
  3031. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  3032. {
  3033. // Then convert to a reference, which will validate the handle
  3034. to.MakeHandle(false);
  3035. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, 0, !toTemporary);
  3036. }
  3037. // Check data type
  3038. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  3039. {
  3040. asCString str;
  3041. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  3042. Error(str.AddressOf(), node);
  3043. }
  3044. else
  3045. {
  3046. // If the assignment will be made with the copy behaviour then the rvalue must not be a reference
  3047. if( lvalue->IsObject() )
  3048. asASSERT(!rctx->type.dataType.IsReference());
  3049. }
  3050. }
  3051. }
  3052. bool asCCompiler::IsLValue(asCTypeInfo &type)
  3053. {
  3054. if( !type.isLValue ) return false;
  3055. if( type.dataType.IsReadOnly() ) return false;
  3056. if( !type.dataType.IsObject() && !type.isVariable && !type.dataType.IsReference() ) return false;
  3057. return true;
  3058. }
  3059. void asCCompiler::PerformAssignment(asCTypeInfo *lvalue, asCTypeInfo *rvalue, asCByteCode *bc, asCScriptNode *node)
  3060. {
  3061. if( lvalue->dataType.IsReadOnly() )
  3062. Error(TXT_REF_IS_READ_ONLY, node);
  3063. if( lvalue->dataType.IsPrimitive() )
  3064. {
  3065. if( lvalue->isVariable )
  3066. {
  3067. // Copy the value between the variables directly
  3068. if( lvalue->dataType.GetSizeInMemoryDWords() == 1 )
  3069. bc->InstrW_W(asBC_CpyVtoV4, lvalue->stackOffset, rvalue->stackOffset);
  3070. else
  3071. bc->InstrW_W(asBC_CpyVtoV8, lvalue->stackOffset, rvalue->stackOffset);
  3072. // Mark variable as initialized
  3073. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3074. if( v ) v->isInitialized = true;
  3075. }
  3076. else if( lvalue->dataType.IsReference() )
  3077. {
  3078. // Copy the value of the variable to the reference in the register
  3079. int s = lvalue->dataType.GetSizeInMemoryBytes();
  3080. if( s == 1 )
  3081. bc->InstrSHORT(asBC_WRTV1, rvalue->stackOffset);
  3082. else if( s == 2 )
  3083. bc->InstrSHORT(asBC_WRTV2, rvalue->stackOffset);
  3084. else if( s == 4 )
  3085. bc->InstrSHORT(asBC_WRTV4, rvalue->stackOffset);
  3086. else if( s == 8 )
  3087. bc->InstrSHORT(asBC_WRTV8, rvalue->stackOffset);
  3088. }
  3089. else
  3090. {
  3091. Error(TXT_NOT_VALID_LVALUE, node);
  3092. return;
  3093. }
  3094. }
  3095. else if( !lvalue->isExplicitHandle )
  3096. {
  3097. asSExprContext ctx(engine);
  3098. ctx.type = *lvalue;
  3099. Dereference(&ctx, true);
  3100. *lvalue = ctx.type;
  3101. bc->AddCode(&ctx.bc);
  3102. // TODO: Can't this leave deferred output params unhandled?
  3103. // TODO: Should find the opAssign method that implements the default copy behaviour.
  3104. // The beh->copy member will be removed.
  3105. asSTypeBehaviour *beh = lvalue->dataType.GetBehaviour();
  3106. if( beh->copy )
  3107. {
  3108. // Call the copy operator
  3109. bc->Call(asBC_CALLSYS, (asDWORD)beh->copy, 2*AS_PTR_SIZE);
  3110. bc->Instr(asBC_PshRPtr);
  3111. }
  3112. else
  3113. {
  3114. // Default copy operator
  3115. if( lvalue->dataType.GetSizeInMemoryDWords() == 0 ||
  3116. !(lvalue->dataType.GetObjectType()->flags & asOBJ_POD) )
  3117. {
  3118. asCString msg;
  3119. msg.Format(TXT_NO_DEFAULT_COPY_OP_FOR_s, lvalue->dataType.GetObjectType()->name.AddressOf());
  3120. Error(msg.AddressOf(), node);
  3121. }
  3122. // Copy larger data types from a reference
  3123. bc->InstrSHORT_DW(asBC_COPY, (short)lvalue->dataType.GetSizeInMemoryDWords(), engine->GetTypeIdFromDataType(lvalue->dataType));
  3124. }
  3125. }
  3126. else
  3127. {
  3128. // TODO: The object handle can be stored in a variable as well
  3129. if( !lvalue->dataType.IsReference() )
  3130. {
  3131. Error(TXT_NOT_VALID_REFERENCE, node);
  3132. return;
  3133. }
  3134. // TODO: optimize: Convert to register based
  3135. bc->InstrPTR(asBC_REFCPY, lvalue->dataType.GetObjectType());
  3136. // Mark variable as initialized
  3137. if( variables )
  3138. {
  3139. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3140. if( v ) v->isInitialized = true;
  3141. }
  3142. }
  3143. }
  3144. bool asCCompiler::CompileRefCast(asSExprContext *ctx, const asCDataType &to, bool isExplicit, asCScriptNode *node, bool generateCode)
  3145. {
  3146. bool conversionDone = false;
  3147. asCArray<int> ops;
  3148. asUINT n;
  3149. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT )
  3150. {
  3151. // We need it to be a reference
  3152. if( !ctx->type.dataType.IsReference() )
  3153. {
  3154. asCDataType to = ctx->type.dataType;
  3155. to.MakeReference(true);
  3156. ImplicitConversion(ctx, to, 0, isExplicit ? asIC_EXPLICIT_REF_CAST : asIC_IMPLICIT_CONV, generateCode);
  3157. }
  3158. if( isExplicit )
  3159. {
  3160. // Allow dynamic cast between object handles (only for script objects).
  3161. // At run time this may result in a null handle,
  3162. // which when used will throw an exception
  3163. conversionDone = true;
  3164. if( generateCode )
  3165. {
  3166. ctx->bc.InstrDWORD(asBC_Cast, engine->GetTypeIdFromDataType(to));
  3167. // Allocate a temporary variable for the returned object
  3168. int returnOffset = AllocateVariable(to, true);
  3169. // Move the pointer from the object register to the temporary variable
  3170. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  3171. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  3172. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3173. ctx->type.SetVariable(to, returnOffset, true);
  3174. ctx->type.dataType.MakeReference(true);
  3175. }
  3176. else
  3177. {
  3178. ctx->type.dataType = to;
  3179. ctx->type.dataType.MakeReference(true);
  3180. }
  3181. }
  3182. else
  3183. {
  3184. if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3185. {
  3186. conversionDone = true;
  3187. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3188. }
  3189. }
  3190. }
  3191. else
  3192. {
  3193. // Find a suitable registered behaviour
  3194. asSTypeBehaviour *beh = &ctx->type.dataType.GetObjectType()->beh;
  3195. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3196. {
  3197. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3198. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3199. {
  3200. int funcId = beh->operators[n+1];
  3201. // Is the operator for the output type?
  3202. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3203. if( func->returnType.GetObjectType() != to.GetObjectType() )
  3204. continue;
  3205. ops.PushLast(funcId);
  3206. }
  3207. }
  3208. // It shouldn't be possible to have more than one
  3209. asASSERT( ops.GetLength() <= 1 );
  3210. // Should only have one behaviour for each output type
  3211. if( ops.GetLength() == 1 )
  3212. {
  3213. if( generateCode )
  3214. {
  3215. // TODO: optimize: Instead of producing bytecode for checking if the handle is
  3216. // null, we can create a special CALLSYS instruction that checks
  3217. // if the object pointer is null and if so sets the object register
  3218. // to null directly without executing the function.
  3219. //
  3220. // Alternatively I could force the ref cast behaviours be global
  3221. // functions with 1 parameter, even though they should still be
  3222. // registered with RegisterObjectBehaviour()
  3223. // Add code to avoid calling the cast behaviour if the handle is already null,
  3224. // because that will raise a null pointer exception due to the cast behaviour
  3225. // being a class method, and the this pointer cannot be null.
  3226. if( ctx->type.isVariable )
  3227. ctx->bc.Pop(AS_PTR_SIZE);
  3228. else
  3229. {
  3230. Dereference(ctx, true);
  3231. ConvertToVariable(ctx);
  3232. }
  3233. #ifdef AS_64BIT_PTR
  3234. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttUInt64, false), true);
  3235. ctx->bc.InstrW_QW(asBC_SetV8, (asWORD)offset, 0);
  3236. ctx->bc.InstrW_W(asBC_CMPi64, ctx->type.stackOffset, offset);
  3237. DeallocateVariable(offset);
  3238. #else
  3239. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttUInt, false), true);
  3240. ctx->bc.InstrW_DW(asBC_SetV4, (asWORD)offset, 0);
  3241. ctx->bc.InstrW_W(asBC_CMPi, ctx->type.stackOffset, offset);
  3242. DeallocateVariable(offset);
  3243. #endif
  3244. int afterLabel = nextLabel++;
  3245. ctx->bc.InstrDWORD(asBC_JZ, afterLabel);
  3246. // Call the cast operator
  3247. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3248. ctx->bc.Instr(asBC_RDSPTR);
  3249. ctx->type.dataType.MakeReference(false);
  3250. asCTypeInfo objType = ctx->type;
  3251. asCArray<asSExprContext *> args;
  3252. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  3253. ctx->bc.Pop(AS_PTR_SIZE);
  3254. int endLabel = nextLabel++;
  3255. ctx->bc.InstrINT(asBC_JMP, endLabel);
  3256. ctx->bc.Label((short)afterLabel);
  3257. // Make a NULL pointer
  3258. #ifdef AS_64BIT_PTR
  3259. ctx->bc.InstrW_QW(asBC_SetV8, ctx->type.stackOffset, 0);
  3260. #else
  3261. ctx->bc.InstrW_DW(asBC_SetV4, ctx->type.stackOffset, 0);
  3262. #endif
  3263. ctx->bc.Label((short)endLabel);
  3264. // Since we're receiving a handle, we can release the original variable
  3265. ReleaseTemporaryVariable(objType, &ctx->bc);
  3266. // Push the reference to the handle on the stack
  3267. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3268. }
  3269. else
  3270. {
  3271. asCScriptFunction *func = engine->scriptFunctions[ops[0]];
  3272. ctx->type.Set(func->returnType);
  3273. }
  3274. }
  3275. else if( ops.GetLength() == 0 )
  3276. {
  3277. // Check for the generic ref cast behaviour
  3278. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3279. {
  3280. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3281. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3282. {
  3283. int funcId = beh->operators[n+1];
  3284. // Does the operator take the ?&out parameter?
  3285. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3286. if( func->parameterTypes.GetLength() != 1 ||
  3287. func->parameterTypes[0].GetTokenType() != ttQuestion ||
  3288. func->inOutFlags[0] != asTM_OUTREF )
  3289. continue;
  3290. ops.PushLast(funcId);
  3291. }
  3292. }
  3293. // It shouldn't be possible to have more than one
  3294. asASSERT( ops.GetLength() <= 1 );
  3295. if( ops.GetLength() == 1 )
  3296. {
  3297. if( generateCode )
  3298. {
  3299. asASSERT(to.IsObjectHandle());
  3300. // Allocate a temporary variable of the requested handle type
  3301. asCArray<int> vars;
  3302. ctx->bc.GetVarsUsed(vars);
  3303. int stackOffset = AllocateVariableNotIn(to, true, &vars);
  3304. // Pass the reference of that variable to the function as output parameter
  3305. asCDataType toRef(to);
  3306. toRef.MakeReference(true);
  3307. asCArray<asSExprContext *> args;
  3308. asSExprContext arg(engine);
  3309. arg.bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3310. // Don't mark the variable as temporary, so it won't be freed too early
  3311. arg.type.SetVariable(toRef, stackOffset, false);
  3312. arg.type.isLValue = true;
  3313. arg.type.isExplicitHandle = true;
  3314. args.PushLast(&arg);
  3315. // Call the behaviour method
  3316. MakeFunctionCall(ctx, ops[0], ctx->type.dataType.GetObjectType(), args, node);
  3317. // Use the reference to the variable as the result of the expression
  3318. // Now we can mark the variable as temporary
  3319. ctx->type.SetVariable(toRef, stackOffset, true);
  3320. ctx->bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3321. }
  3322. else
  3323. {
  3324. // All casts are legal
  3325. ctx->type.Set(to);
  3326. }
  3327. }
  3328. }
  3329. }
  3330. return conversionDone;
  3331. }
  3332. void asCCompiler::ImplicitConvPrimitiveToPrimitive(asSExprContext *ctx, const asCDataType &toOrig, asCScriptNode *node, EImplicitConv convType, bool generateCode, asCArray<int> *reservedVars)
  3333. {
  3334. asCDataType to = toOrig;
  3335. to.MakeReference(false);
  3336. asASSERT( !ctx->type.dataType.IsReference() );
  3337. // Start by implicitly converting constant values
  3338. if( ctx->type.isConstant )
  3339. ImplicitConversionConstant(ctx, to, node, convType);
  3340. // A primitive is const or not
  3341. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3342. if( to == ctx->type.dataType )
  3343. return;
  3344. // Allow implicit conversion between numbers
  3345. if( generateCode )
  3346. {
  3347. // Convert smaller types to 32bit first
  3348. int s = ctx->type.dataType.GetSizeInMemoryBytes();
  3349. if( s < 4 )
  3350. {
  3351. ConvertToTempVariableNotIn(ctx, reservedVars);
  3352. if( ctx->type.dataType.IsIntegerType() )
  3353. {
  3354. if( s == 1 )
  3355. ctx->bc.InstrSHORT(asBC_sbTOi, ctx->type.stackOffset);
  3356. else if( s == 2 )
  3357. ctx->bc.InstrSHORT(asBC_swTOi, ctx->type.stackOffset);
  3358. ctx->type.dataType.SetTokenType(ttInt);
  3359. }
  3360. else if( ctx->type.dataType.IsUnsignedType() )
  3361. {
  3362. if( s == 1 )
  3363. ctx->bc.InstrSHORT(asBC_ubTOi, ctx->type.stackOffset);
  3364. else if( s == 2 )
  3365. ctx->bc.InstrSHORT(asBC_uwTOi, ctx->type.stackOffset);
  3366. ctx->type.dataType.SetTokenType(ttUInt);
  3367. }
  3368. }
  3369. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1) ||
  3370. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  3371. {
  3372. if( ctx->type.dataType.IsIntegerType() ||
  3373. ctx->type.dataType.IsUnsignedType() ||
  3374. ctx->type.dataType.IsEnumType() )
  3375. {
  3376. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3377. {
  3378. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3379. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3380. }
  3381. else
  3382. {
  3383. ConvertToTempVariableNotIn(ctx, reservedVars);
  3384. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3385. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3386. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3387. ctx->type.SetVariable(to, offset, true);
  3388. }
  3389. }
  3390. else if( ctx->type.dataType.IsFloatType() )
  3391. {
  3392. ConvertToTempVariableNotIn(ctx, reservedVars);
  3393. ctx->bc.InstrSHORT(asBC_fTOi, ctx->type.stackOffset);
  3394. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3395. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3396. }
  3397. else if( ctx->type.dataType.IsDoubleType() )
  3398. {
  3399. ConvertToTempVariableNotIn(ctx, reservedVars);
  3400. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3401. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3402. ctx->bc.InstrW_W(asBC_dTOi, offset, ctx->type.stackOffset);
  3403. ctx->type.SetVariable(to, offset, true);
  3404. }
  3405. // Convert to smaller integer if necessary
  3406. int s = to.GetSizeInMemoryBytes();
  3407. if( s < 4 )
  3408. {
  3409. ConvertToTempVariableNotIn(ctx, reservedVars);
  3410. if( s == 1 )
  3411. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3412. else if( s == 2 )
  3413. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3414. }
  3415. }
  3416. if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  3417. {
  3418. if( ctx->type.dataType.IsIntegerType() ||
  3419. ctx->type.dataType.IsUnsignedType() ||
  3420. ctx->type.dataType.IsEnumType() )
  3421. {
  3422. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3423. {
  3424. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3425. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3426. }
  3427. else
  3428. {
  3429. ConvertToTempVariableNotIn(ctx, reservedVars);
  3430. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3431. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3432. if( ctx->type.dataType.IsUnsignedType() )
  3433. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3434. else
  3435. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3436. ctx->type.SetVariable(to, offset, true);
  3437. }
  3438. }
  3439. else if( ctx->type.dataType.IsFloatType() )
  3440. {
  3441. ConvertToTempVariableNotIn(ctx, reservedVars);
  3442. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3443. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3444. ctx->bc.InstrW_W(asBC_fTOi64, offset, ctx->type.stackOffset);
  3445. ctx->type.SetVariable(to, offset, true);
  3446. }
  3447. else if( ctx->type.dataType.IsDoubleType() )
  3448. {
  3449. ConvertToTempVariableNotIn(ctx, reservedVars);
  3450. ctx->bc.InstrSHORT(asBC_dTOi64, ctx->type.stackOffset);
  3451. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3452. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3453. }
  3454. }
  3455. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  3456. {
  3457. if( ctx->type.dataType.IsIntegerType() ||
  3458. ctx->type.dataType.IsUnsignedType() ||
  3459. ctx->type.dataType.IsEnumType() )
  3460. {
  3461. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3462. {
  3463. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3464. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3465. }
  3466. else
  3467. {
  3468. ConvertToTempVariableNotIn(ctx, reservedVars);
  3469. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3470. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3471. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3472. ctx->type.SetVariable(to, offset, true);
  3473. }
  3474. }
  3475. else if( ctx->type.dataType.IsFloatType() )
  3476. {
  3477. ConvertToTempVariableNotIn(ctx, reservedVars);
  3478. ctx->bc.InstrSHORT(asBC_fTOu, ctx->type.stackOffset);
  3479. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3480. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3481. }
  3482. else if( ctx->type.dataType.IsDoubleType() )
  3483. {
  3484. ConvertToTempVariableNotIn(ctx, reservedVars);
  3485. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3486. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3487. ctx->bc.InstrW_W(asBC_dTOu, offset, ctx->type.stackOffset);
  3488. ctx->type.SetVariable(to, offset, true);
  3489. }
  3490. // Convert to smaller integer if necessary
  3491. int s = to.GetSizeInMemoryBytes();
  3492. if( s < 4 )
  3493. {
  3494. ConvertToTempVariableNotIn(ctx, reservedVars);
  3495. if( s == 1 )
  3496. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3497. else if( s == 2 )
  3498. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3499. }
  3500. }
  3501. if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  3502. {
  3503. if( ctx->type.dataType.IsIntegerType() ||
  3504. ctx->type.dataType.IsUnsignedType() ||
  3505. ctx->type.dataType.IsEnumType() )
  3506. {
  3507. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3508. {
  3509. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3510. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3511. }
  3512. else
  3513. {
  3514. ConvertToTempVariableNotIn(ctx, reservedVars);
  3515. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3516. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3517. if( ctx->type.dataType.IsUnsignedType() )
  3518. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3519. else
  3520. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3521. ctx->type.SetVariable(to, offset, true);
  3522. }
  3523. }
  3524. else if( ctx->type.dataType.IsFloatType() )
  3525. {
  3526. ConvertToTempVariableNotIn(ctx, reservedVars);
  3527. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3528. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3529. ctx->bc.InstrW_W(asBC_fTOu64, offset, ctx->type.stackOffset);
  3530. ctx->type.SetVariable(to, offset, true);
  3531. }
  3532. else if( ctx->type.dataType.IsDoubleType() )
  3533. {
  3534. ConvertToTempVariableNotIn(ctx, reservedVars);
  3535. ctx->bc.InstrSHORT(asBC_dTOu64, ctx->type.stackOffset);
  3536. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3537. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3538. }
  3539. }
  3540. else if( to.IsFloatType() )
  3541. {
  3542. if( (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType()) && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3543. {
  3544. ConvertToTempVariableNotIn(ctx, reservedVars);
  3545. ctx->bc.InstrSHORT(asBC_iTOf, ctx->type.stackOffset);
  3546. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3547. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3548. }
  3549. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3550. {
  3551. ConvertToTempVariableNotIn(ctx, reservedVars);
  3552. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3553. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3554. ctx->bc.InstrW_W(asBC_i64TOf, offset, ctx->type.stackOffset);
  3555. ctx->type.SetVariable(to, offset, true);
  3556. }
  3557. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3558. {
  3559. ConvertToTempVariableNotIn(ctx, reservedVars);
  3560. ctx->bc.InstrSHORT(asBC_uTOf, ctx->type.stackOffset);
  3561. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3562. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3563. }
  3564. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3565. {
  3566. ConvertToTempVariableNotIn(ctx, reservedVars);
  3567. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3568. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3569. ctx->bc.InstrW_W(asBC_u64TOf, offset, ctx->type.stackOffset);
  3570. ctx->type.SetVariable(to, offset, true);
  3571. }
  3572. else if( ctx->type.dataType.IsDoubleType() )
  3573. {
  3574. ConvertToTempVariableNotIn(ctx, reservedVars);
  3575. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3576. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3577. ctx->bc.InstrW_W(asBC_dTOf, offset, ctx->type.stackOffset);
  3578. ctx->type.SetVariable(to, offset, true);
  3579. }
  3580. }
  3581. else if( to.IsDoubleType() )
  3582. {
  3583. if( (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType()) && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3584. {
  3585. ConvertToTempVariableNotIn(ctx, reservedVars);
  3586. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3587. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3588. ctx->bc.InstrW_W(asBC_iTOd, offset, ctx->type.stackOffset);
  3589. ctx->type.SetVariable(to, offset, true);
  3590. }
  3591. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3592. {
  3593. ConvertToTempVariableNotIn(ctx, reservedVars);
  3594. ctx->bc.InstrSHORT(asBC_i64TOd, ctx->type.stackOffset);
  3595. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3596. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3597. }
  3598. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3599. {
  3600. ConvertToTempVariableNotIn(ctx, reservedVars);
  3601. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3602. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3603. ctx->bc.InstrW_W(asBC_uTOd, offset, ctx->type.stackOffset);
  3604. ctx->type.SetVariable(to, offset, true);
  3605. }
  3606. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3607. {
  3608. ConvertToTempVariableNotIn(ctx, reservedVars);
  3609. ctx->bc.InstrSHORT(asBC_u64TOd, ctx->type.stackOffset);
  3610. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3611. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3612. }
  3613. else if( ctx->type.dataType.IsFloatType() )
  3614. {
  3615. ConvertToTempVariableNotIn(ctx, reservedVars);
  3616. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3617. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3618. ctx->bc.InstrW_W(asBC_fTOd, offset, ctx->type.stackOffset);
  3619. ctx->type.SetVariable(to, offset, true);
  3620. }
  3621. }
  3622. }
  3623. else
  3624. {
  3625. if( (to.IsIntegerType() || to.IsUnsignedType() ||
  3626. to.IsFloatType() || to.IsDoubleType() ||
  3627. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST)) &&
  3628. (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() ||
  3629. ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType() ||
  3630. ctx->type.dataType.IsEnumType()) )
  3631. {
  3632. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3633. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3634. }
  3635. }
  3636. // Primitive types on the stack, can be const or non-const
  3637. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3638. }
  3639. void asCCompiler::ImplicitConversion(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, asCArray<int> *reservedVars, bool allowObjectConstruct)
  3640. {
  3641. asASSERT( ctx->type.dataType.GetTokenType() != ttUnrecognizedToken ||
  3642. ctx->type.dataType.IsNullHandle() );
  3643. // No conversion from void to any other type
  3644. if( ctx->type.dataType.GetTokenType() == ttVoid )
  3645. return;
  3646. // Do we want a var type?
  3647. if( to.GetTokenType() == ttQuestion )
  3648. {
  3649. // Any type can be converted to a var type, but only when not generating code
  3650. asASSERT( !generateCode );
  3651. ctx->type.dataType = to;
  3652. return;
  3653. }
  3654. // Do we want a primitive?
  3655. else if( to.IsPrimitive() )
  3656. {
  3657. if( !ctx->type.dataType.IsPrimitive() )
  3658. ImplicitConvObjectToPrimitive(ctx, to, node, convType, generateCode, reservedVars);
  3659. else
  3660. ImplicitConvPrimitiveToPrimitive(ctx, to, node, convType, generateCode, reservedVars);
  3661. }
  3662. else // The target is a complex type
  3663. {
  3664. if( ctx->type.dataType.IsPrimitive() )
  3665. ImplicitConvPrimitiveToObject(ctx, to, node, convType, generateCode, reservedVars, allowObjectConstruct);
  3666. else if( ctx->type.IsNullConstant() || ctx->type.dataType.GetObjectType() )
  3667. ImplicitConvObjectToObject(ctx, to, node, convType, generateCode, reservedVars, allowObjectConstruct);
  3668. }
  3669. }
  3670. void asCCompiler::ImplicitConvObjectToPrimitive(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, asCArray<int> *reservedVars)
  3671. {
  3672. if( ctx->type.isExplicitHandle )
  3673. {
  3674. // An explicit handle cannot be converted to a primitive
  3675. if( convType != asIC_IMPLICIT_CONV && node )
  3676. {
  3677. asCString str;
  3678. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3679. Error(str.AddressOf(), node);
  3680. }
  3681. return;
  3682. }
  3683. // TODO: Must use the const cast behaviour if the object is read-only
  3684. // Find matching value cast behaviours
  3685. // Here we're only interested in those that convert the type to a primitive type
  3686. asCArray<int> funcs;
  3687. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  3688. if( beh )
  3689. {
  3690. if( convType == asIC_EXPLICIT_VAL_CAST )
  3691. {
  3692. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3693. {
  3694. // accept both implicit and explicit cast
  3695. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  3696. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  3697. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  3698. funcs.PushLast(beh->operators[n+1]);
  3699. }
  3700. }
  3701. else
  3702. {
  3703. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3704. {
  3705. // accept only implicit cast
  3706. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  3707. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  3708. funcs.PushLast(beh->operators[n+1]);
  3709. }
  3710. }
  3711. }
  3712. // This matrix describes the priorities of the types to search for, for each target type
  3713. // The first column is the target type, the priorities goes from left to right
  3714. eTokenType matchMtx[10][10] =
  3715. {
  3716. {ttDouble, ttFloat, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  3717. {ttFloat, ttDouble, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  3718. {ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  3719. {ttUInt64, ttInt64, ttUInt, ttInt, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  3720. {ttInt, ttUInt, ttInt64, ttUInt64, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  3721. {ttUInt, ttInt, ttUInt64, ttInt64, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  3722. {ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttInt8, ttUInt8, ttDouble, ttFloat},
  3723. {ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttUInt8, ttInt8, ttDouble, ttFloat},
  3724. {ttInt8, ttUInt8, ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttDouble, ttFloat},
  3725. {ttUInt8, ttInt8, ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttDouble, ttFloat},
  3726. };
  3727. // Which row to use?
  3728. eTokenType *row = 0;
  3729. for( unsigned int type = 0; type < 10; type++ )
  3730. {
  3731. if( to.GetTokenType() == matchMtx[type][0] )
  3732. {
  3733. row = &matchMtx[type][0];
  3734. break;
  3735. }
  3736. }
  3737. // Find the best matching cast operator
  3738. int funcId = 0;
  3739. if( row )
  3740. {
  3741. asCDataType target(to);
  3742. // Priority goes from left to right in the matrix
  3743. for( unsigned int attempt = 0; attempt < 10 && funcId == 0; attempt++ )
  3744. {
  3745. target.SetTokenType(row[attempt]);
  3746. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  3747. {
  3748. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[n]);
  3749. if( descr->returnType.IsEqualExceptConst(target) )
  3750. {
  3751. funcId = funcs[n];
  3752. break;
  3753. }
  3754. }
  3755. }
  3756. }
  3757. // Did we find a suitable function?
  3758. if( funcId != 0 )
  3759. {
  3760. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  3761. if( generateCode )
  3762. {
  3763. asCTypeInfo objType = ctx->type;
  3764. Dereference(ctx, true);
  3765. PerformFunctionCall(funcId, ctx);
  3766. ReleaseTemporaryVariable(objType, &ctx->bc);
  3767. }
  3768. else
  3769. ctx->type.Set(descr->returnType);
  3770. // Allow one more implicit conversion to another primitive type
  3771. ImplicitConversion(ctx, to, node, convType, generateCode, reservedVars, false);
  3772. }
  3773. else
  3774. {
  3775. if( convType != asIC_IMPLICIT_CONV && node )
  3776. {
  3777. asCString str;
  3778. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3779. Error(str.AddressOf(), node);
  3780. }
  3781. }
  3782. }
  3783. void asCCompiler::ImplicitConvObjectToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, asCArray<int> *reservedVars, bool allowObjectConstruct)
  3784. {
  3785. // Convert null to any object type handle, but not to a non-handle type
  3786. if( ctx->type.IsNullConstant() )
  3787. {
  3788. if( to.IsObjectHandle() )
  3789. ctx->type.dataType = to;
  3790. return;
  3791. }
  3792. asASSERT(ctx->type.dataType.GetObjectType());
  3793. // First attempt to convert the base type without instanciating another instance
  3794. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  3795. {
  3796. // If the to type is an interface and the from type implements it, then we can convert it immediately
  3797. if( ctx->type.dataType.GetObjectType()->Implements(to.GetObjectType()) )
  3798. {
  3799. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3800. }
  3801. // If the to type is a class and the from type derives from it, then we can convert it immediately
  3802. if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3803. {
  3804. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3805. }
  3806. // If the types are not equal yet, then we may still be able to find a reference cast
  3807. if( ctx->type.dataType.GetObjectType() != to.GetObjectType() )
  3808. {
  3809. // A ref cast must not remove the constness
  3810. bool isConst = false;
  3811. if( (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) ||
  3812. (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) )
  3813. isConst = true;
  3814. // We may still be able to find an implicit ref cast behaviour
  3815. CompileRefCast(ctx, to, convType == asIC_EXPLICIT_REF_CAST, node, generateCode);
  3816. ctx->type.dataType.MakeHandleToConst(isConst);
  3817. }
  3818. }
  3819. // If the base type is still different, and we are allowed to instance
  3820. // another object then we can try an implicit value cast
  3821. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  3822. {
  3823. // TODO: Implement support for implicit constructor/factory
  3824. asCArray<int> funcs;
  3825. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  3826. if( beh )
  3827. {
  3828. if( convType == asIC_EXPLICIT_VAL_CAST )
  3829. {
  3830. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3831. {
  3832. // accept both implicit and explicit cast
  3833. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  3834. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  3835. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  3836. funcs.PushLast(beh->operators[n+1]);
  3837. }
  3838. }
  3839. else
  3840. {
  3841. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3842. {
  3843. // accept only implicit cast
  3844. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  3845. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  3846. funcs.PushLast(beh->operators[n+1]);
  3847. }
  3848. }
  3849. }
  3850. // TODO: If there are multiple valid value casts, then we must choose the most appropriate one
  3851. asASSERT( funcs.GetLength() <= 1 );
  3852. if( funcs.GetLength() == 1 )
  3853. {
  3854. asCScriptFunction *f = builder->GetFunctionDescription(funcs[0]);
  3855. if( generateCode )
  3856. {
  3857. asCTypeInfo objType = ctx->type;
  3858. Dereference(ctx, true);
  3859. bool useVariable = false;
  3860. int stackOffset = 0;
  3861. #ifndef AS_OLD
  3862. if( f->DoesReturnOnStack() )
  3863. {
  3864. useVariable = true;
  3865. stackOffset = AllocateVariable(f->returnType, true);
  3866. // Push the pointer to the pre-allocated space for the return value
  3867. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  3868. // The object pointer is already on the stack, but should be the top
  3869. // one, so we need to swap the pointers in order to get the correct
  3870. #if AS_PTR_SIZE == 1
  3871. ctx->bc.Instr(asBC_SWAP4);
  3872. #else
  3873. ctx->bc.Instr(asBC_SWAP8);
  3874. #endif
  3875. }
  3876. #endif
  3877. PerformFunctionCall(funcs[0], ctx, false, 0, 0, useVariable, stackOffset);
  3878. ReleaseTemporaryVariable(objType, &ctx->bc);
  3879. }
  3880. else
  3881. ctx->type.Set(f->returnType);
  3882. }
  3883. }
  3884. // If we still haven't converted the base type to the correct type, then there is no need to continue
  3885. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  3886. return;
  3887. // Convert matching function types
  3888. if( to.GetFuncDef() && ctx->type.dataType.GetFuncDef() &&
  3889. to.GetFuncDef() != ctx->type.dataType.GetFuncDef() )
  3890. {
  3891. asCScriptFunction *toFunc = to.GetFuncDef();
  3892. asCScriptFunction *fromFunc = ctx->type.dataType.GetFuncDef();
  3893. if( toFunc->IsSignatureExceptNameEqual(fromFunc) )
  3894. {
  3895. ctx->type.dataType.SetFuncDef(toFunc);
  3896. }
  3897. }
  3898. if( to.IsObjectHandle() )
  3899. {
  3900. // reference to handle -> handle
  3901. // reference -> handle
  3902. // object -> handle
  3903. // handle -> reference to handle
  3904. // reference -> reference to handle
  3905. // object -> reference to handle
  3906. // TODO: If the type is handle, then we can't use IsReadOnly to determine the constness of the basetype
  3907. // If the rvalue is a handle to a const object, then
  3908. // the lvalue must also be a handle to a const object
  3909. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() )
  3910. {
  3911. if( convType != asIC_IMPLICIT_CONV )
  3912. {
  3913. asASSERT(node);
  3914. asCString str;
  3915. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3916. Error(str.AddressOf(), node);
  3917. }
  3918. }
  3919. if( !ctx->type.dataType.IsObjectHandle() )
  3920. {
  3921. // An object type can be directly converted to a handle of the same type
  3922. if( ctx->type.dataType.SupportHandles() )
  3923. {
  3924. ctx->type.dataType.MakeHandle(true);
  3925. }
  3926. if( ctx->type.dataType.IsObjectHandle() )
  3927. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3928. if( to.IsHandleToConst() && ctx->type.dataType.IsObjectHandle() )
  3929. ctx->type.dataType.MakeHandleToConst(true);
  3930. }
  3931. else
  3932. {
  3933. // A handle to non-const can be converted to a
  3934. // handle to const, but not the other way
  3935. if( to.IsHandleToConst() )
  3936. ctx->type.dataType.MakeHandleToConst(true);
  3937. // A const handle can be converted to a non-const
  3938. // handle and vice versa as the handle is just a value
  3939. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3940. }
  3941. if( to.IsReference() && !ctx->type.dataType.IsReference() )
  3942. {
  3943. if( generateCode )
  3944. {
  3945. // If the input type is a handle, then a simple ref copy is enough
  3946. bool isExplicitHandle = ctx->type.isExplicitHandle;
  3947. ctx->type.isExplicitHandle = ctx->type.dataType.IsObjectHandle();
  3948. // If the input type is read-only we'll need to temporarily
  3949. // remove this constness, otherwise the assignment will fail
  3950. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  3951. ctx->type.dataType.MakeReadOnly(false);
  3952. // If the object already is a temporary variable, then the copy
  3953. // doesn't have to be made as it is already a unique object
  3954. PrepareTemporaryObject(node, ctx, reservedVars);
  3955. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  3956. ctx->type.isExplicitHandle = isExplicitHandle;
  3957. }
  3958. // A non-reference can be converted to a reference,
  3959. // by putting the value in a temporary variable
  3960. ctx->type.dataType.MakeReference(true);
  3961. // Since it is a new temporary variable it doesn't have to be const
  3962. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3963. }
  3964. else if( !to.IsReference() && ctx->type.dataType.IsReference() )
  3965. {
  3966. // ASHANDLE is really a value type, even though it looks
  3967. // like a handle, so we shouldn't dereference it
  3968. if( !(ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) ||
  3969. (ctx->type.isVariable && IsVariableOnHeap(ctx->type.stackOffset)) )
  3970. Dereference(ctx, generateCode);
  3971. else
  3972. ctx->type.dataType.MakeReference(false);
  3973. }
  3974. }
  3975. else
  3976. {
  3977. if( !to.IsReference() )
  3978. {
  3979. // reference to handle -> object
  3980. // handle -> object
  3981. // reference -> object
  3982. // An implicit handle can be converted to an object by adding a check for null pointer
  3983. if( ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  3984. {
  3985. if( generateCode )
  3986. ctx->bc.Instr(asBC_CHKREF);
  3987. ctx->type.dataType.MakeHandle(false);
  3988. }
  3989. // A const object can be converted to a non-const object through a copy
  3990. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() &&
  3991. allowObjectConstruct )
  3992. {
  3993. // Does the object type allow a copy to be made?
  3994. if( ctx->type.dataType.CanBeCopied() )
  3995. {
  3996. if( generateCode )
  3997. {
  3998. // Make a temporary object with the copy
  3999. PrepareTemporaryObject(node, ctx, reservedVars);
  4000. }
  4001. // In case the object was already in a temporary variable, then the function
  4002. // didn't really do anything so we need to remove the constness here
  4003. ctx->type.dataType.MakeReadOnly(false);
  4004. }
  4005. }
  4006. if( ctx->type.dataType.IsReference() )
  4007. {
  4008. Dereference(ctx, generateCode);
  4009. // TODO: Can't this leave unhandled deferred output params?
  4010. }
  4011. // A non-const object can be converted to a const object directly
  4012. if( !ctx->type.dataType.IsReadOnly() && to.IsReadOnly() )
  4013. {
  4014. ctx->type.dataType.MakeReadOnly(true);
  4015. }
  4016. }
  4017. else
  4018. {
  4019. // reference to handle -> reference
  4020. // handle -> reference
  4021. // object -> reference
  4022. if( ctx->type.dataType.IsReference() )
  4023. {
  4024. if( ctx->type.isExplicitHandle && ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  4025. {
  4026. // ASHANDLE objects are really value types, so explicit handle can be removed
  4027. ctx->type.isExplicitHandle = false;
  4028. ctx->type.dataType.MakeHandle(false);
  4029. }
  4030. // A reference to a handle can be converted to a reference to an object
  4031. // by first reading the address, then verifying that it is not null
  4032. if( !to.IsObjectHandle() && ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  4033. {
  4034. ctx->type.dataType.MakeHandle(false);
  4035. if( generateCode )
  4036. ctx->bc.Instr(asBC_ChkRefS);
  4037. }
  4038. // A reference to a non-const can be converted to a reference to a const
  4039. if( to.IsReadOnly() )
  4040. ctx->type.dataType.MakeReadOnly(true);
  4041. else if( ctx->type.dataType.IsReadOnly() )
  4042. {
  4043. // A reference to a const can be converted to a reference to a
  4044. // non-const by copying the object to a temporary variable
  4045. ctx->type.dataType.MakeReadOnly(false);
  4046. if( generateCode )
  4047. {
  4048. // If the object already is a temporary variable, then the copy
  4049. // doesn't have to be made as it is already a unique object
  4050. PrepareTemporaryObject(node, ctx, reservedVars);
  4051. }
  4052. }
  4053. }
  4054. else
  4055. {
  4056. // A value type allocated on the stack is differentiated
  4057. // by it not being a reference. But it can be handled as
  4058. // reference by pushing the pointer on the stack
  4059. if( (ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) &&
  4060. (ctx->type.isVariable || ctx->type.isTemporary) &&
  4061. !IsVariableOnHeap(ctx->type.stackOffset) )
  4062. {
  4063. // Actually the pointer is already pushed on the stack in
  4064. // CompileVariableAccess, so we don't need to do anything else
  4065. }
  4066. else if( generateCode )
  4067. {
  4068. // A non-reference can be converted to a reference,
  4069. // by putting the value in a temporary variable
  4070. // If the input type is read-only we'll need to temporarily
  4071. // remove this constness, otherwise the assignment will fail
  4072. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  4073. ctx->type.dataType.MakeReadOnly(false);
  4074. // If the object already is a temporary variable, then the copy
  4075. // doesn't have to be made as it is already a unique object
  4076. PrepareTemporaryObject(node, ctx, reservedVars);
  4077. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  4078. }
  4079. // A handle can be converted to a reference, by checking for a null pointer
  4080. if( ctx->type.dataType.IsObjectHandle() )
  4081. {
  4082. if( generateCode )
  4083. ctx->bc.InstrSHORT(asBC_ChkNullV, ctx->type.stackOffset);
  4084. ctx->type.dataType.MakeHandle(false);
  4085. ctx->type.dataType.MakeReference(true);
  4086. // TODO: Make sure a handle to const isn't converted to non-const reference
  4087. }
  4088. else
  4089. {
  4090. // This may look strange as the conversion was to make the expression a reference
  4091. // but a value type allocated on the stack is a reference even without the type
  4092. // being marked as such.
  4093. ctx->type.dataType.MakeReference(IsVariableOnHeap(ctx->type.stackOffset));
  4094. }
  4095. // TODO: If the variable is an object allocated on the stack, this is not true
  4096. // Since it is a new temporary variable it doesn't have to be const
  4097. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4098. }
  4099. }
  4100. }
  4101. }
  4102. void asCCompiler::ImplicitConvPrimitiveToObject(asSExprContext * /*ctx*/, const asCDataType & /*to*/, asCScriptNode * /*node*/, EImplicitConv /*isExplicit*/, bool /*generateCode*/, asCArray<int> * /*reservedVars*/, bool /*allowObjectConstruct*/)
  4103. {
  4104. // TODO: This function should call the constructor/factory that has been marked as available
  4105. // for implicit conversions. The code will likely be similar to CallCopyConstructor()
  4106. }
  4107. void asCCompiler::ImplicitConversionConstant(asSExprContext *from, const asCDataType &to, asCScriptNode *node, EImplicitConv convType)
  4108. {
  4109. asASSERT(from->type.isConstant);
  4110. // TODO: node should be the node of the value that is
  4111. // converted (not the operator that provokes the implicit
  4112. // conversion)
  4113. // If the base type is correct there is no more to do
  4114. if( to.IsEqualExceptRefAndConst(from->type.dataType) ) return;
  4115. // References cannot be constants
  4116. if( from->type.dataType.IsReference() ) return;
  4117. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1) ||
  4118. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  4119. {
  4120. if( from->type.dataType.IsFloatType() ||
  4121. from->type.dataType.IsDoubleType() ||
  4122. from->type.dataType.IsUnsignedType() ||
  4123. from->type.dataType.IsIntegerType() ||
  4124. from->type.dataType.IsEnumType() )
  4125. {
  4126. // Transform the value
  4127. // Float constants can be implicitly converted to int
  4128. if( from->type.dataType.IsFloatType() )
  4129. {
  4130. float fc = from->type.floatValue;
  4131. int ic = int(fc);
  4132. if( float(ic) != fc )
  4133. {
  4134. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4135. }
  4136. from->type.intValue = ic;
  4137. }
  4138. // Double constants can be implicitly converted to int
  4139. else if( from->type.dataType.IsDoubleType() )
  4140. {
  4141. double fc = from->type.doubleValue;
  4142. int ic = int(fc);
  4143. if( double(ic) != fc )
  4144. {
  4145. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4146. }
  4147. from->type.intValue = ic;
  4148. }
  4149. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4150. {
  4151. // Verify that it is possible to convert to signed without getting negative
  4152. if( from->type.intValue < 0 )
  4153. {
  4154. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4155. }
  4156. // Convert to 32bit
  4157. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4158. from->type.intValue = from->type.byteValue;
  4159. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4160. from->type.intValue = from->type.wordValue;
  4161. }
  4162. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4163. {
  4164. // Convert to 32bit
  4165. from->type.intValue = int(from->type.qwordValue);
  4166. }
  4167. else if( from->type.dataType.IsIntegerType() &&
  4168. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4169. {
  4170. // Convert to 32bit
  4171. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4172. from->type.intValue = (signed char)from->type.byteValue;
  4173. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4174. from->type.intValue = (short)from->type.wordValue;
  4175. }
  4176. else if( from->type.dataType.IsEnumType() )
  4177. {
  4178. // Enum type is already an integer type
  4179. }
  4180. // Set the resulting type
  4181. if( to.IsEnumType() )
  4182. from->type.dataType = to;
  4183. else
  4184. from->type.dataType = asCDataType::CreatePrimitive(ttInt, true);
  4185. }
  4186. // Check if a downsize is necessary
  4187. if( to.IsIntegerType() &&
  4188. from->type.dataType.IsIntegerType() &&
  4189. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4190. {
  4191. // Verify if it is possible
  4192. if( to.GetSizeInMemoryBytes() == 1 )
  4193. {
  4194. if( char(from->type.intValue) != from->type.intValue )
  4195. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4196. from->type.byteValue = char(from->type.intValue);
  4197. }
  4198. else if( to.GetSizeInMemoryBytes() == 2 )
  4199. {
  4200. if( short(from->type.intValue) != from->type.intValue )
  4201. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4202. from->type.wordValue = short(from->type.intValue);
  4203. }
  4204. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4205. }
  4206. }
  4207. else if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  4208. {
  4209. // Float constants can be implicitly converted to int
  4210. if( from->type.dataType.IsFloatType() )
  4211. {
  4212. float fc = from->type.floatValue;
  4213. asINT64 ic = asINT64(fc);
  4214. if( float(ic) != fc )
  4215. {
  4216. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4217. }
  4218. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4219. from->type.qwordValue = ic;
  4220. }
  4221. // Double constants can be implicitly converted to int
  4222. else if( from->type.dataType.IsDoubleType() )
  4223. {
  4224. double fc = from->type.doubleValue;
  4225. asINT64 ic = asINT64(fc);
  4226. if( double(ic) != fc )
  4227. {
  4228. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4229. }
  4230. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4231. from->type.qwordValue = ic;
  4232. }
  4233. else if( from->type.dataType.IsUnsignedType() )
  4234. {
  4235. // Convert to 64bit
  4236. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4237. from->type.qwordValue = from->type.byteValue;
  4238. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4239. from->type.qwordValue = from->type.wordValue;
  4240. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4241. from->type.qwordValue = from->type.dwordValue;
  4242. else if( from->type.dataType.GetSizeInMemoryBytes() == 8 )
  4243. {
  4244. if( asINT64(from->type.qwordValue) < 0 )
  4245. {
  4246. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4247. }
  4248. }
  4249. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4250. }
  4251. else if( from->type.dataType.IsEnumType() )
  4252. {
  4253. from->type.qwordValue = from->type.intValue;
  4254. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4255. }
  4256. else if( from->type.dataType.IsIntegerType() )
  4257. {
  4258. // Convert to 64bit
  4259. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4260. from->type.qwordValue = (signed char)from->type.byteValue;
  4261. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4262. from->type.qwordValue = (short)from->type.wordValue;
  4263. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4264. from->type.qwordValue = from->type.intValue;
  4265. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4266. }
  4267. }
  4268. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  4269. {
  4270. if( from->type.dataType.IsFloatType() )
  4271. {
  4272. float fc = from->type.floatValue;
  4273. // Some compilers set the value to 0 when converting a negative float to unsigned int.
  4274. // To maintain a consistent behaviour across compilers we convert to int first.
  4275. asUINT uic = asUINT(int(fc));
  4276. if( float(uic) != fc )
  4277. {
  4278. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4279. }
  4280. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4281. from->type.intValue = uic;
  4282. // Try once more, in case of a smaller type
  4283. ImplicitConversionConstant(from, to, node, convType);
  4284. }
  4285. else if( from->type.dataType.IsDoubleType() )
  4286. {
  4287. double fc = from->type.doubleValue;
  4288. // Some compilers set the value to 0 when converting a negative double to unsigned int.
  4289. // To maintain a consistent behaviour across compilers we convert to int first.
  4290. asUINT uic = asUINT(int(fc));
  4291. if( double(uic) != fc )
  4292. {
  4293. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4294. }
  4295. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4296. from->type.intValue = uic;
  4297. // Try once more, in case of a smaller type
  4298. ImplicitConversionConstant(from, to, node, convType);
  4299. }
  4300. else if( from->type.dataType.IsEnumType() )
  4301. {
  4302. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4303. // Try once more, in case of a smaller type
  4304. ImplicitConversionConstant(from, to, node, convType);
  4305. }
  4306. else if( from->type.dataType.IsIntegerType() )
  4307. {
  4308. // Verify that it is possible to convert to unsigned without loosing negative
  4309. if( from->type.intValue < 0 )
  4310. {
  4311. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4312. }
  4313. // Convert to 32bit
  4314. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4315. from->type.intValue = (signed char)from->type.byteValue;
  4316. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4317. from->type.intValue = (short)from->type.wordValue;
  4318. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4319. // Try once more, in case of a smaller type
  4320. ImplicitConversionConstant(from, to, node, convType);
  4321. }
  4322. else if( from->type.dataType.IsUnsignedType() &&
  4323. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4324. {
  4325. // Convert to 32bit
  4326. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4327. from->type.dwordValue = from->type.byteValue;
  4328. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4329. from->type.dwordValue = from->type.wordValue;
  4330. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4331. // Try once more, in case of a smaller type
  4332. ImplicitConversionConstant(from, to, node, convType);
  4333. }
  4334. else if( from->type.dataType.IsUnsignedType() &&
  4335. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4336. {
  4337. // Verify if it is possible
  4338. if( to.GetSizeInMemoryBytes() == 1 )
  4339. {
  4340. if( asBYTE(from->type.dwordValue) != from->type.dwordValue )
  4341. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4342. from->type.byteValue = asBYTE(from->type.dwordValue);
  4343. }
  4344. else if( to.GetSizeInMemoryBytes() == 2 )
  4345. {
  4346. if( asWORD(from->type.dwordValue) != from->type.dwordValue )
  4347. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4348. from->type.wordValue = asWORD(from->type.dwordValue);
  4349. }
  4350. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4351. }
  4352. }
  4353. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  4354. {
  4355. if( from->type.dataType.IsFloatType() )
  4356. {
  4357. float fc = from->type.floatValue;
  4358. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  4359. asQWORD uic = asQWORD(asINT64(fc));
  4360. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  4361. // MSVC6 doesn't support this conversion
  4362. if( float(uic) != fc )
  4363. {
  4364. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4365. }
  4366. #endif
  4367. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4368. from->type.qwordValue = uic;
  4369. }
  4370. else if( from->type.dataType.IsDoubleType() )
  4371. {
  4372. double fc = from->type.doubleValue;
  4373. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  4374. asQWORD uic = asQWORD(asINT64(fc));
  4375. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  4376. // MSVC6 doesn't support this conversion
  4377. if( double(uic) != fc )
  4378. {
  4379. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4380. }
  4381. #endif
  4382. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4383. from->type.qwordValue = uic;
  4384. }
  4385. else if( from->type.dataType.IsEnumType() )
  4386. {
  4387. from->type.qwordValue = (asINT64)from->type.intValue;
  4388. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4389. }
  4390. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4391. {
  4392. // Convert to 64bit
  4393. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4394. from->type.qwordValue = (asINT64)(signed char)from->type.byteValue;
  4395. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4396. from->type.qwordValue = (asINT64)(short)from->type.wordValue;
  4397. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4398. from->type.qwordValue = (asINT64)from->type.intValue;
  4399. // Verify that it is possible to convert to unsigned without loosing negative
  4400. if( asINT64(from->type.qwordValue) < 0 )
  4401. {
  4402. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4403. }
  4404. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4405. }
  4406. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4407. {
  4408. // Verify that it is possible to convert to unsigned without loosing negative
  4409. if( asINT64(from->type.qwordValue) < 0 )
  4410. {
  4411. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4412. }
  4413. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4414. }
  4415. else if( from->type.dataType.IsUnsignedType() )
  4416. {
  4417. // Convert to 64bit
  4418. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4419. from->type.qwordValue = from->type.byteValue;
  4420. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4421. from->type.qwordValue = from->type.wordValue;
  4422. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4423. from->type.qwordValue = from->type.dwordValue;
  4424. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4425. }
  4426. }
  4427. else if( to.IsFloatType() )
  4428. {
  4429. if( from->type.dataType.IsDoubleType() )
  4430. {
  4431. double ic = from->type.doubleValue;
  4432. float fc = float(ic);
  4433. // Don't bother warning about this
  4434. // if( double(fc) != ic )
  4435. // {
  4436. // asCString str;
  4437. // str.Format(TXT_POSSIBLE_LOSS_OF_PRECISION);
  4438. // if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(str.AddressOf(), node);
  4439. // }
  4440. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4441. from->type.floatValue = fc;
  4442. }
  4443. else if( from->type.dataType.IsEnumType() )
  4444. {
  4445. float fc = float(from->type.intValue);
  4446. if( int(fc) != from->type.intValue )
  4447. {
  4448. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4449. }
  4450. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4451. from->type.floatValue = fc;
  4452. }
  4453. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4454. {
  4455. // Must properly convert value in case the from value is smaller
  4456. int ic;
  4457. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4458. ic = (signed char)from->type.byteValue;
  4459. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4460. ic = (short)from->type.wordValue;
  4461. else
  4462. ic = from->type.intValue;
  4463. float fc = float(ic);
  4464. if( int(fc) != ic )
  4465. {
  4466. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4467. }
  4468. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4469. from->type.floatValue = fc;
  4470. }
  4471. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4472. {
  4473. float fc = float(asINT64(from->type.qwordValue));
  4474. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  4475. {
  4476. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4477. }
  4478. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4479. from->type.floatValue = fc;
  4480. }
  4481. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4482. {
  4483. // Must properly convert value in case the from value is smaller
  4484. unsigned int uic;
  4485. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4486. uic = from->type.byteValue;
  4487. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4488. uic = from->type.wordValue;
  4489. else
  4490. uic = from->type.dwordValue;
  4491. float fc = float(uic);
  4492. if( (unsigned int)(fc) != uic )
  4493. {
  4494. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4495. }
  4496. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4497. from->type.floatValue = fc;
  4498. }
  4499. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4500. {
  4501. float fc = float((asINT64)from->type.qwordValue);
  4502. if( asQWORD(fc) != from->type.qwordValue )
  4503. {
  4504. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4505. }
  4506. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4507. from->type.floatValue = fc;
  4508. }
  4509. }
  4510. else if( to.IsDoubleType() )
  4511. {
  4512. if( from->type.dataType.IsFloatType() )
  4513. {
  4514. float ic = from->type.floatValue;
  4515. double fc = double(ic);
  4516. // Don't check for float->double
  4517. // if( float(fc) != ic )
  4518. // {
  4519. // acCString str;
  4520. // str.Format(TXT_NOT_EXACT_g_g_g, ic, fc, float(fc));
  4521. // if( !isExplicit ) Warning(str, node);
  4522. // }
  4523. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4524. from->type.doubleValue = fc;
  4525. }
  4526. else if( from->type.dataType.IsEnumType() )
  4527. {
  4528. double fc = double(from->type.intValue);
  4529. if( int(fc) != from->type.intValue )
  4530. {
  4531. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4532. }
  4533. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4534. from->type.doubleValue = fc;
  4535. }
  4536. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4537. {
  4538. // Must properly convert value in case the from value is smaller
  4539. int ic;
  4540. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4541. ic = (signed char)from->type.byteValue;
  4542. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4543. ic = (short)from->type.wordValue;
  4544. else
  4545. ic = from->type.intValue;
  4546. double fc = double(ic);
  4547. if( int(fc) != ic )
  4548. {
  4549. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4550. }
  4551. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4552. from->type.doubleValue = fc;
  4553. }
  4554. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4555. {
  4556. double fc = double(asINT64(from->type.qwordValue));
  4557. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  4558. {
  4559. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4560. }
  4561. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4562. from->type.doubleValue = fc;
  4563. }
  4564. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4565. {
  4566. // Must properly convert value in case the from value is smaller
  4567. unsigned int uic;
  4568. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4569. uic = from->type.byteValue;
  4570. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4571. uic = from->type.wordValue;
  4572. else
  4573. uic = from->type.dwordValue;
  4574. double fc = double(uic);
  4575. if( (unsigned int)(fc) != uic )
  4576. {
  4577. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4578. }
  4579. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4580. from->type.doubleValue = fc;
  4581. }
  4582. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4583. {
  4584. double fc = double((asINT64)from->type.qwordValue);
  4585. if( asQWORD(fc) != from->type.qwordValue )
  4586. {
  4587. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4588. }
  4589. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4590. from->type.doubleValue = fc;
  4591. }
  4592. }
  4593. }
  4594. int asCCompiler::DoAssignment(asSExprContext *ctx, asSExprContext *lctx, asSExprContext *rctx, asCScriptNode *lexpr, asCScriptNode *rexpr, int op, asCScriptNode *opNode)
  4595. {
  4596. // Implicit handle types should always be treated as handles in assignments
  4597. if (lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  4598. {
  4599. lctx->type.dataType.MakeHandle(true);
  4600. lctx->type.isExplicitHandle = true;
  4601. }
  4602. // Urho3D: if there is a handle type, and it does not have an overloaded assignment operator, convert to an explicit handle
  4603. // for scripting convenience. (For the Urho3D handle types, value assignment is not supported)
  4604. if (lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle && !lctx->type.dataType.GetObjectType()->beh.copy)
  4605. lctx->type.isExplicitHandle = true;
  4606. // If the left hand expression is a property accessor, then that should be used
  4607. // to do the assignment instead of the ordinary operator. The exception is when
  4608. // the property accessor is for a handle property, and the operation is a value
  4609. // assignment.
  4610. if( (lctx->property_get || lctx->property_set) &&
  4611. !(lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle) )
  4612. {
  4613. if( op != ttAssignment )
  4614. {
  4615. // TODO: getset: We may actually be able to support this, if we can
  4616. // guarantee that the object reference will stay valid
  4617. // between the calls to the get and set accessors.
  4618. // Process the property to free the memory
  4619. ProcessPropertySetAccessor(lctx, rctx, opNode);
  4620. // Compound assignments are not allowed for properties
  4621. Error(TXT_COMPOUND_ASGN_WITH_PROP, opNode);
  4622. return -1;
  4623. }
  4624. // It is not allowed to do a handle assignment on a property
  4625. // accessor that doesn't take a handle in the set accessor.
  4626. if( lctx->property_set && lctx->type.isExplicitHandle )
  4627. {
  4628. // set_opIndex has 2 arguments, where as normal setters have only 1
  4629. asCArray<asCDataType>& parameterTypes =
  4630. builder->GetFunctionDescription(lctx->property_set)->parameterTypes;
  4631. if( !parameterTypes[parameterTypes.GetLength() - 1].IsObjectHandle() )
  4632. {
  4633. // Process the property to free the memory
  4634. ProcessPropertySetAccessor(lctx, rctx, opNode);
  4635. Error(TXT_HANDLE_ASSIGN_ON_NON_HANDLE_PROP, opNode);
  4636. return -1;
  4637. }
  4638. }
  4639. MergeExprBytecodeAndType(ctx, lctx);
  4640. return ProcessPropertySetAccessor(ctx, rctx, opNode);
  4641. }
  4642. else if( lctx->property_get && lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  4643. {
  4644. // Get the handle to the object that will be used for the value assignment
  4645. ProcessPropertyGetAccessor(lctx, opNode);
  4646. }
  4647. if( lctx->type.dataType.IsPrimitive() )
  4648. {
  4649. if( !lctx->type.isLValue )
  4650. {
  4651. Error(TXT_NOT_LVALUE, lexpr);
  4652. return -1;
  4653. }
  4654. if( op != ttAssignment )
  4655. {
  4656. // Compute the operator before the assignment
  4657. asCTypeInfo lvalue = lctx->type;
  4658. if( lctx->type.isTemporary && !lctx->type.isVariable )
  4659. {
  4660. // The temporary variable must not be freed until the
  4661. // assignment has been performed. lvalue still holds
  4662. // the information about the temporary variable
  4663. lctx->type.isTemporary = false;
  4664. }
  4665. asSExprContext o(engine);
  4666. CompileOperator(opNode, lctx, rctx, &o);
  4667. MergeExprBytecode(rctx, &o);
  4668. rctx->type = o.type;
  4669. // Convert the rvalue to the right type and validate it
  4670. PrepareForAssignment(&lvalue.dataType, rctx, rexpr, false);
  4671. MergeExprBytecode(ctx, rctx);
  4672. lctx->type = lvalue;
  4673. // The lvalue continues the same, either it was a variable, or a reference in the register
  4674. }
  4675. else
  4676. {
  4677. // Convert the rvalue to the right type and validate it
  4678. PrepareForAssignment(&lctx->type.dataType, rctx, rexpr, false, lctx);
  4679. MergeExprBytecode(ctx, rctx);
  4680. MergeExprBytecode(ctx, lctx);
  4681. }
  4682. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4683. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4684. ctx->type = lctx->type;
  4685. }
  4686. else if( lctx->type.isExplicitHandle )
  4687. {
  4688. if( !lctx->type.isLValue )
  4689. {
  4690. Error(TXT_NOT_LVALUE, lexpr);
  4691. return -1;
  4692. }
  4693. // Object handles don't have any compound assignment operators
  4694. if( op != ttAssignment )
  4695. {
  4696. asCString str;
  4697. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4698. Error(str.AddressOf(), lexpr);
  4699. return -1;
  4700. }
  4701. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  4702. {
  4703. // The object is a value type but that should be treated as a handle
  4704. // TODO: handle: Make sure the right hand value is a handle
  4705. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  4706. {
  4707. // An overloaded assignment operator was found (or a compilation error occured)
  4708. return 0;
  4709. }
  4710. // The object must implement the opAssign method
  4711. Error(TXT_NO_APPROPRIATE_OPASSIGN, opNode);
  4712. return -1;
  4713. }
  4714. else
  4715. {
  4716. asCDataType dt = lctx->type.dataType;
  4717. dt.MakeReference(false);
  4718. PrepareArgument(&dt, rctx, rexpr, true, 1);
  4719. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4720. {
  4721. asCString str;
  4722. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  4723. Error(str.AddressOf(), rexpr);
  4724. return -1;
  4725. }
  4726. MergeExprBytecode(ctx, rctx);
  4727. MergeExprBytecode(ctx, lctx);
  4728. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  4729. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4730. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4731. ctx->type = rctx->type;
  4732. }
  4733. }
  4734. else // if( lctx->type.dataType.IsObject() )
  4735. {
  4736. // An ASHANDLE type must not allow a value assignment, as
  4737. // the opAssign operator is used for the handle assignment
  4738. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  4739. {
  4740. asCString str;
  4741. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4742. Error(str.AddressOf(), lexpr);
  4743. return -1;
  4744. }
  4745. // The lvalue reference may be marked as a temporary, if for example
  4746. // it was originated as a handle returned from a function. In such
  4747. // cases it must be possible to assign values to it anyway.
  4748. if( lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  4749. {
  4750. // Convert the handle to a object reference
  4751. asCDataType to;
  4752. to = lctx->type.dataType;
  4753. to.MakeHandle(false);
  4754. ImplicitConversion(lctx, to, lexpr, asIC_IMPLICIT_CONV);
  4755. lctx->type.isLValue = true; // Handle may not have been an lvalue, but the dereferenced object is
  4756. }
  4757. // Check for overloaded assignment operator
  4758. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  4759. {
  4760. // An overloaded assignment operator was found (or a compilation error occured)
  4761. return 0;
  4762. }
  4763. // No registered operator was found. In case the operation is a direct
  4764. // assignment and the rvalue is the same type as the lvalue, then we can
  4765. // still use the byte-for-byte copy to do the assignment
  4766. if( op != ttAssignment )
  4767. {
  4768. asCString str;
  4769. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4770. Error(str.AddressOf(), lexpr);
  4771. return -1;
  4772. }
  4773. // If the left hand expression is simple, i.e. without any
  4774. // function calls or allocations of memory, then we can avoid
  4775. // doing a copy of the right hand expression (done by PrepareArgument).
  4776. // Instead the reference to the value can be placed directly on the
  4777. // stack.
  4778. //
  4779. // This optimization should only be done for value types, where
  4780. // the application developer is responsible for making the
  4781. // implementation safe against unwanted destruction of the input
  4782. // reference before the time.
  4783. bool simpleExpr = (lctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) && lctx->bc.IsSimpleExpression();
  4784. // Implicitly convert the rvalue to the type of the lvalue
  4785. if( !lctx->type.dataType.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4786. simpleExpr = false;
  4787. if( !simpleExpr )
  4788. {
  4789. asCDataType dt = lctx->type.dataType;
  4790. dt.MakeReference(true);
  4791. dt.MakeReadOnly(true);
  4792. PrepareArgument(&dt, rctx, rexpr, true, 1);
  4793. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4794. {
  4795. asCString str;
  4796. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  4797. Error(str.AddressOf(), rexpr);
  4798. return -1;
  4799. }
  4800. }
  4801. else if( rctx->type.dataType.IsReference() && (!(rctx->type.isVariable || rctx->type.isTemporary) || IsVariableOnHeap(rctx->type.stackOffset)) )
  4802. rctx->bc.Instr(asBC_RDSPTR);
  4803. MergeExprBytecode(ctx, rctx);
  4804. MergeExprBytecode(ctx, lctx);
  4805. if( !simpleExpr )
  4806. {
  4807. if( (rctx->type.isVariable || rctx->type.isTemporary) && !IsVariableOnHeap(rctx->type.stackOffset) )
  4808. // TODO: optimize: Actually the reference can be pushed on the stack directly
  4809. // as the value allocated on the stack is guaranteed to be safe
  4810. ctx->bc.InstrWORD(asBC_GETREF, AS_PTR_SIZE);
  4811. else
  4812. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  4813. }
  4814. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4815. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4816. ctx->type = lctx->type;
  4817. }
  4818. return 0;
  4819. }
  4820. int asCCompiler::CompileAssignment(asCScriptNode *expr, asSExprContext *ctx)
  4821. {
  4822. asCScriptNode *lexpr = expr->firstChild;
  4823. if( lexpr->next )
  4824. {
  4825. // Compile the two expression terms
  4826. asSExprContext lctx(engine), rctx(engine);
  4827. int rr = CompileAssignment(lexpr->next->next, &rctx);
  4828. int lr = CompileCondition(lexpr, &lctx);
  4829. if( lr >= 0 && rr >= 0 )
  4830. return DoAssignment(ctx, &lctx, &rctx, lexpr, lexpr->next->next, lexpr->next->tokenType, lexpr->next);
  4831. // Since the operands failed, the assignment was not computed
  4832. ctx->type.SetDummy();
  4833. return -1;
  4834. }
  4835. return CompileCondition(lexpr, ctx);
  4836. }
  4837. int asCCompiler::CompileCondition(asCScriptNode *expr, asSExprContext *ctx)
  4838. {
  4839. asCTypeInfo ctype;
  4840. // Compile the conditional expression
  4841. asCScriptNode *cexpr = expr->firstChild;
  4842. if( cexpr->next )
  4843. {
  4844. //-------------------------------
  4845. // Compile the condition
  4846. asSExprContext e(engine);
  4847. int r = CompileExpression(cexpr, &e);
  4848. if( r < 0 )
  4849. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  4850. if( r >= 0 && !e.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  4851. {
  4852. Error(TXT_EXPR_MUST_BE_BOOL, cexpr);
  4853. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  4854. }
  4855. ctype = e.type;
  4856. ProcessPropertyGetAccessor(&e, cexpr);
  4857. if( e.type.dataType.IsReference() ) ConvertToVariable(&e);
  4858. ProcessDeferredParams(&e);
  4859. //-------------------------------
  4860. // Compile the left expression
  4861. asSExprContext le(engine);
  4862. int lr = CompileAssignment(cexpr->next, &le);
  4863. //-------------------------------
  4864. // Compile the right expression
  4865. asSExprContext re(engine);
  4866. int rr = CompileAssignment(cexpr->next->next, &re);
  4867. if( lr >= 0 && rr >= 0 )
  4868. {
  4869. ProcessPropertyGetAccessor(&le, cexpr->next);
  4870. ProcessPropertyGetAccessor(&re, cexpr->next->next);
  4871. bool isExplicitHandle = le.type.isExplicitHandle || re.type.isExplicitHandle;
  4872. // Allow a 0 or null in the first case to be implicitly converted to the second type
  4873. if( le.type.isConstant && le.type.intValue == 0 && le.type.dataType.IsUnsignedType() )
  4874. {
  4875. asCDataType to = re.type.dataType;
  4876. to.MakeReference(false);
  4877. to.MakeReadOnly(true);
  4878. ImplicitConversionConstant(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  4879. }
  4880. else if( le.type.IsNullConstant() )
  4881. {
  4882. asCDataType to = re.type.dataType;
  4883. to.MakeHandle(true);
  4884. ImplicitConversion(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  4885. }
  4886. //---------------------------------
  4887. // Output the byte code
  4888. int afterLabel = nextLabel++;
  4889. int elseLabel = nextLabel++;
  4890. // If left expression is void, then we don't need to store the result
  4891. if( le.type.dataType.IsEqualExceptConst(asCDataType::CreatePrimitive(ttVoid, false)) )
  4892. {
  4893. // Put the code for the condition expression on the output
  4894. MergeExprBytecode(ctx, &e);
  4895. // Added the branch decision
  4896. ctx->type = e.type;
  4897. ConvertToVariable(ctx);
  4898. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  4899. ctx->bc.Instr(asBC_ClrHi);
  4900. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  4901. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4902. // Add the left expression
  4903. MergeExprBytecode(ctx, &le);
  4904. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  4905. // Add the right expression
  4906. ctx->bc.Label((short)elseLabel);
  4907. MergeExprBytecode(ctx, &re);
  4908. ctx->bc.Label((short)afterLabel);
  4909. // Make sure both expressions have the same type
  4910. if( le.type.dataType != re.type.dataType )
  4911. Error(TXT_BOTH_MUST_BE_SAME, expr);
  4912. // Set the type of the result
  4913. ctx->type = le.type;
  4914. }
  4915. else
  4916. {
  4917. // Allocate temporary variable and copy the result to that one
  4918. asCTypeInfo temp;
  4919. temp = le.type;
  4920. temp.dataType.MakeReference(false);
  4921. temp.dataType.MakeReadOnly(false);
  4922. // Make sure the variable isn't used in the initial expression
  4923. asCArray<int> vars;
  4924. e.bc.GetVarsUsed(vars);
  4925. int offset = AllocateVariableNotIn(temp.dataType, true, &vars);
  4926. temp.SetVariable(temp.dataType, offset, true);
  4927. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  4928. CallDefaultConstructor(temp.dataType, offset, IsVariableOnHeap(offset), &ctx->bc, expr);
  4929. // Put the code for the condition expression on the output
  4930. MergeExprBytecode(ctx, &e);
  4931. // Add the branch decision
  4932. ctx->type = e.type;
  4933. ConvertToVariable(ctx);
  4934. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  4935. ctx->bc.Instr(asBC_ClrHi);
  4936. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  4937. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4938. // Assign the result of the left expression to the temporary variable
  4939. asCTypeInfo rtemp;
  4940. rtemp = temp;
  4941. if( rtemp.dataType.IsObjectHandle() )
  4942. rtemp.isExplicitHandle = true;
  4943. PrepareForAssignment(&rtemp.dataType, &le, cexpr->next, true);
  4944. MergeExprBytecode(ctx, &le);
  4945. if( !rtemp.dataType.IsPrimitive() )
  4946. {
  4947. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  4948. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  4949. }
  4950. PerformAssignment(&rtemp, &le.type, &ctx->bc, cexpr->next);
  4951. if( !rtemp.dataType.IsPrimitive() )
  4952. ctx->bc.Pop(le.type.dataType.GetSizeOnStackDWords()); // Pop the original value
  4953. // Release the old temporary variable
  4954. ReleaseTemporaryVariable(le.type, &ctx->bc);
  4955. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  4956. // Start of the right expression
  4957. ctx->bc.Label((short)elseLabel);
  4958. // Copy the result to the same temporary variable
  4959. PrepareForAssignment(&rtemp.dataType, &re, cexpr->next, true);
  4960. MergeExprBytecode(ctx, &re);
  4961. if( !rtemp.dataType.IsPrimitive() )
  4962. {
  4963. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  4964. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  4965. }
  4966. PerformAssignment(&rtemp, &re.type, &ctx->bc, cexpr->next);
  4967. if( !rtemp.dataType.IsPrimitive() )
  4968. ctx->bc.Pop(le.type.dataType.GetSizeOnStackDWords()); // Pop the original value
  4969. // Release the old temporary variable
  4970. ReleaseTemporaryVariable(re.type, &ctx->bc);
  4971. ctx->bc.Label((short)afterLabel);
  4972. // Make sure both expressions have the same type
  4973. if( le.type.dataType != re.type.dataType )
  4974. Error(TXT_BOTH_MUST_BE_SAME, expr);
  4975. // Set the temporary variable as output
  4976. ctx->type = rtemp;
  4977. ctx->type.isExplicitHandle = isExplicitHandle;
  4978. if( !ctx->type.dataType.IsPrimitive() )
  4979. {
  4980. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  4981. ctx->type.dataType.MakeReference(IsVariableOnHeap(offset));
  4982. }
  4983. // Make sure the output isn't marked as being a literal constant
  4984. ctx->type.isConstant = false;
  4985. }
  4986. }
  4987. else
  4988. {
  4989. ctx->type.SetDummy();
  4990. return -1;
  4991. }
  4992. }
  4993. else
  4994. return CompileExpression(cexpr, ctx);
  4995. return 0;
  4996. }
  4997. int asCCompiler::CompileExpression(asCScriptNode *expr, asSExprContext *ctx)
  4998. {
  4999. asASSERT(expr->nodeType == snExpression);
  5000. // Count the nodes
  5001. int count = 0;
  5002. asCScriptNode *node = expr->firstChild;
  5003. while( node )
  5004. {
  5005. count++;
  5006. node = node->next;
  5007. }
  5008. // Convert to polish post fix, i.e: a+b => ab+
  5009. asCArray<asCScriptNode *> stack(count);
  5010. asCArray<asCScriptNode *> stack2(count);
  5011. asCArray<asCScriptNode *> postfix(count);
  5012. node = expr->firstChild;
  5013. while( node )
  5014. {
  5015. int precedence = GetPrecedence(node);
  5016. while( stack.GetLength() > 0 &&
  5017. precedence <= GetPrecedence(stack[stack.GetLength()-1]) )
  5018. stack2.PushLast(stack.PopLast());
  5019. stack.PushLast(node);
  5020. node = node->next;
  5021. }
  5022. while( stack.GetLength() > 0 )
  5023. stack2.PushLast(stack.PopLast());
  5024. // We need to swap operands so that the left
  5025. // operand is always computed before the right
  5026. SwapPostFixOperands(stack2, postfix);
  5027. // Compile the postfix formatted expression
  5028. return CompilePostFixExpression(&postfix, ctx);
  5029. }
  5030. void asCCompiler::SwapPostFixOperands(asCArray<asCScriptNode *> &postfix, asCArray<asCScriptNode *> &target)
  5031. {
  5032. if( postfix.GetLength() == 0 ) return;
  5033. asCScriptNode *node = postfix.PopLast();
  5034. if( node->nodeType == snExprTerm )
  5035. {
  5036. target.PushLast(node);
  5037. return;
  5038. }
  5039. SwapPostFixOperands(postfix, target);
  5040. SwapPostFixOperands(postfix, target);
  5041. target.PushLast(node);
  5042. }
  5043. int asCCompiler::CompilePostFixExpression(asCArray<asCScriptNode *> *postfix, asSExprContext *ctx)
  5044. {
  5045. // Shouldn't send any byte code
  5046. asASSERT(ctx->bc.GetLastInstr() == -1);
  5047. // Set the context to a dummy type to avoid further
  5048. // errors in case the expression fails to compile
  5049. ctx->type.SetDummy();
  5050. // Pop the last node
  5051. asCScriptNode *node = postfix->PopLast();
  5052. ctx->exprNode = node;
  5053. // If term, compile the term
  5054. if( node->nodeType == snExprTerm )
  5055. return CompileExpressionTerm(node, ctx);
  5056. // Compile the two expression terms
  5057. asSExprContext r(engine), l(engine);
  5058. int ret;
  5059. ret = CompilePostFixExpression(postfix, &l); if( ret < 0 ) return ret;
  5060. ret = CompilePostFixExpression(postfix, &r); if( ret < 0 ) return ret;
  5061. // Compile the operation
  5062. return CompileOperator(node, &l, &r, ctx);
  5063. }
  5064. int asCCompiler::CompileExpressionTerm(asCScriptNode *node, asSExprContext *ctx)
  5065. {
  5066. // Shouldn't send any byte code
  5067. asASSERT(ctx->bc.GetLastInstr() == -1);
  5068. // Set the type as a dummy by default, in case of any compiler errors
  5069. ctx->type.SetDummy();
  5070. // Compile the value node
  5071. asCScriptNode *vnode = node->firstChild;
  5072. while( vnode->nodeType != snExprValue )
  5073. vnode = vnode->next;
  5074. asSExprContext v(engine);
  5075. int r = CompileExpressionValue(vnode, &v); if( r < 0 ) return r;
  5076. // Compile post fix operators
  5077. asCScriptNode *pnode = vnode->next;
  5078. while( pnode )
  5079. {
  5080. r = CompileExpressionPostOp(pnode, &v); if( r < 0 ) return r;
  5081. pnode = pnode->next;
  5082. }
  5083. // Compile pre fix operators
  5084. pnode = vnode->prev;
  5085. while( pnode )
  5086. {
  5087. r = CompileExpressionPreOp(pnode, &v); if( r < 0 ) return r;
  5088. pnode = pnode->prev;
  5089. }
  5090. // Return the byte code and final type description
  5091. MergeExprBytecodeAndType(ctx, &v);
  5092. return 0;
  5093. }
  5094. int asCCompiler::CompileVariableAccess(const asCString &name, const asCString &scope, asSExprContext *ctx, asCScriptNode *errNode, bool isOptional, bool noFunction, asCObjectType *objType)
  5095. {
  5096. bool found = false;
  5097. // It is a local variable or parameter?
  5098. // This is not accessible by default arg expressions
  5099. sVariable *v = 0;
  5100. if( !isCompilingDefaultArg && scope == "" && !objType )
  5101. v = variables->GetVariable(name.AddressOf());
  5102. if( v )
  5103. {
  5104. found = true;
  5105. if( v->isPureConstant )
  5106. ctx->type.SetConstantQW(v->type, v->constantValue);
  5107. else if( v->type.IsPrimitive() )
  5108. {
  5109. if( v->type.IsReference() )
  5110. {
  5111. // Copy the reference into the register
  5112. #if AS_PTR_SIZE == 1
  5113. ctx->bc.InstrSHORT(asBC_CpyVtoR4, (short)v->stackOffset);
  5114. #else
  5115. ctx->bc.InstrSHORT(asBC_CpyVtoR8, (short)v->stackOffset);
  5116. #endif
  5117. ctx->type.Set(v->type);
  5118. }
  5119. else
  5120. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5121. ctx->type.isLValue = true;
  5122. }
  5123. else
  5124. {
  5125. ctx->bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  5126. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5127. // If the variable is allocated on the heap we have a reference,
  5128. // otherwise the actual object pointer is pushed on the stack.
  5129. if( v->onHeap || v->type.IsObjectHandle() ) ctx->type.dataType.MakeReference(true);
  5130. // Implicitly dereference handle parameters sent by reference
  5131. if( v->type.IsReference() && (!v->type.IsObject() || v->type.IsObjectHandle()) )
  5132. ctx->bc.Instr(asBC_RDSPTR);
  5133. ctx->type.isLValue = true;
  5134. }
  5135. }
  5136. // Is it a class member?
  5137. // This is not accessible by default arg expressions
  5138. if( !isCompilingDefaultArg && !found && ((objType) || (outFunc && outFunc->objectType && scope == "")) )
  5139. {
  5140. if( name == THIS_TOKEN && !objType )
  5141. {
  5142. asCDataType dt = asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly);
  5143. // The object pointer is located at stack position 0
  5144. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5145. ctx->type.SetVariable(dt, 0, false);
  5146. ctx->type.dataType.MakeReference(true);
  5147. ctx->type.isLValue = true;
  5148. found = true;
  5149. }
  5150. if( !found )
  5151. {
  5152. // See if there are any matching property accessors
  5153. asSExprContext access(engine);
  5154. if( objType )
  5155. access.type.Set(asCDataType::CreateObject(objType, false));
  5156. else
  5157. access.type.Set(asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly));
  5158. access.type.dataType.MakeReference(true);
  5159. int r = 0;
  5160. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5161. {
  5162. // This is an index access, check if there is a property accessor that takes an index arg
  5163. asSExprContext dummyArg(engine);
  5164. r = FindPropertyAccessor(name, &access, &dummyArg, errNode, true);
  5165. }
  5166. if( r == 0 )
  5167. {
  5168. // Normal property access
  5169. r = FindPropertyAccessor(name, &access, errNode, true);
  5170. }
  5171. if( r < 0 ) return -1;
  5172. if( access.property_get || access.property_set )
  5173. {
  5174. if( !objType )
  5175. {
  5176. // Prepare the bytecode for the member access
  5177. // This is only done when accessing through the implicit this pointer
  5178. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5179. }
  5180. MergeExprBytecodeAndType(ctx, &access);
  5181. found = true;
  5182. }
  5183. }
  5184. if( !found )
  5185. {
  5186. asCDataType dt;
  5187. if( objType )
  5188. dt = asCDataType::CreateObject(objType, false);
  5189. else
  5190. dt = asCDataType::CreateObject(outFunc->objectType, false);
  5191. asCObjectProperty *prop = builder->GetObjectProperty(dt, name.AddressOf());
  5192. if( prop )
  5193. {
  5194. if( !objType )
  5195. {
  5196. // The object pointer is located at stack position 0
  5197. // This is only done when accessing through the implicit this pointer
  5198. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5199. ctx->type.SetVariable(dt, 0, false);
  5200. ctx->type.dataType.MakeReference(true);
  5201. Dereference(ctx, true);
  5202. }
  5203. // TODO: This is the same as what is in CompileExpressionPostOp
  5204. // Put the offset on the stack
  5205. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(dt));
  5206. if( prop->type.IsReference() )
  5207. ctx->bc.Instr(asBC_RDSPTR);
  5208. // Reference to primitive must be stored in the temp register
  5209. if( prop->type.IsPrimitive() )
  5210. {
  5211. // TODO: optimize: The ADD offset command should store the reference in the register directly
  5212. ctx->bc.Instr(asBC_PopRPtr);
  5213. }
  5214. // Set the new type (keeping info about temp variable)
  5215. ctx->type.dataType = prop->type;
  5216. ctx->type.dataType.MakeReference(true);
  5217. ctx->type.isVariable = false;
  5218. ctx->type.isLValue = true;
  5219. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  5220. {
  5221. // Objects that are members are not references
  5222. ctx->type.dataType.MakeReference(false);
  5223. }
  5224. // If the object reference is const, the property will also be const
  5225. ctx->type.dataType.MakeReadOnly(outFunc->isReadOnly);
  5226. found = true;
  5227. }
  5228. }
  5229. }
  5230. // Is it a global property?
  5231. if( !found && (scope == "" || scope == "::") && !objType )
  5232. {
  5233. // See if there are any matching global property accessors
  5234. asSExprContext access(engine);
  5235. int r = 0;
  5236. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5237. {
  5238. // This is an index access, check if there is a property accessor that takes an index arg
  5239. asSExprContext dummyArg(engine);
  5240. r = FindPropertyAccessor(name, &access, &dummyArg, errNode);
  5241. }
  5242. if( r == 0 )
  5243. {
  5244. // Normal property access
  5245. r = FindPropertyAccessor(name, &access, errNode);
  5246. }
  5247. if( r < 0 ) return -1;
  5248. if( access.property_get || access.property_set )
  5249. {
  5250. // Prepare the bytecode for the function call
  5251. MergeExprBytecodeAndType(ctx, &access);
  5252. found = true;
  5253. }
  5254. // See if there is any matching global property
  5255. if( !found )
  5256. {
  5257. bool isCompiled = true;
  5258. bool isPureConstant = false;
  5259. bool isAppProp = false;
  5260. asQWORD constantValue;
  5261. asCGlobalProperty *prop = builder->GetGlobalProperty(name.AddressOf(), &isCompiled, &isPureConstant, &constantValue, &isAppProp);
  5262. if( prop )
  5263. {
  5264. found = true;
  5265. // Verify that the global property has been compiled already
  5266. if( isCompiled )
  5267. {
  5268. if( ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  5269. {
  5270. ctx->type.dataType.MakeHandle(true);
  5271. ctx->type.isExplicitHandle = true;
  5272. }
  5273. // If the global property is a pure constant
  5274. // we can allow the compiler to optimize it. Pure
  5275. // constants are global constant variables that were
  5276. // initialized by literal constants.
  5277. if( isPureConstant )
  5278. ctx->type.SetConstantQW(prop->type, constantValue);
  5279. else
  5280. {
  5281. // A shared type must not access global vars, unless they
  5282. // too are shared, e.g. application registered vars
  5283. if( outFunc->objectType && outFunc->objectType->IsShared() )
  5284. {
  5285. if( !isAppProp )
  5286. {
  5287. asCString str;
  5288. str.Format(TXT_SHARED_CANNOT_ACCESS_NON_SHARED_VAR_s, prop->name.AddressOf());
  5289. Error(str.AddressOf(), errNode);
  5290. // Allow the compilation to continue to catch other problems
  5291. }
  5292. }
  5293. ctx->type.Set(prop->type);
  5294. ctx->type.dataType.MakeReference(true);
  5295. ctx->type.isLValue = true;
  5296. if( ctx->type.dataType.IsPrimitive() )
  5297. {
  5298. // Load the address of the variable into the register
  5299. ctx->bc.InstrPTR(asBC_LDG, engine->globalProperties[prop->id]->GetAddressOfValue());
  5300. }
  5301. else
  5302. {
  5303. // Push the address of the variable on the stack
  5304. ctx->bc.InstrPTR(asBC_PGA, engine->globalProperties[prop->id]->GetAddressOfValue());
  5305. // If the object is a value type, then we must validate the existance,
  5306. // as it could potentially be accessed before it is initialized.
  5307. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_VALUE ||
  5308. !ctx->type.dataType.IsObjectHandle() )
  5309. {
  5310. // TODO: optimize: This is not necessary for application registered properties
  5311. ctx->bc.Instr(asBC_ChkRefS);
  5312. }
  5313. }
  5314. }
  5315. }
  5316. else
  5317. {
  5318. asCString str;
  5319. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, prop->name.AddressOf());
  5320. Error(str.AddressOf(), errNode);
  5321. return -1;
  5322. }
  5323. }
  5324. }
  5325. }
  5326. // Is it the name of a global function?
  5327. if( !noFunction && !found && (scope == "" || scope == "::") && !objType )
  5328. {
  5329. asCArray<int> funcs;
  5330. builder->GetFunctionDescriptions(name.AddressOf(), funcs);
  5331. if( funcs.GetLength() > 1 )
  5332. {
  5333. // TODO: funcdef: If multiple functions are found, then the compiler should defer the decision
  5334. // to which one it should use until the value is actually used.
  5335. //
  5336. // - assigning the function pointer to a variable
  5337. // - performing an explicit cast
  5338. // - passing the function pointer to a function as parameter
  5339. asCString str;
  5340. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, name.AddressOf());
  5341. Error(str.AddressOf(), errNode);
  5342. return -1;
  5343. }
  5344. else if( funcs.GetLength() == 1 )
  5345. {
  5346. found = true;
  5347. // A shared object may not access global functions unless they too are shared (e.g. registered functions)
  5348. if( !builder->GetFunctionDescription(funcs[0])->IsShared() &&
  5349. outFunc->objectType && outFunc->objectType->IsShared() )
  5350. {
  5351. asCString msg;
  5352. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, builder->GetFunctionDescription(funcs[0])->GetDeclaration());
  5353. Error(msg.AddressOf(), errNode);
  5354. return -1;
  5355. }
  5356. // Push the function pointer on the stack
  5357. ctx->bc.InstrPTR(asBC_FuncPtr, builder->GetFunctionDescription(funcs[0]));
  5358. ctx->type.Set(asCDataType::CreateFuncDef(builder->GetFunctionDescription(funcs[0])));
  5359. }
  5360. }
  5361. // Is it an enum value?
  5362. if( !found && !objType )
  5363. {
  5364. asCObjectType *scopeType = 0;
  5365. if( scope != "" )
  5366. {
  5367. // resolve the type before the scope
  5368. scopeType = builder->GetObjectType( scope.AddressOf() );
  5369. }
  5370. asDWORD value = 0;
  5371. asCDataType dt;
  5372. if( scopeType && builder->GetEnumValueFromObjectType(scopeType, name.AddressOf(), dt, value) )
  5373. {
  5374. // scoped enum value found
  5375. found = true;
  5376. }
  5377. else if( scope == "" && !engine->ep.requireEnumScope )
  5378. {
  5379. // look for the enum value with no namespace
  5380. int e = builder->GetEnumValue(name.AddressOf(), dt, value);
  5381. if( e )
  5382. {
  5383. found = true;
  5384. if( e == 2 )
  5385. {
  5386. Error(TXT_FOUND_MULTIPLE_ENUM_VALUES, errNode);
  5387. }
  5388. }
  5389. }
  5390. if( found )
  5391. {
  5392. // Even if the enum type is not shared, and we're compiling a shared object,
  5393. // the use of the values are still allowed, since they are treated as constants.
  5394. // an enum value was resolved
  5395. ctx->type.SetConstantDW(dt, value);
  5396. }
  5397. }
  5398. // The name doesn't match any variable
  5399. if( !found )
  5400. {
  5401. // Give dummy value
  5402. ctx->type.SetDummy();
  5403. if( !isOptional )
  5404. {
  5405. // Prepend the scope to the name for the error message
  5406. asCString ename;
  5407. if( scope != "" && scope != "::" )
  5408. ename = scope + "::";
  5409. else
  5410. ename = scope;
  5411. ename += name;
  5412. asCString str;
  5413. str.Format(TXT_s_NOT_DECLARED, ename.AddressOf());
  5414. Error(str.AddressOf(), errNode);
  5415. // Declare the variable now so that it will not be reported again
  5416. variables->DeclareVariable(name.AddressOf(), asCDataType::CreatePrimitive(ttInt, false), 0x7FFF, true);
  5417. // Mark the variable as initialized so that the user will not be bother by it again
  5418. sVariable *v = variables->GetVariable(name.AddressOf());
  5419. asASSERT(v);
  5420. if( v ) v->isInitialized = true;
  5421. }
  5422. // Return -1 to signal that the variable wasn't found
  5423. return -1;
  5424. }
  5425. return 0;
  5426. }
  5427. int asCCompiler::CompileExpressionValue(asCScriptNode *node, asSExprContext *ctx)
  5428. {
  5429. // Shouldn't receive any byte code
  5430. asASSERT(ctx->bc.GetLastInstr() == -1);
  5431. asCScriptNode *vnode = node->firstChild;
  5432. ctx->exprNode = vnode;
  5433. if( vnode->nodeType == snVariableAccess )
  5434. {
  5435. // Determine the scope resolution of the variable
  5436. asCString scope = GetScopeFromNode(vnode);
  5437. // Determine the name of the variable
  5438. vnode = vnode->lastChild;
  5439. asASSERT(vnode->nodeType == snIdentifier );
  5440. asCString name(&script->code[vnode->tokenPos], vnode->tokenLength);
  5441. return CompileVariableAccess(name, scope, ctx, node);
  5442. }
  5443. else if( vnode->nodeType == snConstant )
  5444. {
  5445. if( vnode->tokenType == ttIntConstant )
  5446. {
  5447. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5448. asQWORD val = asStringScanUInt64(value.AddressOf(), 10, 0);
  5449. // Do we need 64 bits?
  5450. if( val>>32 )
  5451. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  5452. else
  5453. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  5454. }
  5455. else if( vnode->tokenType == ttBitsConstant )
  5456. {
  5457. asCString value(&script->code[vnode->tokenPos+2], vnode->tokenLength-2);
  5458. // TODO: Check for overflow
  5459. asQWORD val = asStringScanUInt64(value.AddressOf(), 16, 0);
  5460. // Do we need 64 bits?
  5461. if( val>>32 )
  5462. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  5463. else
  5464. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  5465. }
  5466. else if( vnode->tokenType == ttFloatConstant )
  5467. {
  5468. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5469. // TODO: Check for overflow
  5470. size_t numScanned;
  5471. float v = float(asStringScanDouble(value.AddressOf(), &numScanned));
  5472. ctx->type.SetConstantF(asCDataType::CreatePrimitive(ttFloat, true), v);
  5473. #ifndef AS_USE_DOUBLE_AS_FLOAT
  5474. // Don't check this if we have double as float, because then the whole token would be scanned (i.e. no f suffix)
  5475. asASSERT(numScanned == vnode->tokenLength - 1);
  5476. #endif
  5477. }
  5478. else if( vnode->tokenType == ttDoubleConstant )
  5479. {
  5480. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5481. // TODO: Check for overflow
  5482. size_t numScanned;
  5483. double v = asStringScanDouble(value.AddressOf(), &numScanned);
  5484. ctx->type.SetConstantD(asCDataType::CreatePrimitive(ttDouble, true), v);
  5485. asASSERT(numScanned == vnode->tokenLength);
  5486. }
  5487. else if( vnode->tokenType == ttTrue ||
  5488. vnode->tokenType == ttFalse )
  5489. {
  5490. #if AS_SIZEOF_BOOL == 1
  5491. ctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  5492. #else
  5493. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  5494. #endif
  5495. }
  5496. else if( vnode->tokenType == ttStringConstant ||
  5497. vnode->tokenType == ttMultilineStringConstant ||
  5498. vnode->tokenType == ttHeredocStringConstant )
  5499. {
  5500. asCString str;
  5501. asCScriptNode *snode = vnode->firstChild;
  5502. if( script->code[snode->tokenPos] == '\'' && engine->ep.useCharacterLiterals )
  5503. {
  5504. // Treat the single quoted string as a single character literal
  5505. str.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5506. asDWORD val = 0;
  5507. if( str.GetLength() && (unsigned char)str[0] > 127 && engine->ep.scanner == 1 )
  5508. {
  5509. // This is the start of a UTF8 encoded character. We need to decode it
  5510. val = asStringDecodeUTF8(str.AddressOf(), 0);
  5511. if( val == (asDWORD)-1 )
  5512. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  5513. }
  5514. else
  5515. {
  5516. val = ProcessStringConstant(str, snode);
  5517. if( val == (asDWORD)-1 )
  5518. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  5519. }
  5520. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), val);
  5521. }
  5522. else
  5523. {
  5524. // Process the string constants
  5525. while( snode )
  5526. {
  5527. asCString cat;
  5528. if( snode->tokenType == ttStringConstant )
  5529. {
  5530. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5531. ProcessStringConstant(cat, snode);
  5532. }
  5533. else if( snode->tokenType == ttMultilineStringConstant )
  5534. {
  5535. if( !engine->ep.allowMultilineStrings )
  5536. Error(TXT_MULTILINE_STRINGS_NOT_ALLOWED, snode);
  5537. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5538. ProcessStringConstant(cat, snode);
  5539. }
  5540. else if( snode->tokenType == ttHeredocStringConstant )
  5541. {
  5542. cat.Assign(&script->code[snode->tokenPos+3], snode->tokenLength-6);
  5543. ProcessHeredocStringConstant(cat, snode);
  5544. }
  5545. str += cat;
  5546. snode = snode->next;
  5547. }
  5548. // Call the string factory function to create a string object
  5549. asCScriptFunction *descr = engine->stringFactory;
  5550. if( descr == 0 )
  5551. {
  5552. // Error
  5553. Error(TXT_STRINGS_NOT_RECOGNIZED, vnode);
  5554. // Give dummy value
  5555. ctx->type.SetDummy();
  5556. return -1;
  5557. }
  5558. else
  5559. {
  5560. // Register the constant string with the engine
  5561. int id = engine->AddConstantString(str.AddressOf(), str.GetLength());
  5562. ctx->bc.InstrWORD(asBC_STR, (asWORD)id);
  5563. bool useVariable = false;
  5564. int stackOffset = 0;
  5565. #ifndef AS_OLD
  5566. if( descr->DoesReturnOnStack() )
  5567. {
  5568. useVariable = true;
  5569. stackOffset = AllocateVariable(descr->returnType, true);
  5570. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  5571. }
  5572. #endif
  5573. PerformFunctionCall(descr->id, ctx, false, 0, 0, useVariable, stackOffset);
  5574. }
  5575. }
  5576. }
  5577. else if( vnode->tokenType == ttNull )
  5578. {
  5579. #ifndef AS_64BIT_PTR
  5580. ctx->bc.InstrDWORD(asBC_PshC4, 0);
  5581. #else
  5582. ctx->bc.InstrQWORD(asBC_PshC8, 0);
  5583. #endif
  5584. ctx->type.SetNullConstant();
  5585. }
  5586. else
  5587. asASSERT(false);
  5588. }
  5589. else if( vnode->nodeType == snFunctionCall )
  5590. {
  5591. // Determine the scope resolution
  5592. asCString scope = GetScopeFromNode(vnode);
  5593. if( outFunc && outFunc->objectType && scope != "::" )
  5594. {
  5595. // TODO: funcdef: There may be a local variable of a function type with the same name
  5596. // Check if a class method is being called
  5597. asCScriptNode *nm = vnode->lastChild->prev;
  5598. asCString name;
  5599. name.Assign(&script->code[nm->tokenPos], nm->tokenLength);
  5600. asCArray<int> funcs;
  5601. // If we're compiling a constructor and the name of the function called
  5602. // is 'super' then the base class' constructor is being called.
  5603. // super cannot be called from another scope, i.e. must not be prefixed
  5604. if( m_isConstructor && name == SUPER_TOKEN && nm->prev == 0 )
  5605. {
  5606. // Actually it is the base class' constructor that is being called,
  5607. // but as we won't use the actual function ids here we can take the
  5608. // object's own constructors and avoid the need to check if the
  5609. // object actually derives from any other class
  5610. funcs = outFunc->objectType->beh.constructors;
  5611. // Must not allow calling constructors multiple times
  5612. if( continueLabels.GetLength() > 0 )
  5613. {
  5614. // If a continue label is set we are in a loop
  5615. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_LOOPS, vnode);
  5616. }
  5617. else if( breakLabels.GetLength() > 0 )
  5618. {
  5619. // TODO: inheritance: Should eventually allow constructors in switch statements
  5620. // If a break label is set we are either in a loop or a switch statements
  5621. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_SWITCH, vnode);
  5622. }
  5623. else if( m_isConstructorCalled )
  5624. {
  5625. Error(TXT_CANNOT_CALL_CONSTRUCTOR_TWICE, vnode);
  5626. }
  5627. m_isConstructorCalled = true;
  5628. }
  5629. else
  5630. builder->GetObjectMethodDescriptions(name.AddressOf(), outFunc->objectType, funcs, false);
  5631. if( funcs.GetLength() )
  5632. {
  5633. asCDataType dt = asCDataType::CreateObject(outFunc->objectType, false);
  5634. // The object pointer is located at stack position 0
  5635. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5636. ctx->type.SetVariable(dt, 0, false);
  5637. ctx->type.dataType.MakeReference(true);
  5638. // TODO: optimize: This adds a CHKREF. Is that really necessary?
  5639. Dereference(ctx, true);
  5640. return CompileFunctionCall(vnode, ctx, outFunc->objectType, false, scope);
  5641. }
  5642. }
  5643. return CompileFunctionCall(vnode, ctx, 0, false, scope);
  5644. }
  5645. else if( vnode->nodeType == snConstructCall )
  5646. {
  5647. CompileConstructCall(vnode, ctx);
  5648. }
  5649. else if( vnode->nodeType == snAssignment )
  5650. {
  5651. asSExprContext e(engine);
  5652. int r = CompileAssignment(vnode, &e);
  5653. if( r < 0 )
  5654. {
  5655. ctx->type.SetDummy();
  5656. return r;
  5657. }
  5658. MergeExprBytecodeAndType(ctx, &e);
  5659. }
  5660. else if( vnode->nodeType == snCast )
  5661. {
  5662. // Implement the cast operator
  5663. CompileConversion(vnode, ctx);
  5664. }
  5665. else
  5666. asASSERT(false);
  5667. return 0;
  5668. }
  5669. asCString asCCompiler::GetScopeFromNode(asCScriptNode *node)
  5670. {
  5671. asCString scope;
  5672. asCScriptNode *sn = node->firstChild;
  5673. if( sn->tokenType == ttScope )
  5674. {
  5675. // Global scope
  5676. scope = "::";
  5677. sn = sn->next;
  5678. }
  5679. else if( sn->next && sn->next->tokenType == ttScope )
  5680. {
  5681. scope.Assign(&script->code[sn->tokenPos], sn->tokenLength);
  5682. sn = sn->next->next;
  5683. }
  5684. if( scope != "" )
  5685. {
  5686. // We don't support multiple levels of scope yet
  5687. if( sn->next && sn->next->tokenType == ttScope )
  5688. {
  5689. Error(TXT_INVALID_SCOPE, sn->next);
  5690. }
  5691. }
  5692. return scope;
  5693. }
  5694. asUINT asCCompiler::ProcessStringConstant(asCString &cstr, asCScriptNode *node, bool processEscapeSequences)
  5695. {
  5696. int charLiteral = -1;
  5697. // Process escape sequences
  5698. asCArray<char> str((int)cstr.GetLength());
  5699. for( asUINT n = 0; n < cstr.GetLength(); n++ )
  5700. {
  5701. #ifdef AS_DOUBLEBYTE_CHARSET
  5702. // Double-byte charset is only allowed for ASCII and not UTF16 encoded strings
  5703. if( (cstr[n] & 0x80) && engine->ep.scanner == 0 && engine->ep.stringEncoding != 1 )
  5704. {
  5705. // This is the lead character of a double byte character
  5706. // include the trail character without checking it's value.
  5707. str.PushLast(cstr[n]);
  5708. n++;
  5709. str.PushLast(cstr[n]);
  5710. continue;
  5711. }
  5712. #endif
  5713. asUINT val;
  5714. if( processEscapeSequences && cstr[n] == '\\' )
  5715. {
  5716. ++n;
  5717. if( n == cstr.GetLength() )
  5718. {
  5719. if( charLiteral == -1 ) charLiteral = 0;
  5720. return charLiteral;
  5721. }
  5722. // TODO: Consider deprecating use of hexadecimal escape sequences,
  5723. // as they do not guarantee proper unicode sequences
  5724. if( cstr[n] == 'x' || cstr[n] == 'X' )
  5725. {
  5726. ++n;
  5727. if( n == cstr.GetLength() ) break;
  5728. val = 0;
  5729. int c = engine->ep.stringEncoding == 1 ? 4 : 2;
  5730. for( ; c > 0 && n < cstr.GetLength(); c--, n++ )
  5731. {
  5732. if( cstr[n] >= '0' && cstr[n] <= '9' )
  5733. val = val*16 + cstr[n] - '0';
  5734. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  5735. val = val*16 + cstr[n] - 'a' + 10;
  5736. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  5737. val = val*16 + cstr[n] - 'A' + 10;
  5738. else
  5739. break;
  5740. }
  5741. // Rewind one, since the loop will increment it again
  5742. n--;
  5743. // Hexadecimal escape sequences produce exact value, even if it is not proper unicode chars
  5744. if( engine->ep.stringEncoding == 0 )
  5745. {
  5746. str.PushLast((asBYTE)val);
  5747. }
  5748. else
  5749. {
  5750. #ifndef AS_BIG_ENDIAN
  5751. str.PushLast((asBYTE)val);
  5752. str.PushLast((asBYTE)(val>>8));
  5753. #else
  5754. str.PushLast((asBYTE)(val>>8));
  5755. str.PushLast((asBYTE)val);
  5756. #endif
  5757. }
  5758. if( charLiteral == -1 ) charLiteral = val;
  5759. continue;
  5760. }
  5761. else if( cstr[n] == 'u' || cstr[n] == 'U' )
  5762. {
  5763. // \u expects 4 hex digits
  5764. // \U expects 8 hex digits
  5765. bool expect2 = cstr[n] == 'u';
  5766. int c = expect2 ? 4 : 8;
  5767. val = 0;
  5768. for( ; c > 0; c-- )
  5769. {
  5770. ++n;
  5771. if( n == cstr.GetLength() ) break;
  5772. if( cstr[n] >= '0' && cstr[n] <= '9' )
  5773. val = val*16 + cstr[n] - '0';
  5774. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  5775. val = val*16 + cstr[n] - 'a' + 10;
  5776. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  5777. val = val*16 + cstr[n] - 'A' + 10;
  5778. else
  5779. break;
  5780. }
  5781. if( c != 0 )
  5782. {
  5783. // Give warning about invalid code point
  5784. // TODO: Need code position for warning
  5785. asCString msg;
  5786. msg.Format(TXT_INVALID_UNICODE_FORMAT_EXPECTED_d, expect2 ? 4 : 8);
  5787. Warning(msg.AddressOf(), node);
  5788. continue;
  5789. }
  5790. }
  5791. else
  5792. {
  5793. if( cstr[n] == '"' )
  5794. val = '"';
  5795. else if( cstr[n] == '\'' )
  5796. val = '\'';
  5797. else if( cstr[n] == 'n' )
  5798. val = '\n';
  5799. else if( cstr[n] == 'r' )
  5800. val = '\r';
  5801. else if( cstr[n] == 't' )
  5802. val = '\t';
  5803. else if( cstr[n] == '0' )
  5804. val = '\0';
  5805. else if( cstr[n] == '\\' )
  5806. val = '\\';
  5807. else
  5808. {
  5809. // Invalid escape sequence
  5810. Warning(TXT_INVALID_ESCAPE_SEQUENCE, node);
  5811. continue;
  5812. }
  5813. }
  5814. }
  5815. else
  5816. {
  5817. if( engine->ep.scanner == 1 && (cstr[n] & 0x80) )
  5818. {
  5819. unsigned int len;
  5820. val = asStringDecodeUTF8(&cstr[n], &len);
  5821. if( val == 0xFFFFFFFF )
  5822. {
  5823. // Incorrect UTF8 encoding. Use only the first byte
  5824. // TODO: Need code position for warning
  5825. Warning(TXT_INVALID_UNICODE_SEQUENCE_IN_SRC, node);
  5826. val = (unsigned char)cstr[n];
  5827. }
  5828. else
  5829. n += len-1;
  5830. }
  5831. else
  5832. val = (unsigned char)cstr[n];
  5833. }
  5834. // Add the character to the final string
  5835. char encodedValue[5];
  5836. int len;
  5837. if( engine->ep.scanner == 1 && engine->ep.stringEncoding == 0 )
  5838. {
  5839. // Convert to UTF8 encoded
  5840. len = asStringEncodeUTF8(val, encodedValue);
  5841. }
  5842. else if( engine->ep.stringEncoding == 1 )
  5843. {
  5844. // Convert to 16bit wide character string (even if the script is scanned as ASCII)
  5845. len = asStringEncodeUTF16(val, encodedValue);
  5846. }
  5847. else
  5848. {
  5849. // Do not convert ASCII characters
  5850. encodedValue[0] = (asBYTE)val;
  5851. len = 1;
  5852. }
  5853. if( len < 0 )
  5854. {
  5855. // Give warning about invalid code point
  5856. // TODO: Need code position for warning
  5857. Warning(TXT_INVALID_UNICODE_VALUE, node);
  5858. }
  5859. else
  5860. {
  5861. // Add the encoded value to the final string
  5862. str.Concatenate(encodedValue, len);
  5863. if( charLiteral == -1 ) charLiteral = val;
  5864. }
  5865. }
  5866. cstr.Assign(str.AddressOf(), str.GetLength());
  5867. return charLiteral;
  5868. }
  5869. void asCCompiler::ProcessHeredocStringConstant(asCString &str, asCScriptNode *node)
  5870. {
  5871. // Remove first line if it only contains whitespace
  5872. int start;
  5873. for( start = 0; start < (int)str.GetLength(); start++ )
  5874. {
  5875. if( str[start] == '\n' )
  5876. {
  5877. // Remove the linebreak as well
  5878. start++;
  5879. break;
  5880. }
  5881. if( str[start] != ' ' &&
  5882. str[start] != '\t' &&
  5883. str[start] != '\r' )
  5884. {
  5885. // Don't remove anything
  5886. start = 0;
  5887. break;
  5888. }
  5889. }
  5890. // Remove last line break and the line after that if it only contains whitespaces
  5891. int end;
  5892. for( end = (int)str.GetLength() - 1; end >= 0; end-- )
  5893. {
  5894. if( str[end] == '\n' )
  5895. break;
  5896. if( str[end] != ' ' &&
  5897. str[end] != '\t' &&
  5898. str[end] != '\r' )
  5899. {
  5900. // Don't remove anything
  5901. end = (int)str.GetLength();
  5902. break;
  5903. }
  5904. }
  5905. if( end < 0 ) end = 0;
  5906. asCString tmp;
  5907. if( end > start )
  5908. tmp.Assign(&str[start], end-start);
  5909. ProcessStringConstant(tmp, node, false);
  5910. str = tmp;
  5911. }
  5912. void asCCompiler::CompileConversion(asCScriptNode *node, asSExprContext *ctx)
  5913. {
  5914. asSExprContext expr(engine);
  5915. asCDataType to;
  5916. bool anyErrors = false;
  5917. EImplicitConv convType;
  5918. if( node->nodeType == snConstructCall )
  5919. {
  5920. convType = asIC_EXPLICIT_VAL_CAST;
  5921. // Verify that there is only one argument
  5922. if( node->lastChild->firstChild == 0 ||
  5923. node->lastChild->firstChild != node->lastChild->lastChild )
  5924. {
  5925. Error(TXT_ONLY_ONE_ARGUMENT_IN_CAST, node->lastChild);
  5926. expr.type.SetDummy();
  5927. anyErrors = true;
  5928. }
  5929. else
  5930. {
  5931. // Compile the expression
  5932. int r = CompileAssignment(node->lastChild->firstChild, &expr);
  5933. if( r < 0 )
  5934. anyErrors = true;
  5935. }
  5936. // Determine the requested type
  5937. to = builder->CreateDataTypeFromNode(node->firstChild, script);
  5938. to.MakeReadOnly(true); // Default to const
  5939. asASSERT(to.IsPrimitive());
  5940. }
  5941. else
  5942. {
  5943. convType = asIC_EXPLICIT_REF_CAST;
  5944. // Compile the expression
  5945. int r = CompileAssignment(node->lastChild, &expr);
  5946. if( r < 0 )
  5947. anyErrors = true;
  5948. // Determine the requested type
  5949. to = builder->CreateDataTypeFromNode(node->firstChild, script);
  5950. to = builder->ModifyDataTypeFromNode(to, node->firstChild->next, script, 0, 0);
  5951. // If the type support object handles, then use it
  5952. if( to.SupportHandles() )
  5953. {
  5954. to.MakeHandle(true);
  5955. }
  5956. else if( !to.IsObjectHandle() )
  5957. {
  5958. // The cast<type> operator can only be used for reference casts
  5959. Error(TXT_ILLEGAL_TARGET_TYPE_FOR_REF_CAST, node->firstChild);
  5960. anyErrors = true;
  5961. }
  5962. }
  5963. // Do not allow casting to non shared type if we're compiling a shared method
  5964. if( outFunc->objectType && outFunc->objectType->IsShared() &&
  5965. to.GetObjectType() && !to.GetObjectType()->IsShared() )
  5966. {
  5967. asCString msg;
  5968. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, to.GetObjectType()->name.AddressOf());
  5969. Error(msg.AddressOf(), node);
  5970. anyErrors = true;
  5971. }
  5972. if( anyErrors )
  5973. {
  5974. // Assume that the error can be fixed and allow the compilation to continue
  5975. ctx->type.SetConstantDW(to, 0);
  5976. return;
  5977. }
  5978. ProcessPropertyGetAccessor(&expr, node);
  5979. // We don't want a reference
  5980. if( expr.type.dataType.IsReference() )
  5981. {
  5982. if( expr.type.dataType.IsObject() )
  5983. {
  5984. // ASHANDLE is actually a value type, even though it looks like a handle
  5985. // For this reason we shouldn't dereference it, unless it is on the heap
  5986. if( !(expr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) ||
  5987. (expr.type.isVariable && IsVariableOnHeap(expr.type.stackOffset)) )
  5988. Dereference(&expr, true);
  5989. }
  5990. else
  5991. ConvertToVariable(&expr);
  5992. }
  5993. ImplicitConversion(&expr, to, node, convType);
  5994. IsVariableInitialized(&expr.type, node);
  5995. // If no type conversion is really tried ignore it
  5996. if( to == expr.type.dataType )
  5997. {
  5998. // This will keep information about constant type
  5999. MergeExprBytecode(ctx, &expr);
  6000. ctx->type = expr.type;
  6001. return;
  6002. }
  6003. if( to.IsEqualExceptConst(expr.type.dataType) && to.IsPrimitive() )
  6004. {
  6005. MergeExprBytecode(ctx, &expr);
  6006. ctx->type = expr.type;
  6007. ctx->type.dataType.MakeReadOnly(true);
  6008. return;
  6009. }
  6010. // The implicit conversion already does most of the conversions permitted,
  6011. // here we'll only treat those conversions that require an explicit cast.
  6012. bool conversionOK = false;
  6013. if( !expr.type.isConstant )
  6014. {
  6015. if( !expr.type.dataType.IsObject() )
  6016. ConvertToTempVariable(&expr);
  6017. if( to.IsObjectHandle() &&
  6018. expr.type.dataType.IsObjectHandle() &&
  6019. !(!to.IsHandleToConst() && expr.type.dataType.IsHandleToConst()) )
  6020. {
  6021. conversionOK = CompileRefCast(&expr, to, true, node);
  6022. MergeExprBytecode(ctx, &expr);
  6023. ctx->type = expr.type;
  6024. }
  6025. }
  6026. if( conversionOK )
  6027. return;
  6028. // Conversion not available
  6029. ctx->type.SetDummy();
  6030. asCString strTo, strFrom;
  6031. strTo = to.Format();
  6032. strFrom = expr.type.dataType.Format();
  6033. asCString msg;
  6034. msg.Format(TXT_NO_CONVERSION_s_TO_s, strFrom.AddressOf(), strTo.AddressOf());
  6035. Error(msg.AddressOf(), node);
  6036. }
  6037. void asCCompiler::AfterFunctionCall(int funcID, asCArray<asSExprContext*> &args, asSExprContext *ctx, bool deferAll)
  6038. {
  6039. asCScriptFunction *descr = builder->GetFunctionDescription(funcID);
  6040. // Parameters that are sent by reference should be assigned
  6041. // to the evaluated expression if it is an lvalue
  6042. // Evaluate the arguments from last to first
  6043. int n = (int)descr->parameterTypes.GetLength() - 1;
  6044. for( ; n >= 0; n-- )
  6045. {
  6046. if( (descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] & asTM_OUTREF)) ||
  6047. (descr->parameterTypes[n].IsObject() && deferAll) )
  6048. {
  6049. asASSERT( !(descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] == asTM_OUTREF)) || args[n]->origExpr );
  6050. // For &inout, only store the argument if it is for a temporary variable
  6051. if( engine->ep.allowUnsafeReferences ||
  6052. descr->inOutFlags[n] != asTM_INOUTREF || args[n]->type.isTemporary )
  6053. {
  6054. // Store the argument for later processing
  6055. asSDeferredParam outParam;
  6056. outParam.argNode = args[n]->exprNode;
  6057. outParam.argType = args[n]->type;
  6058. outParam.argInOutFlags = descr->inOutFlags[n];
  6059. outParam.origExpr = args[n]->origExpr;
  6060. ctx->deferredParams.PushLast(outParam);
  6061. }
  6062. }
  6063. else
  6064. {
  6065. // Release the temporary variable now
  6066. ReleaseTemporaryVariable(args[n]->type, &ctx->bc);
  6067. }
  6068. // Move the argument's deferred expressions over to the final expression
  6069. for( asUINT m = 0; m < args[n]->deferredParams.GetLength(); m++ )
  6070. {
  6071. ctx->deferredParams.PushLast(args[n]->deferredParams[m]);
  6072. args[n]->deferredParams[m].origExpr = 0;
  6073. }
  6074. args[n]->deferredParams.SetLength(0);
  6075. }
  6076. }
  6077. void asCCompiler::ProcessDeferredParams(asSExprContext *ctx)
  6078. {
  6079. if( isProcessingDeferredParams ) return;
  6080. isProcessingDeferredParams = true;
  6081. for( asUINT n = 0; n < ctx->deferredParams.GetLength(); n++ )
  6082. {
  6083. asSDeferredParam outParam = ctx->deferredParams[n];
  6084. if( outParam.argInOutFlags < asTM_OUTREF ) // &in, or not reference
  6085. {
  6086. // Just release the variable
  6087. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6088. }
  6089. else if( outParam.argInOutFlags == asTM_OUTREF )
  6090. {
  6091. asSExprContext *expr = outParam.origExpr;
  6092. outParam.origExpr = 0;
  6093. if( outParam.argType.dataType.IsObjectHandle() )
  6094. {
  6095. // Implicitly convert the value to a handle
  6096. if( expr->type.dataType.IsObjectHandle() )
  6097. expr->type.isExplicitHandle = true;
  6098. }
  6099. // Verify that the expression result in a lvalue, or a property accessor
  6100. if( IsLValue(expr->type) || expr->property_get || expr->property_set )
  6101. {
  6102. asSExprContext rctx(engine);
  6103. rctx.type = outParam.argType;
  6104. if( rctx.type.dataType.IsPrimitive() )
  6105. rctx.type.dataType.MakeReference(false);
  6106. else
  6107. {
  6108. rctx.bc.InstrSHORT(asBC_PSF, outParam.argType.stackOffset);
  6109. rctx.type.dataType.MakeReference(IsVariableOnHeap(outParam.argType.stackOffset));
  6110. if( expr->type.isExplicitHandle )
  6111. rctx.type.isExplicitHandle = true;
  6112. }
  6113. asSExprContext o(engine);
  6114. DoAssignment(&o, expr, &rctx, outParam.argNode, outParam.argNode, ttAssignment, outParam.argNode);
  6115. if( !o.type.dataType.IsPrimitive() ) o.bc.Pop(AS_PTR_SIZE);
  6116. MergeExprBytecode(ctx, &o);
  6117. }
  6118. else
  6119. {
  6120. // We must still evaluate the expression
  6121. MergeExprBytecode(ctx, expr);
  6122. if( !expr->type.isConstant || expr->type.IsNullConstant() )
  6123. ctx->bc.Pop(expr->type.dataType.GetSizeOnStackDWords());
  6124. // Give a warning, except if the argument is null which indicate the argument is really to be ignored
  6125. if( !expr->type.IsNullConstant() )
  6126. Warning(TXT_ARG_NOT_LVALUE, outParam.argNode);
  6127. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6128. }
  6129. ReleaseTemporaryVariable(expr->type, &ctx->bc);
  6130. // Delete the original expression context
  6131. asDELETE(expr,asSExprContext);
  6132. }
  6133. else // &inout
  6134. {
  6135. if( outParam.argType.isTemporary )
  6136. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6137. else if( !outParam.argType.isVariable )
  6138. {
  6139. if( outParam.argType.dataType.IsObject() &&
  6140. outParam.argType.dataType.GetBehaviour()->addref &&
  6141. outParam.argType.dataType.GetBehaviour()->release )
  6142. {
  6143. // Release the object handle that was taken to guarantee the reference
  6144. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6145. }
  6146. }
  6147. }
  6148. }
  6149. ctx->deferredParams.SetLength(0);
  6150. isProcessingDeferredParams = false;
  6151. }
  6152. void asCCompiler::CompileConstructCall(asCScriptNode *node, asSExprContext *ctx)
  6153. {
  6154. // The first node is a datatype node
  6155. asCString name;
  6156. asCTypeInfo tempObj;
  6157. bool onHeap = true;
  6158. asCArray<int> funcs;
  6159. // It is possible that the name is really a constructor
  6160. asCDataType dt;
  6161. dt = builder->CreateDataTypeFromNode(node->firstChild, script);
  6162. if( dt.IsPrimitive() )
  6163. {
  6164. // This is a cast to a primitive type
  6165. CompileConversion(node, ctx);
  6166. return;
  6167. }
  6168. // Do not allow constructing non-shared types in shared functions
  6169. if( outFunc->objectType && outFunc->objectType->IsShared() &&
  6170. dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  6171. {
  6172. asCString msg;
  6173. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  6174. Error(msg.AddressOf(), node);
  6175. }
  6176. // Compile the arguments
  6177. asCArray<asSExprContext *> args;
  6178. asCArray<asCTypeInfo> temporaryVariables;
  6179. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6180. {
  6181. // Check for a value cast behaviour
  6182. if( args.GetLength() == 1 && args[0]->type.dataType.GetObjectType() )
  6183. {
  6184. asSExprContext conv(engine);
  6185. conv.type = args[0]->type;
  6186. ImplicitConversion(&conv, dt, node->lastChild, asIC_EXPLICIT_VAL_CAST, false);
  6187. if( conv.type.dataType.IsEqualExceptRef(dt) )
  6188. {
  6189. ImplicitConversion(args[0], dt, node->lastChild, asIC_EXPLICIT_VAL_CAST);
  6190. ctx->bc.AddCode(&args[0]->bc);
  6191. ctx->type = args[0]->type;
  6192. asDELETE(args[0],asSExprContext);
  6193. return;
  6194. }
  6195. }
  6196. // Check for possible constructor/factory
  6197. name = dt.Format();
  6198. asSTypeBehaviour *beh = dt.GetBehaviour();
  6199. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6200. {
  6201. funcs = beh->constructors;
  6202. // Value types and script types are allocated through the constructor
  6203. tempObj.dataType = dt;
  6204. tempObj.stackOffset = (short)AllocateVariable(dt, true);
  6205. tempObj.dataType.MakeReference(true);
  6206. tempObj.isTemporary = true;
  6207. tempObj.isVariable = true;
  6208. onHeap = IsVariableOnHeap(tempObj.stackOffset);
  6209. // Push the address of the object on the stack
  6210. if( onHeap )
  6211. ctx->bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  6212. }
  6213. else
  6214. {
  6215. funcs = beh->factories;
  6216. }
  6217. // Special case: Allow calling func(void) with a void expression.
  6218. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6219. {
  6220. // Evaluate the expression before the function call
  6221. MergeExprBytecode(ctx, args[0]);
  6222. asDELETE(args[0],asSExprContext);
  6223. args.SetLength(0);
  6224. }
  6225. // Special case: If this is an object constructor and there are no arguments use the default constructor.
  6226. // If none has been registered, just allocate the variable and push it on the stack.
  6227. if( args.GetLength() == 0 )
  6228. {
  6229. asSTypeBehaviour *beh = tempObj.dataType.GetBehaviour();
  6230. if( beh && beh->construct == 0 && !(dt.GetObjectType()->flags & asOBJ_REF) )
  6231. {
  6232. // Call the default constructor
  6233. ctx->type = tempObj;
  6234. if( onHeap )
  6235. {
  6236. asASSERT(ctx->bc.GetLastInstr() == asBC_VAR);
  6237. ctx->bc.RemoveLastInstr();
  6238. }
  6239. CallDefaultConstructor(tempObj.dataType, tempObj.stackOffset, IsVariableOnHeap(tempObj.stackOffset), &ctx->bc, node);
  6240. // Push the reference on the stack
  6241. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6242. return;
  6243. }
  6244. }
  6245. MatchFunctions(funcs, args, node, name.AddressOf(), NULL, false);
  6246. if( funcs.GetLength() != 1 )
  6247. {
  6248. // The error was reported by MatchFunctions()
  6249. // Dummy value
  6250. ctx->type.SetDummy();
  6251. }
  6252. else
  6253. {
  6254. int r = asSUCCESS;
  6255. // Add the default values for arguments not explicitly supplied
  6256. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  6257. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  6258. r = CompileDefaultArgs(node, args, func);
  6259. if( r == asSUCCESS )
  6260. {
  6261. asCByteCode objBC(engine);
  6262. PrepareFunctionCall(funcs[0], &ctx->bc, args);
  6263. MoveArgsToStack(funcs[0], &ctx->bc, args, false);
  6264. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6265. {
  6266. // If the object is allocated on the stack, then call the constructor as a normal function
  6267. if( onHeap )
  6268. {
  6269. int offset = 0;
  6270. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  6271. for( asUINT n = 0; n < args.GetLength(); n++ )
  6272. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  6273. ctx->bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  6274. }
  6275. else
  6276. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6277. PerformFunctionCall(funcs[0], ctx, onHeap, &args, tempObj.dataType.GetObjectType());
  6278. // Add tag that the object has been initialized
  6279. ctx->bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  6280. // The constructor doesn't return anything,
  6281. // so we have to manually inform the type of
  6282. // the return value
  6283. ctx->type = tempObj;
  6284. if( !onHeap )
  6285. ctx->type.dataType.MakeReference(false);
  6286. // Push the address of the object on the stack again
  6287. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6288. }
  6289. else
  6290. {
  6291. // Call the factory to create the reference type
  6292. PerformFunctionCall(funcs[0], ctx, false, &args);
  6293. }
  6294. }
  6295. }
  6296. }
  6297. else
  6298. {
  6299. // Failed to compile the argument list, set the result to the dummy type
  6300. ctx->type.SetDummy();
  6301. }
  6302. // Cleanup
  6303. for( asUINT n = 0; n < args.GetLength(); n++ )
  6304. if( args[n] )
  6305. {
  6306. asDELETE(args[n],asSExprContext);
  6307. }
  6308. }
  6309. int asCCompiler::CompileFunctionCall(asCScriptNode *node, asSExprContext *ctx, asCObjectType *objectType, bool objIsConst, const asCString &scope)
  6310. {
  6311. asCString name;
  6312. asCTypeInfo tempObj;
  6313. asCArray<int> funcs;
  6314. int r = -1;
  6315. asCScriptNode *nm = node->lastChild->prev;
  6316. name.Assign(&script->code[nm->tokenPos], nm->tokenLength);
  6317. // First check for a local variable of a function type
  6318. // Must not allow function names, nor global variables to be returned in this instance
  6319. asSExprContext funcPtr(engine);
  6320. if( objectType == 0 )
  6321. r = CompileVariableAccess(name, scope, &funcPtr, node, true, true);
  6322. if( r < 0 )
  6323. {
  6324. if( objectType )
  6325. {
  6326. // If we're compiling a constructor and the name of the function is super then
  6327. // the constructor of the base class is being called.
  6328. // super cannot be prefixed with a scope operator
  6329. if( m_isConstructor && name == SUPER_TOKEN && nm->prev == 0 )
  6330. {
  6331. // If the class is not derived from anyone else, calling super should give an error
  6332. if( objectType->derivedFrom )
  6333. funcs = objectType->derivedFrom->beh.constructors;
  6334. }
  6335. else
  6336. builder->GetObjectMethodDescriptions(name.AddressOf(), objectType, funcs, objIsConst, scope);
  6337. // It is still possible that there is a class member of a function type
  6338. if( funcs.GetLength() == 0 )
  6339. CompileVariableAccess(name, scope, &funcPtr, node, true, true, objectType);
  6340. }
  6341. else
  6342. {
  6343. builder->GetFunctionDescriptions(name.AddressOf(), funcs);
  6344. // TODO: funcdef: It is still possible that there is a global variable of a function type
  6345. }
  6346. }
  6347. else if( !funcPtr.type.dataType.GetFuncDef() )
  6348. {
  6349. // The variable is not a function
  6350. asCString msg;
  6351. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  6352. Error(msg.AddressOf(), node);
  6353. return -1;
  6354. }
  6355. if( funcs.GetLength() == 0 && funcPtr.type.dataType.GetFuncDef() )
  6356. {
  6357. funcs.PushLast(funcPtr.type.dataType.GetFuncDef()->id);
  6358. }
  6359. // Compile the arguments
  6360. asCArray<asSExprContext *> args;
  6361. asCArray<asCTypeInfo> temporaryVariables;
  6362. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6363. {
  6364. // Special case: Allow calling func(void) with a void expression.
  6365. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6366. {
  6367. // Evaluate the expression before the function call
  6368. MergeExprBytecode(ctx, args[0]);
  6369. asDELETE(args[0],asSExprContext);
  6370. args.SetLength(0);
  6371. }
  6372. MatchFunctions(funcs, args, node, name.AddressOf(), objectType, objIsConst, false, true, scope);
  6373. if( funcs.GetLength() != 1 )
  6374. {
  6375. // The error was reported by MatchFunctions()
  6376. // Dummy value
  6377. ctx->type.SetDummy();
  6378. }
  6379. else
  6380. {
  6381. int r = asSUCCESS;
  6382. // Add the default values for arguments not explicitly supplied
  6383. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  6384. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  6385. r = CompileDefaultArgs(node, args, func);
  6386. // TODO: funcdef: Do we have to make sure the handle is stored in a temporary variable, or
  6387. // is it enough to make sure it is in a local variable?
  6388. // For function pointer we must guarantee that the function is safe, i.e.
  6389. // by first storing the function pointer in a local variable (if it isn't already in one)
  6390. if( r == asSUCCESS )
  6391. {
  6392. if( (funcs[0] & 0xFFFF0000) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  6393. {
  6394. if( objectType )
  6395. {
  6396. Dereference(ctx, true); // Dereference the object pointer to access the member
  6397. // The actual function should be called as if a global function
  6398. objectType = 0;
  6399. }
  6400. Dereference(&funcPtr, true);
  6401. ConvertToVariable(&funcPtr);
  6402. ctx->bc.AddCode(&funcPtr.bc);
  6403. if( !funcPtr.type.isTemporary )
  6404. ctx->bc.Pop(AS_PTR_SIZE);
  6405. }
  6406. MakeFunctionCall(ctx, funcs[0], objectType, args, node, false, 0, funcPtr.type.stackOffset);
  6407. // If the function pointer was copied to a local variable for the call, then
  6408. // release it again (temporary local variable)
  6409. if( (funcs[0] & 0xFFFF0000) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  6410. {
  6411. ReleaseTemporaryVariable(funcPtr.type, &ctx->bc);
  6412. }
  6413. }
  6414. }
  6415. }
  6416. else
  6417. {
  6418. // Failed to compile the argument list, set the dummy type and continue compilation
  6419. ctx->type.SetDummy();
  6420. }
  6421. // Cleanup
  6422. for( asUINT n = 0; n < args.GetLength(); n++ )
  6423. if( args[n] )
  6424. {
  6425. asDELETE(args[n],asSExprContext);
  6426. }
  6427. return 0;
  6428. }
  6429. int asCCompiler::CompileExpressionPreOp(asCScriptNode *node, asSExprContext *ctx)
  6430. {
  6431. int op = node->tokenType;
  6432. IsVariableInitialized(&ctx->type, node);
  6433. if( op == ttHandle )
  6434. {
  6435. // Verify that the type allow its handle to be taken
  6436. if( ctx->type.isExplicitHandle ||
  6437. !ctx->type.dataType.IsObject() ||
  6438. !((ctx->type.dataType.GetObjectType()->beh.addref && ctx->type.dataType.GetObjectType()->beh.release) || ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  6439. {
  6440. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  6441. return -1;
  6442. }
  6443. // Objects that are not local variables are not references
  6444. if( !ctx->type.dataType.IsReference() && !(ctx->type.dataType.IsObject() && !ctx->type.isVariable) )
  6445. {
  6446. Error(TXT_NOT_VALID_REFERENCE, node);
  6447. return -1;
  6448. }
  6449. // If this is really an object then the handle created is a const handle
  6450. bool makeConst = !ctx->type.dataType.IsObjectHandle();
  6451. // Mark the type as an object handle
  6452. ctx->type.dataType.MakeHandle(true);
  6453. ctx->type.isExplicitHandle = true;
  6454. if( makeConst )
  6455. ctx->type.dataType.MakeReadOnly(true);
  6456. }
  6457. else if( (op == ttMinus || op == ttBitNot || op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  6458. {
  6459. // Look for the appropriate method
  6460. const char *opName = 0;
  6461. switch( op )
  6462. {
  6463. case ttMinus: opName = "opNeg"; break;
  6464. case ttBitNot: opName = "opCom"; break;
  6465. case ttInc: opName = "opPreInc"; break;
  6466. case ttDec: opName = "opPreDec"; break;
  6467. }
  6468. if( opName )
  6469. {
  6470. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  6471. ProcessPropertyGetAccessor(ctx, node);
  6472. // Is it a const value?
  6473. bool isConst = false;
  6474. if( ctx->type.dataType.IsObjectHandle() )
  6475. isConst = ctx->type.dataType.IsHandleToConst();
  6476. else
  6477. isConst = ctx->type.dataType.IsReadOnly();
  6478. // TODO: If the value isn't const, then first try to find the non const method, and if not found try to find the const method
  6479. // Find the correct method
  6480. asCArray<int> funcs;
  6481. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  6482. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  6483. {
  6484. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  6485. if( func->name == opName &&
  6486. func->parameterTypes.GetLength() == 0 &&
  6487. (!isConst || func->isReadOnly) )
  6488. {
  6489. funcs.PushLast(func->id);
  6490. }
  6491. }
  6492. // Did we find the method?
  6493. if( funcs.GetLength() == 1 )
  6494. {
  6495. asCTypeInfo objType = ctx->type;
  6496. asCArray<asSExprContext *> args;
  6497. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  6498. ReleaseTemporaryVariable(objType, &ctx->bc);
  6499. return 0;
  6500. }
  6501. else if( funcs.GetLength() == 0 )
  6502. {
  6503. asCString str;
  6504. str = asCString(opName) + "()";
  6505. if( isConst )
  6506. str += " const";
  6507. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  6508. Error(str.AddressOf(), node);
  6509. ctx->type.SetDummy();
  6510. return -1;
  6511. }
  6512. else if( funcs.GetLength() > 1 )
  6513. {
  6514. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  6515. PrintMatchingFuncs(funcs, node);
  6516. ctx->type.SetDummy();
  6517. return -1;
  6518. }
  6519. }
  6520. }
  6521. else if( op == ttPlus || op == ttMinus )
  6522. {
  6523. ProcessPropertyGetAccessor(ctx, node);
  6524. asCDataType to = ctx->type.dataType;
  6525. // TODO: The case -2147483648 gives an unecessary warning of changed sign for implicit conversion
  6526. if( ctx->type.dataType.IsUnsignedType() || ctx->type.dataType.IsEnumType() )
  6527. {
  6528. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  6529. to = asCDataType::CreatePrimitive(ttInt8, false);
  6530. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  6531. to = asCDataType::CreatePrimitive(ttInt16, false);
  6532. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  6533. to = asCDataType::CreatePrimitive(ttInt, false);
  6534. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  6535. to = asCDataType::CreatePrimitive(ttInt64, false);
  6536. else
  6537. {
  6538. Error(TXT_INVALID_TYPE, node);
  6539. return -1;
  6540. }
  6541. }
  6542. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  6543. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  6544. if( !ctx->type.isConstant )
  6545. {
  6546. ConvertToTempVariable(ctx);
  6547. asASSERT(!ctx->type.isLValue);
  6548. if( op == ttMinus )
  6549. {
  6550. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6551. ctx->bc.InstrSHORT(asBC_NEGi, ctx->type.stackOffset);
  6552. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  6553. ctx->bc.InstrSHORT(asBC_NEGi64, ctx->type.stackOffset);
  6554. else if( ctx->type.dataType.IsFloatType() )
  6555. ctx->bc.InstrSHORT(asBC_NEGf, ctx->type.stackOffset);
  6556. else if( ctx->type.dataType.IsDoubleType() )
  6557. ctx->bc.InstrSHORT(asBC_NEGd, ctx->type.stackOffset);
  6558. else
  6559. {
  6560. Error(TXT_ILLEGAL_OPERATION, node);
  6561. return -1;
  6562. }
  6563. return 0;
  6564. }
  6565. }
  6566. else
  6567. {
  6568. if( op == ttMinus )
  6569. {
  6570. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6571. ctx->type.intValue = -ctx->type.intValue;
  6572. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  6573. ctx->type.qwordValue = -(asINT64)ctx->type.qwordValue;
  6574. else if( ctx->type.dataType.IsFloatType() )
  6575. ctx->type.floatValue = -ctx->type.floatValue;
  6576. else if( ctx->type.dataType.IsDoubleType() )
  6577. ctx->type.doubleValue = -ctx->type.doubleValue;
  6578. else
  6579. {
  6580. Error(TXT_ILLEGAL_OPERATION, node);
  6581. return -1;
  6582. }
  6583. return 0;
  6584. }
  6585. }
  6586. if( op == ttPlus )
  6587. {
  6588. if( !ctx->type.dataType.IsIntegerType() &&
  6589. !ctx->type.dataType.IsFloatType() &&
  6590. !ctx->type.dataType.IsDoubleType() )
  6591. {
  6592. Error(TXT_ILLEGAL_OPERATION, node);
  6593. return -1;
  6594. }
  6595. }
  6596. }
  6597. else if( op == ttNot )
  6598. {
  6599. if( ctx->type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  6600. {
  6601. if( ctx->type.isConstant )
  6602. {
  6603. ctx->type.dwordValue = (ctx->type.dwordValue == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  6604. return 0;
  6605. }
  6606. ProcessPropertyGetAccessor(ctx, node);
  6607. ConvertToTempVariable(ctx);
  6608. asASSERT(!ctx->type.isLValue);
  6609. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  6610. }
  6611. else
  6612. {
  6613. Error(TXT_ILLEGAL_OPERATION, node);
  6614. return -1;
  6615. }
  6616. }
  6617. else if( op == ttBitNot )
  6618. {
  6619. ProcessPropertyGetAccessor(ctx, node);
  6620. asCDataType to = ctx->type.dataType;
  6621. if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType() )
  6622. {
  6623. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  6624. to = asCDataType::CreatePrimitive(ttUInt8, false);
  6625. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  6626. to = asCDataType::CreatePrimitive(ttUInt16, false);
  6627. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  6628. to = asCDataType::CreatePrimitive(ttUInt, false);
  6629. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  6630. to = asCDataType::CreatePrimitive(ttUInt64, false);
  6631. else
  6632. {
  6633. Error(TXT_INVALID_TYPE, node);
  6634. return -1;
  6635. }
  6636. }
  6637. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  6638. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  6639. if( ctx->type.dataType.IsUnsignedType() )
  6640. {
  6641. if( ctx->type.isConstant )
  6642. {
  6643. ctx->type.qwordValue = ~ctx->type.qwordValue;
  6644. return 0;
  6645. }
  6646. ConvertToTempVariable(ctx);
  6647. asASSERT(!ctx->type.isLValue);
  6648. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6649. ctx->bc.InstrSHORT(asBC_BNOT, ctx->type.stackOffset);
  6650. else
  6651. ctx->bc.InstrSHORT(asBC_BNOT64, ctx->type.stackOffset);
  6652. }
  6653. else
  6654. {
  6655. Error(TXT_ILLEGAL_OPERATION, node);
  6656. return -1;
  6657. }
  6658. }
  6659. else if( op == ttInc || op == ttDec )
  6660. {
  6661. // Need a reference to the primitive that will be updated
  6662. // The result of this expression is the same reference as before
  6663. // Make sure the reference isn't a temporary variable
  6664. if( ctx->type.isTemporary )
  6665. {
  6666. Error(TXT_REF_IS_TEMP, node);
  6667. return -1;
  6668. }
  6669. if( ctx->type.dataType.IsReadOnly() )
  6670. {
  6671. Error(TXT_REF_IS_READ_ONLY, node);
  6672. return -1;
  6673. }
  6674. if( ctx->property_get || ctx->property_set )
  6675. {
  6676. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  6677. return -1;
  6678. }
  6679. if( !ctx->type.isLValue )
  6680. {
  6681. Error(TXT_NOT_LVALUE, node);
  6682. return -1;
  6683. }
  6684. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  6685. ConvertToReference(ctx);
  6686. else if( !ctx->type.dataType.IsReference() )
  6687. {
  6688. Error(TXT_NOT_VALID_REFERENCE, node);
  6689. return -1;
  6690. }
  6691. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  6692. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  6693. {
  6694. if( op == ttInc )
  6695. ctx->bc.Instr(asBC_INCi64);
  6696. else
  6697. ctx->bc.Instr(asBC_DECi64);
  6698. }
  6699. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt, false)) ||
  6700. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt, false)) )
  6701. {
  6702. if( op == ttInc )
  6703. ctx->bc.Instr(asBC_INCi);
  6704. else
  6705. ctx->bc.Instr(asBC_DECi);
  6706. }
  6707. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  6708. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  6709. {
  6710. if( op == ttInc )
  6711. ctx->bc.Instr(asBC_INCi16);
  6712. else
  6713. ctx->bc.Instr(asBC_DECi16);
  6714. }
  6715. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  6716. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  6717. {
  6718. if( op == ttInc )
  6719. ctx->bc.Instr(asBC_INCi8);
  6720. else
  6721. ctx->bc.Instr(asBC_DECi8);
  6722. }
  6723. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttFloat, false)) )
  6724. {
  6725. if( op == ttInc )
  6726. ctx->bc.Instr(asBC_INCf);
  6727. else
  6728. ctx->bc.Instr(asBC_DECf);
  6729. }
  6730. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttDouble, false)) )
  6731. {
  6732. if( op == ttInc )
  6733. ctx->bc.Instr(asBC_INCd);
  6734. else
  6735. ctx->bc.Instr(asBC_DECd);
  6736. }
  6737. else
  6738. {
  6739. Error(TXT_ILLEGAL_OPERATION, node);
  6740. return -1;
  6741. }
  6742. }
  6743. else
  6744. {
  6745. // Unknown operator
  6746. asASSERT(false);
  6747. return -1;
  6748. }
  6749. return 0;
  6750. }
  6751. void asCCompiler::ConvertToReference(asSExprContext *ctx)
  6752. {
  6753. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  6754. {
  6755. ctx->bc.InstrSHORT(asBC_LDV, ctx->type.stackOffset);
  6756. ctx->type.dataType.MakeReference(true);
  6757. ctx->type.SetVariable(ctx->type.dataType, ctx->type.stackOffset, ctx->type.isTemporary);
  6758. }
  6759. }
  6760. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asCScriptNode *node, bool isThisAccess)
  6761. {
  6762. return FindPropertyAccessor(name, ctx, 0, node, isThisAccess);
  6763. }
  6764. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node, bool isThisAccess)
  6765. {
  6766. if( engine->ep.propertyAccessorMode == 0 )
  6767. {
  6768. // Property accessors have been disabled by the application
  6769. return 0;
  6770. }
  6771. int getId = 0, setId = 0;
  6772. asCString getName = "get_" + name;
  6773. asCString setName = "set_" + name;
  6774. asCArray<int> multipleGetFuncs, multipleSetFuncs;
  6775. if( ctx->type.dataType.IsObject() )
  6776. {
  6777. // Check if the object has any methods with the property name prefixed by get_ or set_
  6778. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  6779. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  6780. {
  6781. asCScriptFunction *f = engine->scriptFunctions[ot->methods[n]];
  6782. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  6783. if( f->name == getName && (int)f->parameterTypes.GetLength() == (arg?1:0) )
  6784. {
  6785. if( getId == 0 )
  6786. getId = ot->methods[n];
  6787. else
  6788. {
  6789. if( multipleGetFuncs.GetLength() == 0 )
  6790. multipleGetFuncs.PushLast(getId);
  6791. multipleGetFuncs.PushLast(ot->methods[n]);
  6792. }
  6793. }
  6794. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  6795. if( f->name == setName && (int)f->parameterTypes.GetLength() == (arg?2:1) )
  6796. {
  6797. if( setId == 0 )
  6798. setId = ot->methods[n];
  6799. else
  6800. {
  6801. if( multipleSetFuncs.GetLength() == 0 )
  6802. multipleSetFuncs.PushLast(setId);
  6803. multipleSetFuncs.PushLast(ot->methods[n]);
  6804. }
  6805. }
  6806. }
  6807. }
  6808. else
  6809. {
  6810. // Look for appropriate global functions.
  6811. asCArray<int> funcs;
  6812. asUINT n;
  6813. builder->GetFunctionDescriptions(getName.AddressOf(), funcs);
  6814. for( n = 0; n < funcs.GetLength(); n++ )
  6815. {
  6816. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  6817. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  6818. if( (int)f->parameterTypes.GetLength() == (arg?1:0) )
  6819. {
  6820. if( getId == 0 )
  6821. getId = funcs[n];
  6822. else
  6823. {
  6824. if( multipleGetFuncs.GetLength() == 0 )
  6825. multipleGetFuncs.PushLast(getId);
  6826. multipleGetFuncs.PushLast(funcs[n]);
  6827. }
  6828. }
  6829. }
  6830. funcs.SetLength(0);
  6831. builder->GetFunctionDescriptions(setName.AddressOf(), funcs);
  6832. for( n = 0; n < funcs.GetLength(); n++ )
  6833. {
  6834. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  6835. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  6836. if( (int)f->parameterTypes.GetLength() == (arg?2:1) )
  6837. {
  6838. if( setId == 0 )
  6839. setId = funcs[n];
  6840. else
  6841. {
  6842. if( multipleSetFuncs.GetLength() == 0 )
  6843. multipleSetFuncs.PushLast(getId);
  6844. multipleSetFuncs.PushLast(funcs[n]);
  6845. }
  6846. }
  6847. }
  6848. }
  6849. // Check for multiple matches
  6850. if( multipleGetFuncs.GetLength() > 0 )
  6851. {
  6852. asCString str;
  6853. str.Format(TXT_MULTIPLE_PROP_GET_ACCESSOR_FOR_s, name.AddressOf());
  6854. Error(str.AddressOf(), node);
  6855. PrintMatchingFuncs(multipleGetFuncs, node);
  6856. return -1;
  6857. }
  6858. if( multipleSetFuncs.GetLength() > 0 )
  6859. {
  6860. asCString str;
  6861. str.Format(TXT_MULTIPLE_PROP_SET_ACCESSOR_FOR_s, name.AddressOf());
  6862. Error(str.AddressOf(), node);
  6863. PrintMatchingFuncs(multipleSetFuncs, node);
  6864. return -1;
  6865. }
  6866. // Check for type compatibility between get and set accessor
  6867. if( getId && setId )
  6868. {
  6869. asCScriptFunction *getFunc = builder->GetFunctionDescription(getId);
  6870. asCScriptFunction *setFunc = builder->GetFunctionDescription(setId);
  6871. // It is permitted for a getter to return a handle and the setter to take a reference
  6872. int idx = (arg?1:0);
  6873. if( !getFunc->returnType.IsEqualExceptRefAndConst(setFunc->parameterTypes[idx]) &&
  6874. !((getFunc->returnType.IsObjectHandle() && !setFunc->parameterTypes[idx].IsObjectHandle()) &&
  6875. (getFunc->returnType.GetObjectType() == setFunc->parameterTypes[idx].GetObjectType())) )
  6876. {
  6877. asCString str;
  6878. str.Format(TXT_GET_SET_ACCESSOR_TYPE_MISMATCH_FOR_s, name.AddressOf());
  6879. Error(str.AddressOf(), node);
  6880. asCArray<int> funcs;
  6881. funcs.PushLast(getId);
  6882. funcs.PushLast(setId);
  6883. PrintMatchingFuncs(funcs, node);
  6884. return -1;
  6885. }
  6886. }
  6887. // Check if we are within one of the accessors
  6888. int realGetId = getId;
  6889. int realSetId = setId;
  6890. if( outFunc->objectType && isThisAccess )
  6891. {
  6892. // The property accessors would be virtual functions, so we need to find the real implementation
  6893. asCScriptFunction *getFunc = getId ? builder->GetFunctionDescription(getId) : 0;
  6894. if( getFunc &&
  6895. getFunc->funcType == asFUNC_VIRTUAL &&
  6896. outFunc->objectType->DerivesFrom(getFunc->objectType) )
  6897. realGetId = outFunc->objectType->virtualFunctionTable[getFunc->vfTableIdx]->id;
  6898. asCScriptFunction *setFunc = setId ? builder->GetFunctionDescription(setId) : 0;
  6899. if( setFunc &&
  6900. setFunc->funcType == asFUNC_VIRTUAL &&
  6901. outFunc->objectType->DerivesFrom(setFunc->objectType) )
  6902. realSetId = outFunc->objectType->virtualFunctionTable[setFunc->vfTableIdx]->id;
  6903. }
  6904. // Avoid recursive call, by not treating this as a property accessor call.
  6905. // This will also allow having the real property with the same name as the accessors.
  6906. if( (isThisAccess || outFunc->objectType == 0) &&
  6907. ((realGetId && realGetId == outFunc->id) ||
  6908. (realSetId && realSetId == outFunc->id)) )
  6909. {
  6910. getId = 0;
  6911. setId = 0;
  6912. }
  6913. // Check if the application has disabled script written property accessors
  6914. if( engine->ep.propertyAccessorMode == 1 )
  6915. {
  6916. if( getId && builder->GetFunctionDescription(getId)->funcType != asFUNC_SYSTEM )
  6917. getId = 0;
  6918. if( setId && builder->GetFunctionDescription(setId)->funcType != asFUNC_SYSTEM )
  6919. setId = 0;
  6920. }
  6921. if( getId || setId )
  6922. {
  6923. // Property accessors were found, but we don't know which is to be used yet, so
  6924. // we just prepare the bytecode for the method call, and then store the function ids
  6925. // so that the right one can be used when we get there.
  6926. ctx->property_get = getId;
  6927. ctx->property_set = setId;
  6928. if( ctx->type.dataType.IsObject() )
  6929. {
  6930. // If the object is read-only then we need to remember that
  6931. if( (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) ||
  6932. (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) )
  6933. ctx->property_const = true;
  6934. else
  6935. ctx->property_const = false;
  6936. // If the object is a handle then we need to remember that
  6937. ctx->property_handle = ctx->type.dataType.IsObjectHandle();
  6938. ctx->property_ref = ctx->type.dataType.IsReference();
  6939. }
  6940. // The setter's parameter type is used as the property type,
  6941. // unless only the getter is available
  6942. asCDataType dt;
  6943. if( setId )
  6944. dt = builder->GetFunctionDescription(setId)->parameterTypes[(arg?1:0)];
  6945. else
  6946. dt = builder->GetFunctionDescription(getId)->returnType;
  6947. // Just change the type, the context must still maintain information
  6948. // about previous variable offset and the indicator of temporary variable.
  6949. int offset = ctx->type.stackOffset;
  6950. bool isTemp = ctx->type.isTemporary;
  6951. ctx->type.Set(dt);
  6952. ctx->type.stackOffset = (short)offset;
  6953. ctx->type.isTemporary = isTemp;
  6954. ctx->exprNode = node;
  6955. // Store the argument for later use
  6956. if( arg )
  6957. {
  6958. ctx->property_arg = asNEW(asSExprContext)(engine);
  6959. MergeExprBytecodeAndType(ctx->property_arg, arg);
  6960. }
  6961. return 1;
  6962. }
  6963. // No accessor was found
  6964. return 0;
  6965. }
  6966. int asCCompiler::ProcessPropertySetAccessor(asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node)
  6967. {
  6968. // TODO: A lot of this code is similar to ProcessPropertyGetAccessor. Can we unify them?
  6969. if( !ctx->property_set )
  6970. {
  6971. Error(TXT_PROPERTY_HAS_NO_SET_ACCESSOR, node);
  6972. return -1;
  6973. }
  6974. asCTypeInfo objType = ctx->type;
  6975. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_set);
  6976. // Make sure the arg match the property
  6977. asCArray<int> funcs;
  6978. funcs.PushLast(ctx->property_set);
  6979. asCArray<asSExprContext *> args;
  6980. if( ctx->property_arg )
  6981. args.PushLast(ctx->property_arg);
  6982. args.PushLast(arg);
  6983. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  6984. if( funcs.GetLength() == 0 )
  6985. {
  6986. // MatchFunctions already reported the error
  6987. if( ctx->property_arg )
  6988. {
  6989. asDELETE(ctx->property_arg, asSExprContext);
  6990. ctx->property_arg = 0;
  6991. }
  6992. return -1;
  6993. }
  6994. if( func->objectType )
  6995. {
  6996. // Setup the context with the original type so the method call gets built correctly
  6997. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  6998. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  6999. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7000. // Don't allow the call if the object is read-only and the property accessor is not const
  7001. if( ctx->property_const && !func->isReadOnly )
  7002. {
  7003. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  7004. asCArray<int> funcs;
  7005. funcs.PushLast(ctx->property_set);
  7006. PrintMatchingFuncs(funcs, node);
  7007. }
  7008. }
  7009. // Call the accessor
  7010. MakeFunctionCall(ctx, ctx->property_set, func->objectType, args, node);
  7011. if( func->objectType )
  7012. {
  7013. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  7014. if( objType.isTemporary &&
  7015. ctx->type.dataType.IsReference() &&
  7016. !ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7017. {
  7018. // Remember the original object's variable, so that it can be released
  7019. // later on when the reference to its member goes out of scope
  7020. ctx->type.isTemporary = true;
  7021. ctx->type.stackOffset = objType.stackOffset;
  7022. }
  7023. else
  7024. {
  7025. // As the method didn't return a reference to a member
  7026. // we can safely release the original object now
  7027. ReleaseTemporaryVariable(objType, &ctx->bc);
  7028. }
  7029. }
  7030. ctx->property_get = 0;
  7031. ctx->property_set = 0;
  7032. if( ctx->property_arg )
  7033. {
  7034. asDELETE(ctx->property_arg, asSExprContext);
  7035. ctx->property_arg = 0;
  7036. }
  7037. return 0;
  7038. }
  7039. void asCCompiler::ProcessPropertyGetAccessor(asSExprContext *ctx, asCScriptNode *node)
  7040. {
  7041. // If no property accessor has been prepared then don't do anything
  7042. if( !ctx->property_get && !ctx->property_set )
  7043. return;
  7044. if( !ctx->property_get )
  7045. {
  7046. // Raise error on missing accessor
  7047. Error(TXT_PROPERTY_HAS_NO_GET_ACCESSOR, node);
  7048. ctx->type.SetDummy();
  7049. return;
  7050. }
  7051. asCTypeInfo objType = ctx->type;
  7052. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_get);
  7053. // Make sure the arg match the property
  7054. asCArray<int> funcs;
  7055. funcs.PushLast(ctx->property_get);
  7056. asCArray<asSExprContext *> args;
  7057. if( ctx->property_arg )
  7058. args.PushLast(ctx->property_arg);
  7059. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  7060. if( funcs.GetLength() == 0 )
  7061. {
  7062. // MatchFunctions already reported the error
  7063. if( ctx->property_arg )
  7064. {
  7065. asDELETE(ctx->property_arg, asSExprContext);
  7066. ctx->property_arg = 0;
  7067. }
  7068. ctx->type.SetDummy();
  7069. return;
  7070. }
  7071. if( func->objectType )
  7072. {
  7073. // Setup the context with the original type so the method call gets built correctly
  7074. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7075. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7076. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7077. // Don't allow the call if the object is read-only and the property accessor is not const
  7078. if( ctx->property_const && !func->isReadOnly )
  7079. {
  7080. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  7081. asCArray<int> funcs;
  7082. funcs.PushLast(ctx->property_get);
  7083. PrintMatchingFuncs(funcs, node);
  7084. }
  7085. }
  7086. // Call the accessor
  7087. MakeFunctionCall(ctx, ctx->property_get, func->objectType, args, node);
  7088. if( func->objectType )
  7089. {
  7090. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  7091. if( objType.isTemporary &&
  7092. ctx->type.dataType.IsReference() &&
  7093. !ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7094. {
  7095. // Remember the original object's variable, so that it can be released
  7096. // later on when the reference to its member goes out of scope
  7097. ctx->type.isTemporary = true;
  7098. ctx->type.stackOffset = objType.stackOffset;
  7099. }
  7100. else
  7101. {
  7102. // As the method didn't return a reference to a member
  7103. // we can safely release the original object now
  7104. ReleaseTemporaryVariable(objType, &ctx->bc);
  7105. }
  7106. }
  7107. ctx->property_get = 0;
  7108. ctx->property_set = 0;
  7109. if( ctx->property_arg )
  7110. {
  7111. asDELETE(ctx->property_arg, asSExprContext);
  7112. ctx->property_arg = 0;
  7113. }
  7114. }
  7115. int asCCompiler::CompileExpressionPostOp(asCScriptNode *node, asSExprContext *ctx)
  7116. {
  7117. int op = node->tokenType;
  7118. // Check if the variable is initialized (if it indeed is a variable)
  7119. IsVariableInitialized(&ctx->type, node);
  7120. if( (op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  7121. {
  7122. const char *opName = 0;
  7123. switch( op )
  7124. {
  7125. case ttInc: opName = "opPostInc"; break;
  7126. case ttDec: opName = "opPostDec"; break;
  7127. }
  7128. if( opName )
  7129. {
  7130. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  7131. ProcessPropertyGetAccessor(ctx, node);
  7132. // Is it a const value?
  7133. bool isConst = false;
  7134. if( ctx->type.dataType.IsObjectHandle() )
  7135. isConst = ctx->type.dataType.IsHandleToConst();
  7136. else
  7137. isConst = ctx->type.dataType.IsReadOnly();
  7138. // TODO: If the value isn't const, then first try to find the non const method, and if not found try to find the const method
  7139. // Find the correct method
  7140. asCArray<int> funcs;
  7141. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  7142. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7143. {
  7144. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  7145. if( func->name == opName &&
  7146. func->parameterTypes.GetLength() == 0 &&
  7147. (!isConst || func->isReadOnly) )
  7148. {
  7149. funcs.PushLast(func->id);
  7150. }
  7151. }
  7152. // Did we find the method?
  7153. if( funcs.GetLength() == 1 )
  7154. {
  7155. asCTypeInfo objType = ctx->type;
  7156. asCArray<asSExprContext *> args;
  7157. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  7158. ReleaseTemporaryVariable(objType, &ctx->bc);
  7159. return 0;
  7160. }
  7161. else if( funcs.GetLength() == 0 )
  7162. {
  7163. asCString str;
  7164. str = asCString(opName) + "()";
  7165. if( isConst )
  7166. str += " const";
  7167. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  7168. Error(str.AddressOf(), node);
  7169. ctx->type.SetDummy();
  7170. return -1;
  7171. }
  7172. else if( funcs.GetLength() > 1 )
  7173. {
  7174. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  7175. PrintMatchingFuncs(funcs, node);
  7176. ctx->type.SetDummy();
  7177. return -1;
  7178. }
  7179. }
  7180. }
  7181. else if( op == ttInc || op == ttDec )
  7182. {
  7183. // Make sure the reference isn't a temporary variable
  7184. if( ctx->type.isTemporary )
  7185. {
  7186. Error(TXT_REF_IS_TEMP, node);
  7187. return -1;
  7188. }
  7189. if( ctx->type.dataType.IsReadOnly() )
  7190. {
  7191. Error(TXT_REF_IS_READ_ONLY, node);
  7192. return -1;
  7193. }
  7194. if( ctx->property_get || ctx->property_set )
  7195. {
  7196. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  7197. return -1;
  7198. }
  7199. if( !ctx->type.isLValue )
  7200. {
  7201. Error(TXT_NOT_LVALUE, node);
  7202. return -1;
  7203. }
  7204. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  7205. ConvertToReference(ctx);
  7206. else if( !ctx->type.dataType.IsReference() )
  7207. {
  7208. Error(TXT_NOT_VALID_REFERENCE, node);
  7209. return -1;
  7210. }
  7211. // Copy the value to a temp before changing it
  7212. ConvertToTempVariable(ctx);
  7213. asASSERT(!ctx->type.isLValue);
  7214. // Increment the value pointed to by the reference still in the register
  7215. asEBCInstr iInc = asBC_INCi, iDec = asBC_DECi;
  7216. if( ctx->type.dataType.IsDoubleType() )
  7217. {
  7218. iInc = asBC_INCd;
  7219. iDec = asBC_DECd;
  7220. }
  7221. else if( ctx->type.dataType.IsFloatType() )
  7222. {
  7223. iInc = asBC_INCf;
  7224. iDec = asBC_DECf;
  7225. }
  7226. else if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() )
  7227. {
  7228. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  7229. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  7230. {
  7231. iInc = asBC_INCi16;
  7232. iDec = asBC_DECi16;
  7233. }
  7234. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  7235. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  7236. {
  7237. iInc = asBC_INCi8;
  7238. iDec = asBC_DECi8;
  7239. }
  7240. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  7241. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  7242. {
  7243. iInc = asBC_INCi64;
  7244. iDec = asBC_DECi64;
  7245. }
  7246. }
  7247. else
  7248. {
  7249. Error(TXT_ILLEGAL_OPERATION, node);
  7250. return -1;
  7251. }
  7252. if( op == ttInc ) ctx->bc.Instr(iInc); else ctx->bc.Instr(iDec);
  7253. }
  7254. else if( op == ttDot )
  7255. {
  7256. if( node->firstChild->nodeType == snIdentifier )
  7257. {
  7258. ProcessPropertyGetAccessor(ctx, node);
  7259. // Get the property name
  7260. asCString name(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  7261. // We need to look for get/set property accessors.
  7262. // If found, the context stores information on the get/set accessors
  7263. // until it is known which is to be used.
  7264. int r = 0;
  7265. if( node->next && node->next->tokenType == ttOpenBracket )
  7266. {
  7267. // The property accessor should take an index arg
  7268. asSExprContext dummyArg(engine);
  7269. r = FindPropertyAccessor(name, ctx, &dummyArg, node);
  7270. }
  7271. if( r == 0 )
  7272. r = FindPropertyAccessor(name, ctx, node);
  7273. if( r != 0 )
  7274. return r;
  7275. if( !ctx->type.dataType.IsPrimitive() )
  7276. Dereference(ctx, true);
  7277. if( ctx->type.dataType.IsObjectHandle() )
  7278. {
  7279. // Convert the handle to a normal object
  7280. asCDataType dt = ctx->type.dataType;
  7281. dt.MakeHandle(false);
  7282. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  7283. // The handle may not have been an lvalue, but the dereferenced object is
  7284. ctx->type.isLValue = true;
  7285. }
  7286. // Find the property offset and type
  7287. if( ctx->type.dataType.IsObject() )
  7288. {
  7289. bool isConst = ctx->type.dataType.IsReadOnly();
  7290. asCObjectProperty *prop = builder->GetObjectProperty(ctx->type.dataType, name.AddressOf());
  7291. if( prop )
  7292. {
  7293. // Is the property access allowed?
  7294. if( prop->isPrivate && (!outFunc || outFunc->objectType != ctx->type.dataType.GetObjectType()) )
  7295. {
  7296. asCString msg;
  7297. msg.Format(TXT_PRIVATE_PROP_ACCESS_s, name.AddressOf());
  7298. Error(msg.AddressOf(), node);
  7299. }
  7300. // Put the offset on the stack
  7301. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(ctx->type.dataType.GetObjectType(), false)));
  7302. if( prop->type.IsReference() )
  7303. ctx->bc.Instr(asBC_RDSPTR);
  7304. // Reference to primitive must be stored in the temp register
  7305. if( prop->type.IsPrimitive() )
  7306. {
  7307. ctx->bc.Instr(asBC_PopRPtr);
  7308. }
  7309. // Set the new type (keeping info about temp variable)
  7310. ctx->type.dataType = prop->type;
  7311. ctx->type.dataType.MakeReference(true);
  7312. ctx->type.isVariable = false;
  7313. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  7314. {
  7315. // Objects that are members are not references
  7316. ctx->type.dataType.MakeReference(false);
  7317. }
  7318. ctx->type.dataType.MakeReadOnly(isConst ? true : prop->type.IsReadOnly());
  7319. }
  7320. else
  7321. {
  7322. asCString str;
  7323. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  7324. Error(str.AddressOf(), node);
  7325. return -1;
  7326. }
  7327. }
  7328. else
  7329. {
  7330. asCString str;
  7331. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  7332. Error(str.AddressOf(), node);
  7333. return -1;
  7334. }
  7335. }
  7336. else
  7337. {
  7338. // Make sure it is an object we are accessing
  7339. if( !ctx->type.dataType.IsObject() )
  7340. {
  7341. asCString str;
  7342. str.Format(TXT_ILLEGAL_OPERATION_ON_s, ctx->type.dataType.Format().AddressOf());
  7343. Error(str.AddressOf(), node);
  7344. return -1;
  7345. }
  7346. // Process the get property accessor
  7347. ProcessPropertyGetAccessor(ctx, node);
  7348. bool isConst = false;
  7349. if( ctx->type.dataType.IsObjectHandle() )
  7350. isConst = ctx->type.dataType.IsHandleToConst();
  7351. else
  7352. isConst = ctx->type.dataType.IsReadOnly();
  7353. asCObjectType *trueObj = ctx->type.dataType.GetObjectType();
  7354. asCTypeInfo objType = ctx->type;
  7355. // Compile function call
  7356. int r = CompileFunctionCall(node->firstChild, ctx, trueObj, isConst);
  7357. if( r < 0 ) return r;
  7358. // If the method returned a reference, then we can't release the original
  7359. // object yet, because the reference may be to a member of it
  7360. if( objType.isTemporary &&
  7361. (ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) &&
  7362. !ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7363. {
  7364. // Remember the original object's variable, so that it can be released
  7365. // later on when the reference to its member goes out of scope
  7366. ctx->type.isTemporary = true;
  7367. ctx->type.stackOffset = objType.stackOffset;
  7368. }
  7369. else
  7370. {
  7371. // As the method didn't return a reference to a member
  7372. // we can safely release the original object now
  7373. ReleaseTemporaryVariable(objType, &ctx->bc);
  7374. }
  7375. }
  7376. }
  7377. else if( op == ttOpenBracket )
  7378. {
  7379. // If the property access takes an index arg, then we should use that instead of processing it now
  7380. asCString propertyName;
  7381. if( (ctx->property_get && builder->GetFunctionDescription(ctx->property_get)->GetParamCount() == 1) ||
  7382. (ctx->property_set && builder->GetFunctionDescription(ctx->property_set)->GetParamCount() == 2) )
  7383. {
  7384. // Determine the name of the property accessor
  7385. asCScriptFunction *func = 0;
  7386. if( ctx->property_get )
  7387. func = builder->GetFunctionDescription(ctx->property_get);
  7388. else
  7389. func = builder->GetFunctionDescription(ctx->property_set);
  7390. propertyName = func->GetName();
  7391. propertyName = propertyName.SubString(4);
  7392. // Set the original type of the expression so we can re-evaluate the property accessor
  7393. if( func->objectType )
  7394. {
  7395. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7396. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7397. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7398. }
  7399. ctx->property_get = ctx->property_set = 0;
  7400. if( ctx->property_arg )
  7401. {
  7402. asDELETE(ctx->property_arg, asSExprContext);
  7403. ctx->property_arg = 0;
  7404. }
  7405. }
  7406. else
  7407. {
  7408. if( !ctx->type.dataType.IsObject() )
  7409. {
  7410. asCString str;
  7411. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  7412. Error(str.AddressOf(), node);
  7413. return -1;
  7414. }
  7415. ProcessPropertyGetAccessor(ctx, node);
  7416. }
  7417. Dereference(ctx, true);
  7418. // Compile the expression
  7419. asSExprContext expr(engine);
  7420. CompileAssignment(node->firstChild, &expr);
  7421. // Check for the existence of the opIndex method
  7422. asSExprContext lctx(engine);
  7423. MergeExprBytecodeAndType(&lctx, ctx);
  7424. int r = 0;
  7425. if( propertyName == "" )
  7426. r = CompileOverloadedDualOperator2(node, "opIndex", &lctx, &expr, ctx);
  7427. if( r == 0 )
  7428. {
  7429. // Check for accessors methods for the opIndex
  7430. r = FindPropertyAccessor(propertyName == "" ? "opIndex" : propertyName.AddressOf(), &lctx, &expr, node);
  7431. if( r == 0 )
  7432. {
  7433. asCString str;
  7434. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  7435. Error(str.AddressOf(), node);
  7436. return -1;
  7437. }
  7438. else if( r < 0 )
  7439. return -1;
  7440. MergeExprBytecodeAndType(ctx, &lctx);
  7441. }
  7442. }
  7443. return 0;
  7444. }
  7445. int asCCompiler::GetPrecedence(asCScriptNode *op)
  7446. {
  7447. // x * y, x / y, x % y
  7448. // x + y, x - y
  7449. // x <= y, x < y, x >= y, x > y
  7450. // x = =y, x != y, x xor y, x is y, x !is y
  7451. // x and y
  7452. // x or y
  7453. // The following are not used in this function,
  7454. // but should have lower precedence than the above
  7455. // x ? y : z
  7456. // x = y
  7457. // The expression term have the highest precedence
  7458. if( op->nodeType == snExprTerm )
  7459. return 1;
  7460. // Evaluate operators by token
  7461. int tokenType = op->tokenType;
  7462. if( tokenType == ttStar || tokenType == ttSlash || tokenType == ttPercent )
  7463. return 0;
  7464. if( tokenType == ttPlus || tokenType == ttMinus )
  7465. return -1;
  7466. if( tokenType == ttBitShiftLeft ||
  7467. tokenType == ttBitShiftRight ||
  7468. tokenType == ttBitShiftRightArith )
  7469. return -2;
  7470. if( tokenType == ttAmp )
  7471. return -3;
  7472. if( tokenType == ttBitXor )
  7473. return -4;
  7474. if( tokenType == ttBitOr )
  7475. return -5;
  7476. if( tokenType == ttLessThanOrEqual ||
  7477. tokenType == ttLessThan ||
  7478. tokenType == ttGreaterThanOrEqual ||
  7479. tokenType == ttGreaterThan )
  7480. return -6;
  7481. if( tokenType == ttEqual || tokenType == ttNotEqual || tokenType == ttXor || tokenType == ttIs || tokenType == ttNotIs )
  7482. return -7;
  7483. if( tokenType == ttAnd )
  7484. return -8;
  7485. if( tokenType == ttOr )
  7486. return -9;
  7487. // Unknown operator
  7488. asASSERT(false);
  7489. return 0;
  7490. }
  7491. int asCCompiler::MatchArgument(asCArray<int> &funcs, asCArray<int> &matches, const asCTypeInfo *argType, int paramNum, bool allowObjectConstruct)
  7492. {
  7493. bool isExactMatch = false;
  7494. bool isMatchExceptConst = false;
  7495. bool isMatchWithBaseType = false;
  7496. bool isMatchExceptSign = false;
  7497. bool isMatchNotVarType = false;
  7498. asUINT n;
  7499. matches.SetLength(0);
  7500. for( n = 0; n < funcs.GetLength(); n++ )
  7501. {
  7502. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  7503. // Does the function have arguments enough?
  7504. if( (int)desc->parameterTypes.GetLength() <= paramNum )
  7505. continue;
  7506. // Can we make the match by implicit conversion?
  7507. asSExprContext ti(engine);
  7508. ti.type = *argType;
  7509. if( argType->dataType.IsPrimitive() ) ti.type.dataType.MakeReference(false);
  7510. ImplicitConversion(&ti, desc->parameterTypes[paramNum], 0, asIC_IMPLICIT_CONV, false, 0, allowObjectConstruct);
  7511. // If the function parameter is an inout-reference then it must not be possible to call the
  7512. // function with an incorrect argument type, even though the type can normally be converted.
  7513. if( desc->parameterTypes[paramNum].IsReference() &&
  7514. desc->inOutFlags[paramNum] == asTM_INOUTREF &&
  7515. desc->parameterTypes[paramNum].GetTokenType() != ttQuestion )
  7516. {
  7517. if( desc->parameterTypes[paramNum].IsPrimitive() &&
  7518. desc->parameterTypes[paramNum].GetTokenType() != argType->dataType.GetTokenType() )
  7519. continue;
  7520. if( desc->parameterTypes[paramNum].IsEnumType() &&
  7521. desc->parameterTypes[paramNum].GetObjectType() != argType->dataType.GetObjectType() )
  7522. continue;
  7523. }
  7524. // How well does the argument match the function parameter?
  7525. if( desc->parameterTypes[paramNum].IsEqualExceptRef(ti.type.dataType) )
  7526. {
  7527. // Is it an exact match?
  7528. if( argType->dataType.IsEqualExceptRef(ti.type.dataType) )
  7529. {
  7530. if( !isExactMatch ) matches.SetLength(0);
  7531. isExactMatch = true;
  7532. matches.PushLast(funcs[n]);
  7533. continue;
  7534. }
  7535. if( !isExactMatch )
  7536. {
  7537. // Is it a match except const?
  7538. if( argType->dataType.IsEqualExceptRefAndConst(ti.type.dataType) )
  7539. {
  7540. if( !isMatchExceptConst ) matches.SetLength(0);
  7541. isMatchExceptConst = true;
  7542. matches.PushLast(funcs[n]);
  7543. continue;
  7544. }
  7545. if( !isMatchExceptConst )
  7546. {
  7547. // Is it a size promotion, e.g. int8 -> int?
  7548. if( argType->dataType.IsSamePrimitiveBaseType(ti.type.dataType) ||
  7549. (argType->dataType.IsEnumType() && ti.type.dataType.IsIntegerType()) )
  7550. {
  7551. if( !isMatchWithBaseType ) matches.SetLength(0);
  7552. isMatchWithBaseType = true;
  7553. matches.PushLast(funcs[n]);
  7554. continue;
  7555. }
  7556. if( !isMatchWithBaseType )
  7557. {
  7558. // Conversion between signed and unsigned integer is better than between integer and float
  7559. // Is it a match except for sign?
  7560. if( (argType->dataType.IsIntegerType() && ti.type.dataType.IsUnsignedType()) ||
  7561. (argType->dataType.IsUnsignedType() && ti.type.dataType.IsIntegerType()) ||
  7562. (argType->dataType.IsEnumType() && ti.type.dataType.IsUnsignedType()) )
  7563. {
  7564. if( !isMatchExceptSign ) matches.SetLength(0);
  7565. isMatchExceptSign = true;
  7566. matches.PushLast(funcs[n]);
  7567. continue;
  7568. }
  7569. if( !isMatchExceptSign )
  7570. {
  7571. // If there was any match without a var type it has higher priority
  7572. if( desc->parameterTypes[paramNum].GetTokenType() != ttQuestion )
  7573. {
  7574. if( !isMatchNotVarType ) matches.SetLength(0);
  7575. isMatchNotVarType = true;
  7576. matches.PushLast(funcs[n]);
  7577. continue;
  7578. }
  7579. // Implicit conversion to ?& has the smallest priority
  7580. if( !isMatchNotVarType )
  7581. matches.PushLast(funcs[n]);
  7582. }
  7583. }
  7584. }
  7585. }
  7586. }
  7587. }
  7588. return (int)matches.GetLength();
  7589. }
  7590. void asCCompiler::PrepareArgument2(asSExprContext *ctx, asSExprContext *arg, asCDataType *paramType, bool isFunction, int refType, asCArray<int> *reservedVars)
  7591. {
  7592. // Reference parameters whose value won't be used don't evaluate the expression
  7593. if( paramType->IsReference() && !(refType & asTM_INREF) )
  7594. {
  7595. // Store the original bytecode so that it can be reused when processing the deferred output parameter
  7596. asSExprContext *orig = asNEW(asSExprContext)(engine);
  7597. MergeExprBytecodeAndType(orig, arg);
  7598. arg->origExpr = orig;
  7599. }
  7600. PrepareArgument(paramType, arg, arg->exprNode, isFunction, refType, reservedVars);
  7601. // arg still holds the original expression for output parameters
  7602. ctx->bc.AddCode(&arg->bc);
  7603. }
  7604. bool asCCompiler::CompileOverloadedDualOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  7605. {
  7606. ctx->exprNode = node;
  7607. // What type of operator is it?
  7608. int token = node->tokenType;
  7609. if( token == ttUnrecognizedToken )
  7610. {
  7611. // This happens when the compiler is inferring an assignment
  7612. // operation from another action, for example in preparing a value
  7613. // as a function argument
  7614. token = ttAssignment;
  7615. }
  7616. // boolean operators are not overloadable
  7617. if( token == ttAnd ||
  7618. token == ttOr ||
  7619. token == ttXor )
  7620. return false;
  7621. // Dual operators can also be implemented as class methods
  7622. if( token == ttEqual ||
  7623. token == ttNotEqual )
  7624. {
  7625. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7626. // Find the matching opEquals method
  7627. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  7628. if( r == 0 )
  7629. {
  7630. // Try again by switching the order of the operands
  7631. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  7632. }
  7633. if( r == 1 )
  7634. {
  7635. if( token == ttNotEqual )
  7636. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  7637. // Success, don't continue
  7638. return true;
  7639. }
  7640. else if( r < 0 )
  7641. {
  7642. // Compiler error, don't continue
  7643. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  7644. return true;
  7645. }
  7646. }
  7647. if( token == ttEqual ||
  7648. token == ttNotEqual ||
  7649. token == ttLessThan ||
  7650. token == ttLessThanOrEqual ||
  7651. token == ttGreaterThan ||
  7652. token == ttGreaterThanOrEqual )
  7653. {
  7654. bool swappedOrder = false;
  7655. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7656. // Find the matching opCmp method
  7657. int r = CompileOverloadedDualOperator2(node, "opCmp", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  7658. if( r == 0 )
  7659. {
  7660. // Try again by switching the order of the operands
  7661. swappedOrder = true;
  7662. r = CompileOverloadedDualOperator2(node, "opCmp", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  7663. }
  7664. if( r == 1 )
  7665. {
  7666. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  7667. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  7668. ctx->bc.InstrW_DW(asBC_CMPIi, ctx->type.stackOffset, 0);
  7669. if( token == ttEqual )
  7670. ctx->bc.Instr(asBC_TZ);
  7671. else if( token == ttNotEqual )
  7672. ctx->bc.Instr(asBC_TNZ);
  7673. else if( (token == ttLessThan && !swappedOrder) ||
  7674. (token == ttGreaterThan && swappedOrder) )
  7675. ctx->bc.Instr(asBC_TS);
  7676. else if( (token == ttLessThanOrEqual && !swappedOrder) ||
  7677. (token == ttGreaterThanOrEqual && swappedOrder) )
  7678. ctx->bc.Instr(asBC_TNP);
  7679. else if( (token == ttGreaterThan && !swappedOrder) ||
  7680. (token == ttLessThan && swappedOrder) )
  7681. ctx->bc.Instr(asBC_TP);
  7682. else if( (token == ttGreaterThanOrEqual && !swappedOrder) ||
  7683. (token == ttLessThanOrEqual && swappedOrder) )
  7684. ctx->bc.Instr(asBC_TNS);
  7685. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  7686. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), a, true);
  7687. // Success, don't continue
  7688. return true;
  7689. }
  7690. else if( r < 0 )
  7691. {
  7692. // Compiler error, don't continue
  7693. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  7694. return true;
  7695. }
  7696. }
  7697. // The rest of the operators are not commutative, and doesn't require specific return type
  7698. const char *op = 0, *op_r = 0;
  7699. switch( token )
  7700. {
  7701. case ttPlus: op = "opAdd"; op_r = "opAdd_r"; break;
  7702. case ttMinus: op = "opSub"; op_r = "opSub_r"; break;
  7703. case ttStar: op = "opMul"; op_r = "opMul_r"; break;
  7704. case ttSlash: op = "opDiv"; op_r = "opDiv_r"; break;
  7705. case ttPercent: op = "opMod"; op_r = "opMod_r"; break;
  7706. case ttBitOr: op = "opOr"; op_r = "opOr_r"; break;
  7707. case ttAmp: op = "opAnd"; op_r = "opAnd_r"; break;
  7708. case ttBitXor: op = "opXor"; op_r = "opXor_r"; break;
  7709. case ttBitShiftLeft: op = "opShl"; op_r = "opShl_r"; break;
  7710. case ttBitShiftRight: op = "opShr"; op_r = "opShr_r"; break;
  7711. case ttBitShiftRightArith: op = "opUShr"; op_r = "opUShr_r"; break;
  7712. }
  7713. // TODO: Might be interesting to support a concatenation operator, e.g. ~
  7714. if( op && op_r )
  7715. {
  7716. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7717. // Find the matching operator method
  7718. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  7719. if( r == 0 )
  7720. {
  7721. // Try again by switching the order of the operands, and using the reversed operator
  7722. r = CompileOverloadedDualOperator2(node, op_r, rctx, lctx, ctx);
  7723. }
  7724. if( r == 1 )
  7725. {
  7726. // Success, don't continue
  7727. return true;
  7728. }
  7729. else if( r < 0 )
  7730. {
  7731. // Compiler error, don't continue
  7732. ctx->type.SetDummy();
  7733. return true;
  7734. }
  7735. }
  7736. // Assignment operators
  7737. op = 0;
  7738. switch( token )
  7739. {
  7740. case ttAssignment: op = "opAssign"; break;
  7741. case ttAddAssign: op = "opAddAssign"; break;
  7742. case ttSubAssign: op = "opSubAssign"; break;
  7743. case ttMulAssign: op = "opMulAssign"; break;
  7744. case ttDivAssign: op = "opDivAssign"; break;
  7745. case ttModAssign: op = "opModAssign"; break;
  7746. case ttOrAssign: op = "opOrAssign"; break;
  7747. case ttAndAssign: op = "opAndAssign"; break;
  7748. case ttXorAssign: op = "opXorAssign"; break;
  7749. case ttShiftLeftAssign: op = "opShlAssign"; break;
  7750. case ttShiftRightLAssign: op = "opShrAssign"; break;
  7751. case ttShiftRightAAssign: op = "opUShrAssign"; break;
  7752. }
  7753. if( op )
  7754. {
  7755. // TODO: Shouldn't accept const lvalue with the assignment operators
  7756. // Find the matching operator method
  7757. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  7758. if( r == 1 )
  7759. {
  7760. // Success, don't continue
  7761. return true;
  7762. }
  7763. else if( r < 0 )
  7764. {
  7765. // Compiler error, don't continue
  7766. ctx->type.SetDummy();
  7767. return true;
  7768. }
  7769. }
  7770. // No suitable operator was found
  7771. return false;
  7772. }
  7773. // Returns negative on compile error
  7774. // zero on no matching operator
  7775. // one on matching operator
  7776. int asCCompiler::CompileOverloadedDualOperator2(asCScriptNode *node, const char *methodName, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx, bool specificReturn, const asCDataType &returnType)
  7777. {
  7778. // Find the matching method
  7779. if( lctx->type.dataType.IsObject() &&
  7780. (!lctx->type.isExplicitHandle ||
  7781. lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  7782. {
  7783. // Is the left value a const?
  7784. bool isConst = false;
  7785. if( lctx->type.dataType.IsObjectHandle() )
  7786. isConst = lctx->type.dataType.IsHandleToConst();
  7787. else
  7788. isConst = lctx->type.dataType.IsReadOnly();
  7789. asCArray<int> funcs;
  7790. asCObjectType *ot = lctx->type.dataType.GetObjectType();
  7791. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7792. {
  7793. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  7794. if( func->name == methodName &&
  7795. (!specificReturn || func->returnType == returnType) &&
  7796. func->parameterTypes.GetLength() == 1 &&
  7797. (!isConst || func->isReadOnly) )
  7798. {
  7799. // Make sure the method is accessible by the module
  7800. if( builder->module->accessMask & func->accessMask )
  7801. {
  7802. #ifdef AS_DEPRECATED
  7803. // deprecated since 2011-10-04
  7804. asCConfigGroup *group = engine->FindConfigGroupForFunction(func->id);
  7805. if( !group || group->HasModuleAccess(builder->module->name.AddressOf()) )
  7806. #endif
  7807. funcs.PushLast(func->id);
  7808. }
  7809. }
  7810. }
  7811. // Which is the best matching function?
  7812. asCArray<int> ops;
  7813. MatchArgument(funcs, ops, &rctx->type, 0);
  7814. // If the object is not const, then we need to prioritize non-const methods
  7815. if( !isConst )
  7816. FilterConst(ops);
  7817. // Did we find an operator?
  7818. if( ops.GetLength() == 1 )
  7819. {
  7820. // Process the lctx expression as get accessor
  7821. ProcessPropertyGetAccessor(lctx, node);
  7822. // Merge the bytecode so that it forms lvalue.methodName(rvalue)
  7823. asCTypeInfo objType = lctx->type;
  7824. asCArray<asSExprContext *> args;
  7825. args.PushLast(rctx);
  7826. MergeExprBytecode(ctx, lctx);
  7827. ctx->type = lctx->type;
  7828. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  7829. // If the method returned a reference, then we can't release the original
  7830. // object yet, because the reference may be to a member of it
  7831. if( objType.isTemporary &&
  7832. (ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) &&
  7833. !ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not to a member
  7834. {
  7835. // Remember the object's variable, so that it can be released
  7836. // later on when the reference to its member goes out of scope
  7837. ctx->type.isTemporary = true;
  7838. ctx->type.stackOffset = objType.stackOffset;
  7839. }
  7840. else
  7841. {
  7842. // As the index operator didn't return a reference to a
  7843. // member we can release the original object now
  7844. ReleaseTemporaryVariable(objType, &ctx->bc);
  7845. }
  7846. // Found matching operator
  7847. return 1;
  7848. }
  7849. else if( ops.GetLength() > 1 )
  7850. {
  7851. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  7852. PrintMatchingFuncs(ops, node);
  7853. ctx->type.SetDummy();
  7854. // Compiler error
  7855. return -1;
  7856. }
  7857. }
  7858. // No matching operator
  7859. return 0;
  7860. }
  7861. void asCCompiler::MakeFunctionCall(asSExprContext *ctx, int funcId, asCObjectType *objectType, asCArray<asSExprContext*> &args, asCScriptNode * /*node*/, bool useVariable, int stackOffset, int funcPtrVar)
  7862. {
  7863. if( objectType )
  7864. {
  7865. // The ASHANDLE type is really a value type, so if it is a
  7866. // local variable on the stack it must not be dereferenced
  7867. if( !(objectType->flags & asOBJ_ASHANDLE) ||
  7868. !(ctx->type.isVariable && !IsVariableOnHeap(ctx->type.stackOffset)) )
  7869. Dereference(ctx, true);
  7870. // This following warning was removed as there may be valid reasons
  7871. // for calling non-const methods on temporary objects, and we shouldn't
  7872. // warn when there is no way of removing the warning.
  7873. /*
  7874. // Warn if the method is non-const and the object is temporary
  7875. // since the changes will be lost when the object is destroyed.
  7876. // If the object is accessed through a handle, then it is assumed
  7877. // the object is not temporary, even though the handle is.
  7878. if( ctx->type.isTemporary &&
  7879. !ctx->type.dataType.IsObjectHandle() &&
  7880. !engine->scriptFunctions[funcId]->isReadOnly )
  7881. {
  7882. Warning("A non-const method is called on temporary object. Changes to the object may be lost.", node);
  7883. Information(engine->scriptFunctions[funcId]->GetDeclaration(), node);
  7884. }
  7885. */ }
  7886. asCByteCode objBC(engine);
  7887. objBC.AddCode(&ctx->bc);
  7888. PrepareFunctionCall(funcId, &ctx->bc, args);
  7889. // Verify if any of the args variable offsets are used in the other code.
  7890. // If they are exchange the offset for a new one
  7891. asUINT n;
  7892. for( n = 0; n < args.GetLength(); n++ )
  7893. {
  7894. if( args[n]->type.isTemporary && objBC.IsVarUsed(args[n]->type.stackOffset) )
  7895. {
  7896. // Release the current temporary variable
  7897. ReleaseTemporaryVariable(args[n]->type, 0);
  7898. asCArray<int> usedVars;
  7899. objBC.GetVarsUsed(usedVars);
  7900. ctx->bc.GetVarsUsed(usedVars);
  7901. asCDataType dt = args[n]->type.dataType;
  7902. dt.MakeReference(false);
  7903. int newOffset = AllocateVariableNotIn(dt, true, &usedVars, IsVariableOnHeap(args[n]->type.stackOffset));
  7904. asASSERT( IsVariableOnHeap(args[n]->type.stackOffset) == IsVariableOnHeap(newOffset) );
  7905. ctx->bc.ExchangeVar(args[n]->type.stackOffset, newOffset);
  7906. args[n]->type.stackOffset = (short)newOffset;
  7907. args[n]->type.isTemporary = true;
  7908. args[n]->type.isVariable = true;
  7909. }
  7910. }
  7911. #ifndef AS_OLD
  7912. // If the function will return a value type on the stack, then we must allocate space
  7913. // for that here and push the address on the stack as a hidden argument to the function
  7914. asCScriptFunction *func = builder->GetFunctionDescription(funcId);
  7915. if( func->DoesReturnOnStack() )
  7916. {
  7917. asASSERT(!useVariable);
  7918. useVariable = true;
  7919. stackOffset = AllocateVariable(func->returnType, true);
  7920. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  7921. }
  7922. #endif
  7923. ctx->bc.AddCode(&objBC);
  7924. MoveArgsToStack(funcId, &ctx->bc, args, objectType ? true : false);
  7925. PerformFunctionCall(funcId, ctx, false, &args, 0, useVariable, stackOffset, funcPtrVar);
  7926. }
  7927. int asCCompiler::CompileOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  7928. {
  7929. IsVariableInitialized(&lctx->type, node);
  7930. IsVariableInitialized(&rctx->type, node);
  7931. if( lctx->type.isExplicitHandle || rctx->type.isExplicitHandle ||
  7932. node->tokenType == ttIs || node->tokenType == ttNotIs )
  7933. {
  7934. CompileOperatorOnHandles(node, lctx, rctx, ctx);
  7935. return 0;
  7936. }
  7937. else
  7938. {
  7939. // Compile an overloaded operator for the two operands
  7940. if( CompileOverloadedDualOperator(node, lctx, rctx, ctx) )
  7941. return 0;
  7942. // If both operands are objects, then we shouldn't continue
  7943. if( lctx->type.dataType.IsObject() && rctx->type.dataType.IsObject() )
  7944. {
  7945. asCString str;
  7946. str.Format(TXT_NO_MATCHING_OP_FOUND_FOR_TYPES_s_AND_s, lctx->type.dataType.Format().AddressOf(), rctx->type.dataType.Format().AddressOf());
  7947. Error(str.AddressOf(), node);
  7948. ctx->type.SetDummy();
  7949. return -1;
  7950. }
  7951. // Process the property get accessors (if any)
  7952. ProcessPropertyGetAccessor(lctx, node);
  7953. ProcessPropertyGetAccessor(rctx, node);
  7954. // Make sure we have two variables or constants
  7955. if( lctx->type.dataType.IsReference() ) ConvertToVariableNotIn(lctx, rctx);
  7956. if( rctx->type.dataType.IsReference() ) ConvertToVariableNotIn(rctx, lctx);
  7957. // Make sure lctx doesn't end up with a variable used in rctx
  7958. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  7959. {
  7960. asCArray<int> vars;
  7961. rctx->bc.GetVarsUsed(vars);
  7962. int offset = AllocateVariableNotIn(lctx->type.dataType, true, &vars);
  7963. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  7964. ReleaseTemporaryVariable(offset, 0);
  7965. }
  7966. // Math operators
  7967. // + - * / % += -= *= /= %=
  7968. int op = node->tokenType;
  7969. if( op == ttPlus || op == ttAddAssign ||
  7970. op == ttMinus || op == ttSubAssign ||
  7971. op == ttStar || op == ttMulAssign ||
  7972. op == ttSlash || op == ttDivAssign ||
  7973. op == ttPercent || op == ttModAssign )
  7974. {
  7975. CompileMathOperator(node, lctx, rctx, ctx);
  7976. return 0;
  7977. }
  7978. // Bitwise operators
  7979. // << >> >>> & | ^ <<= >>= >>>= &= |= ^=
  7980. if( op == ttAmp || op == ttAndAssign ||
  7981. op == ttBitOr || op == ttOrAssign ||
  7982. op == ttBitXor || op == ttXorAssign ||
  7983. op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  7984. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  7985. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  7986. {
  7987. CompileBitwiseOperator(node, lctx, rctx, ctx);
  7988. return 0;
  7989. }
  7990. // Comparison operators
  7991. // == != < > <= >=
  7992. if( op == ttEqual || op == ttNotEqual ||
  7993. op == ttLessThan || op == ttLessThanOrEqual ||
  7994. op == ttGreaterThan || op == ttGreaterThanOrEqual )
  7995. {
  7996. CompileComparisonOperator(node, lctx, rctx, ctx);
  7997. return 0;
  7998. }
  7999. // Boolean operators
  8000. // && || ^^
  8001. if( op == ttAnd || op == ttOr || op == ttXor )
  8002. {
  8003. CompileBooleanOperator(node, lctx, rctx, ctx);
  8004. return 0;
  8005. }
  8006. }
  8007. asASSERT(false);
  8008. return -1;
  8009. }
  8010. void asCCompiler::ConvertToTempVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  8011. {
  8012. asCArray<int> excludeVars;
  8013. if( exclude ) exclude->bc.GetVarsUsed(excludeVars);
  8014. ConvertToTempVariableNotIn(ctx, &excludeVars);
  8015. }
  8016. void asCCompiler::ConvertToTempVariableNotIn(asSExprContext *ctx, asCArray<int> *reservedVars)
  8017. {
  8018. // This is only used for primitive types and null handles
  8019. asASSERT( ctx->type.dataType.IsPrimitive() || ctx->type.dataType.IsNullHandle() );
  8020. ConvertToVariableNotIn(ctx, reservedVars);
  8021. if( !ctx->type.isTemporary )
  8022. {
  8023. if( ctx->type.dataType.IsPrimitive() )
  8024. {
  8025. // Copy the variable to a temporary variable
  8026. int offset = AllocateVariableNotIn(ctx->type.dataType, true, reservedVars);
  8027. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8028. ctx->bc.InstrW_W(asBC_CpyVtoV4, offset, ctx->type.stackOffset);
  8029. else
  8030. ctx->bc.InstrW_W(asBC_CpyVtoV8, offset, ctx->type.stackOffset);
  8031. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8032. }
  8033. else
  8034. {
  8035. // We should never get here
  8036. asASSERT(false);
  8037. }
  8038. }
  8039. }
  8040. void asCCompiler::ConvertToTempVariable(asSExprContext *ctx)
  8041. {
  8042. ConvertToTempVariableNotIn(ctx, (asCArray<int>*)0);
  8043. }
  8044. void asCCompiler::ConvertToVariable(asSExprContext *ctx)
  8045. {
  8046. ConvertToVariableNotIn(ctx, (asCArray<int>*)0);
  8047. }
  8048. void asCCompiler::ConvertToVariableNotIn(asSExprContext *ctx, asCArray<int> *reservedVars)
  8049. {
  8050. // We should never get here while the context is still an unprocessed property accessor
  8051. asASSERT(ctx->property_get == 0 && ctx->property_set == 0);
  8052. asCArray<int> excludeVars;
  8053. if( reservedVars ) excludeVars.Concatenate(*reservedVars);
  8054. int offset;
  8055. if( !ctx->type.isVariable &&
  8056. (ctx->type.dataType.IsObjectHandle() ||
  8057. (ctx->type.dataType.IsObject() && ctx->type.dataType.SupportHandles())) )
  8058. {
  8059. offset = AllocateVariableNotIn(ctx->type.dataType, true, &excludeVars);
  8060. if( ctx->type.IsNullConstant() )
  8061. {
  8062. if( ctx->bc.GetLastInstr() == asBC_PshC4 || ctx->bc.GetLastInstr() == asBC_PshC8 )
  8063. ctx->bc.Pop(AS_PTR_SIZE); // Pop the null constant pushed onto the stack
  8064. #ifdef AS_64BIT_PTR
  8065. ctx->bc.InstrSHORT_QW(asBC_SetV8, (short)offset, 0);
  8066. #else
  8067. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, 0);
  8068. #endif
  8069. }
  8070. else
  8071. {
  8072. // Copy the object handle to a variable
  8073. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  8074. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  8075. ctx->bc.Pop(AS_PTR_SIZE);
  8076. }
  8077. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  8078. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8079. ctx->type.dataType.MakeHandle(true);
  8080. }
  8081. else if( (!ctx->type.isVariable || ctx->type.dataType.IsReference()) &&
  8082. ctx->type.dataType.IsPrimitive() )
  8083. {
  8084. if( ctx->type.isConstant )
  8085. {
  8086. offset = AllocateVariableNotIn(ctx->type.dataType, true, &excludeVars);
  8087. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  8088. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, ctx->type.byteValue);
  8089. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  8090. ctx->bc.InstrSHORT_W(asBC_SetV2, (short)offset, ctx->type.wordValue);
  8091. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  8092. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, ctx->type.dwordValue);
  8093. else
  8094. ctx->bc.InstrSHORT_QW(asBC_SetV8, (short)offset, ctx->type.qwordValue);
  8095. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8096. return;
  8097. }
  8098. else
  8099. {
  8100. asASSERT(ctx->type.dataType.IsPrimitive());
  8101. asASSERT(ctx->type.dataType.IsReference());
  8102. ctx->type.dataType.MakeReference(false);
  8103. offset = AllocateVariableNotIn(ctx->type.dataType, true, &excludeVars);
  8104. // Read the value from the address in the register directly into the variable
  8105. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  8106. ctx->bc.InstrSHORT(asBC_RDR1, (short)offset);
  8107. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  8108. ctx->bc.InstrSHORT(asBC_RDR2, (short)offset);
  8109. else if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8110. ctx->bc.InstrSHORT(asBC_RDR4, (short)offset);
  8111. else
  8112. ctx->bc.InstrSHORT(asBC_RDR8, (short)offset);
  8113. }
  8114. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  8115. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8116. }
  8117. }
  8118. void asCCompiler::ConvertToVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  8119. {
  8120. asCArray<int> excludeVars;
  8121. if( exclude ) exclude->bc.GetVarsUsed(excludeVars);
  8122. ConvertToVariableNotIn(ctx, &excludeVars);
  8123. }
  8124. void asCCompiler::CompileMathOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8125. {
  8126. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  8127. // Implicitly convert the operands to a number type
  8128. asCDataType to;
  8129. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  8130. to.SetTokenType(ttDouble);
  8131. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  8132. to.SetTokenType(ttFloat);
  8133. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8134. {
  8135. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() )
  8136. to.SetTokenType(ttInt64);
  8137. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8138. to.SetTokenType(ttUInt64);
  8139. }
  8140. else
  8141. {
  8142. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() ||
  8143. lctx->type.dataType.IsEnumType() || rctx->type.dataType.IsEnumType() )
  8144. to.SetTokenType(ttInt);
  8145. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8146. to.SetTokenType(ttUInt);
  8147. }
  8148. // If doing an operation with double constant and float variable, the constant should be converted to float
  8149. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  8150. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  8151. to.SetTokenType(ttFloat);
  8152. // Do the actual conversion
  8153. asCArray<int> reservedVars;
  8154. rctx->bc.GetVarsUsed(reservedVars);
  8155. lctx->bc.GetVarsUsed(reservedVars);
  8156. if( lctx->type.dataType.IsReference() )
  8157. ConvertToVariableNotIn(lctx, &reservedVars);
  8158. if( rctx->type.dataType.IsReference() )
  8159. ConvertToVariableNotIn(rctx, &reservedVars);
  8160. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8161. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8162. // Verify that the conversion was successful
  8163. if( !lctx->type.dataType.IsIntegerType() &&
  8164. !lctx->type.dataType.IsUnsignedType() &&
  8165. !lctx->type.dataType.IsFloatType() &&
  8166. !lctx->type.dataType.IsDoubleType() )
  8167. {
  8168. asCString str;
  8169. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, lctx->type.dataType.Format().AddressOf());
  8170. Error(str.AddressOf(), node);
  8171. ctx->type.SetDummy();
  8172. return;
  8173. }
  8174. if( !rctx->type.dataType.IsIntegerType() &&
  8175. !rctx->type.dataType.IsUnsignedType() &&
  8176. !rctx->type.dataType.IsFloatType() &&
  8177. !rctx->type.dataType.IsDoubleType() )
  8178. {
  8179. asCString str;
  8180. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, rctx->type.dataType.Format().AddressOf());
  8181. Error(str.AddressOf(), node);
  8182. ctx->type.SetDummy();
  8183. return;
  8184. }
  8185. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8186. // Verify if we are dividing with a constant zero
  8187. int op = node->tokenType;
  8188. if( rctx->type.isConstant && rctx->type.qwordValue == 0 &&
  8189. (op == ttSlash || op == ttDivAssign ||
  8190. op == ttPercent || op == ttModAssign) )
  8191. {
  8192. Error(TXT_DIVIDE_BY_ZERO, node);
  8193. }
  8194. if( !isConstant )
  8195. {
  8196. ConvertToVariableNotIn(lctx, rctx);
  8197. ConvertToVariableNotIn(rctx, lctx);
  8198. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8199. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8200. if( op == ttAddAssign || op == ttSubAssign ||
  8201. op == ttMulAssign || op == ttDivAssign ||
  8202. op == ttModAssign )
  8203. {
  8204. // Merge the operands in the different order so that they are evaluated correctly
  8205. MergeExprBytecode(ctx, rctx);
  8206. MergeExprBytecode(ctx, lctx);
  8207. }
  8208. else
  8209. {
  8210. MergeExprBytecode(ctx, lctx);
  8211. MergeExprBytecode(ctx, rctx);
  8212. }
  8213. ProcessDeferredParams(ctx);
  8214. asEBCInstr instruction = asBC_ADDi;
  8215. if( lctx->type.dataType.IsIntegerType() ||
  8216. lctx->type.dataType.IsUnsignedType() )
  8217. {
  8218. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8219. {
  8220. if( op == ttPlus || op == ttAddAssign )
  8221. instruction = asBC_ADDi;
  8222. else if( op == ttMinus || op == ttSubAssign )
  8223. instruction = asBC_SUBi;
  8224. else if( op == ttStar || op == ttMulAssign )
  8225. instruction = asBC_MULi;
  8226. else if( op == ttSlash || op == ttDivAssign )
  8227. {
  8228. if( lctx->type.dataType.IsIntegerType() )
  8229. instruction = asBC_DIVi;
  8230. else
  8231. instruction = asBC_DIVu;
  8232. }
  8233. else if( op == ttPercent || op == ttModAssign )
  8234. {
  8235. if( lctx->type.dataType.IsIntegerType() )
  8236. instruction = asBC_MODi;
  8237. else
  8238. instruction = asBC_MODu;
  8239. }
  8240. }
  8241. else
  8242. {
  8243. if( op == ttPlus || op == ttAddAssign )
  8244. instruction = asBC_ADDi64;
  8245. else if( op == ttMinus || op == ttSubAssign )
  8246. instruction = asBC_SUBi64;
  8247. else if( op == ttStar || op == ttMulAssign )
  8248. instruction = asBC_MULi64;
  8249. else if( op == ttSlash || op == ttDivAssign )
  8250. {
  8251. if( lctx->type.dataType.IsIntegerType() )
  8252. instruction = asBC_DIVi64;
  8253. else
  8254. instruction = asBC_DIVu64;
  8255. }
  8256. else if( op == ttPercent || op == ttModAssign )
  8257. {
  8258. if( lctx->type.dataType.IsIntegerType() )
  8259. instruction = asBC_MODi64;
  8260. else
  8261. instruction = asBC_MODu64;
  8262. }
  8263. }
  8264. }
  8265. else if( lctx->type.dataType.IsFloatType() )
  8266. {
  8267. if( op == ttPlus || op == ttAddAssign )
  8268. instruction = asBC_ADDf;
  8269. else if( op == ttMinus || op == ttSubAssign )
  8270. instruction = asBC_SUBf;
  8271. else if( op == ttStar || op == ttMulAssign )
  8272. instruction = asBC_MULf;
  8273. else if( op == ttSlash || op == ttDivAssign )
  8274. instruction = asBC_DIVf;
  8275. else if( op == ttPercent || op == ttModAssign )
  8276. instruction = asBC_MODf;
  8277. }
  8278. else if( lctx->type.dataType.IsDoubleType() )
  8279. {
  8280. if( op == ttPlus || op == ttAddAssign )
  8281. instruction = asBC_ADDd;
  8282. else if( op == ttMinus || op == ttSubAssign )
  8283. instruction = asBC_SUBd;
  8284. else if( op == ttStar || op == ttMulAssign )
  8285. instruction = asBC_MULd;
  8286. else if( op == ttSlash || op == ttDivAssign )
  8287. instruction = asBC_DIVd;
  8288. else if( op == ttPercent || op == ttModAssign )
  8289. instruction = asBC_MODd;
  8290. }
  8291. else
  8292. {
  8293. // Shouldn't be possible
  8294. asASSERT(false);
  8295. }
  8296. // Do the operation
  8297. int a = AllocateVariable(lctx->type.dataType, true);
  8298. int b = lctx->type.stackOffset;
  8299. int c = rctx->type.stackOffset;
  8300. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8301. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8302. }
  8303. else
  8304. {
  8305. // Both values are constants
  8306. if( lctx->type.dataType.IsIntegerType() ||
  8307. lctx->type.dataType.IsUnsignedType() )
  8308. {
  8309. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8310. {
  8311. int v = 0;
  8312. if( op == ttPlus )
  8313. v = lctx->type.intValue + rctx->type.intValue;
  8314. else if( op == ttMinus )
  8315. v = lctx->type.intValue - rctx->type.intValue;
  8316. else if( op == ttStar )
  8317. v = lctx->type.intValue * rctx->type.intValue;
  8318. else if( op == ttSlash )
  8319. {
  8320. if( rctx->type.intValue == 0 )
  8321. v = 0;
  8322. else
  8323. if( lctx->type.dataType.IsIntegerType() )
  8324. v = lctx->type.intValue / rctx->type.intValue;
  8325. else
  8326. v = lctx->type.dwordValue / rctx->type.dwordValue;
  8327. }
  8328. else if( op == ttPercent )
  8329. {
  8330. if( rctx->type.intValue == 0 )
  8331. v = 0;
  8332. else
  8333. if( lctx->type.dataType.IsIntegerType() )
  8334. v = lctx->type.intValue % rctx->type.intValue;
  8335. else
  8336. v = lctx->type.dwordValue % rctx->type.dwordValue;
  8337. }
  8338. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8339. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  8340. if( lctx->type.dataType.GetTokenType() == ttUInt && op == ttMinus && lctx->type.intValue < rctx->type.intValue )
  8341. ctx->type.dataType.SetTokenType(ttInt);
  8342. }
  8343. else
  8344. {
  8345. asQWORD v = 0;
  8346. if( op == ttPlus )
  8347. v = lctx->type.qwordValue + rctx->type.qwordValue;
  8348. else if( op == ttMinus )
  8349. v = lctx->type.qwordValue - rctx->type.qwordValue;
  8350. else if( op == ttStar )
  8351. v = lctx->type.qwordValue * rctx->type.qwordValue;
  8352. else if( op == ttSlash )
  8353. {
  8354. if( rctx->type.qwordValue == 0 )
  8355. v = 0;
  8356. else
  8357. if( lctx->type.dataType.IsIntegerType() )
  8358. v = asINT64(lctx->type.qwordValue) / asINT64(rctx->type.qwordValue);
  8359. else
  8360. v = lctx->type.qwordValue / rctx->type.qwordValue;
  8361. }
  8362. else if( op == ttPercent )
  8363. {
  8364. if( rctx->type.qwordValue == 0 )
  8365. v = 0;
  8366. else
  8367. if( lctx->type.dataType.IsIntegerType() )
  8368. v = asINT64(lctx->type.qwordValue) % asINT64(rctx->type.qwordValue);
  8369. else
  8370. v = lctx->type.qwordValue % rctx->type.qwordValue;
  8371. }
  8372. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8373. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  8374. if( lctx->type.dataType.GetTokenType() == ttUInt64 && op == ttMinus && lctx->type.qwordValue < rctx->type.qwordValue )
  8375. ctx->type.dataType.SetTokenType(ttInt64);
  8376. }
  8377. }
  8378. else if( lctx->type.dataType.IsFloatType() )
  8379. {
  8380. float v = 0.0f;
  8381. if( op == ttPlus )
  8382. v = lctx->type.floatValue + rctx->type.floatValue;
  8383. else if( op == ttMinus )
  8384. v = lctx->type.floatValue - rctx->type.floatValue;
  8385. else if( op == ttStar )
  8386. v = lctx->type.floatValue * rctx->type.floatValue;
  8387. else if( op == ttSlash )
  8388. {
  8389. if( rctx->type.floatValue == 0 )
  8390. v = 0;
  8391. else
  8392. v = lctx->type.floatValue / rctx->type.floatValue;
  8393. }
  8394. else if( op == ttPercent )
  8395. {
  8396. if( rctx->type.floatValue == 0 )
  8397. v = 0;
  8398. else
  8399. v = fmodf(lctx->type.floatValue, rctx->type.floatValue);
  8400. }
  8401. ctx->type.SetConstantF(lctx->type.dataType, v);
  8402. }
  8403. else if( lctx->type.dataType.IsDoubleType() )
  8404. {
  8405. double v = 0.0;
  8406. if( op == ttPlus )
  8407. v = lctx->type.doubleValue + rctx->type.doubleValue;
  8408. else if( op == ttMinus )
  8409. v = lctx->type.doubleValue - rctx->type.doubleValue;
  8410. else if( op == ttStar )
  8411. v = lctx->type.doubleValue * rctx->type.doubleValue;
  8412. else if( op == ttSlash )
  8413. {
  8414. if( rctx->type.doubleValue == 0 )
  8415. v = 0;
  8416. else
  8417. v = lctx->type.doubleValue / rctx->type.doubleValue;
  8418. }
  8419. else if( op == ttPercent )
  8420. {
  8421. if( rctx->type.doubleValue == 0 )
  8422. v = 0;
  8423. else
  8424. v = fmod(lctx->type.doubleValue, rctx->type.doubleValue);
  8425. }
  8426. ctx->type.SetConstantD(lctx->type.dataType, v);
  8427. }
  8428. else
  8429. {
  8430. // Shouldn't be possible
  8431. asASSERT(false);
  8432. }
  8433. }
  8434. }
  8435. void asCCompiler::CompileBitwiseOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8436. {
  8437. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  8438. int op = node->tokenType;
  8439. if( op == ttAmp || op == ttAndAssign ||
  8440. op == ttBitOr || op == ttOrAssign ||
  8441. op == ttBitXor || op == ttXorAssign )
  8442. {
  8443. // Convert left hand operand to integer if it's not already one
  8444. asCDataType to;
  8445. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 ||
  8446. rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8447. to.SetTokenType(ttUInt64);
  8448. else
  8449. to.SetTokenType(ttUInt);
  8450. // Do the actual conversion
  8451. asCArray<int> reservedVars;
  8452. rctx->bc.GetVarsUsed(reservedVars);
  8453. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8454. // Verify that the conversion was successful
  8455. if( !lctx->type.dataType.IsUnsignedType() )
  8456. {
  8457. asCString str;
  8458. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8459. Error(str.AddressOf(), node);
  8460. }
  8461. // Convert right hand operand to same type as left hand operand
  8462. asCArray<int> vars;
  8463. lctx->bc.GetVarsUsed(vars);
  8464. ImplicitConversion(rctx, lctx->type.dataType, node, asIC_IMPLICIT_CONV, true, &vars);
  8465. if( !rctx->type.dataType.IsEqualExceptRef(lctx->type.dataType) )
  8466. {
  8467. asCString str;
  8468. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  8469. Error(str.AddressOf(), node);
  8470. }
  8471. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8472. if( !isConstant )
  8473. {
  8474. ConvertToVariableNotIn(lctx, rctx);
  8475. ConvertToVariableNotIn(rctx, lctx);
  8476. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8477. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8478. if( op == ttAndAssign || op == ttOrAssign || op == ttXorAssign )
  8479. {
  8480. // Compound assignments execute the right hand value first
  8481. MergeExprBytecode(ctx, rctx);
  8482. MergeExprBytecode(ctx, lctx);
  8483. }
  8484. else
  8485. {
  8486. MergeExprBytecode(ctx, lctx);
  8487. MergeExprBytecode(ctx, rctx);
  8488. }
  8489. ProcessDeferredParams(ctx);
  8490. asEBCInstr instruction = asBC_BAND;
  8491. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8492. {
  8493. if( op == ttAmp || op == ttAndAssign )
  8494. instruction = asBC_BAND;
  8495. else if( op == ttBitOr || op == ttOrAssign )
  8496. instruction = asBC_BOR;
  8497. else if( op == ttBitXor || op == ttXorAssign )
  8498. instruction = asBC_BXOR;
  8499. }
  8500. else
  8501. {
  8502. if( op == ttAmp || op == ttAndAssign )
  8503. instruction = asBC_BAND64;
  8504. else if( op == ttBitOr || op == ttOrAssign )
  8505. instruction = asBC_BOR64;
  8506. else if( op == ttBitXor || op == ttXorAssign )
  8507. instruction = asBC_BXOR64;
  8508. }
  8509. // Do the operation
  8510. int a = AllocateVariable(lctx->type.dataType, true);
  8511. int b = lctx->type.stackOffset;
  8512. int c = rctx->type.stackOffset;
  8513. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8514. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8515. }
  8516. else
  8517. {
  8518. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8519. {
  8520. asQWORD v = 0;
  8521. if( op == ttAmp )
  8522. v = lctx->type.qwordValue & rctx->type.qwordValue;
  8523. else if( op == ttBitOr )
  8524. v = lctx->type.qwordValue | rctx->type.qwordValue;
  8525. else if( op == ttBitXor )
  8526. v = lctx->type.qwordValue ^ rctx->type.qwordValue;
  8527. // Remember the result
  8528. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8529. }
  8530. else
  8531. {
  8532. asDWORD v = 0;
  8533. if( op == ttAmp )
  8534. v = lctx->type.dwordValue & rctx->type.dwordValue;
  8535. else if( op == ttBitOr )
  8536. v = lctx->type.dwordValue | rctx->type.dwordValue;
  8537. else if( op == ttBitXor )
  8538. v = lctx->type.dwordValue ^ rctx->type.dwordValue;
  8539. // Remember the result
  8540. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8541. }
  8542. }
  8543. }
  8544. else if( op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  8545. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  8546. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8547. {
  8548. // Don't permit object to primitive conversion, since we don't know which integer type is the correct one
  8549. if( lctx->type.dataType.IsObject() )
  8550. {
  8551. asCString str;
  8552. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  8553. Error(str.AddressOf(), node);
  8554. // Set an integer value and allow the compiler to continue
  8555. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttInt, true), 0);
  8556. return;
  8557. }
  8558. // Convert left hand operand to integer if it's not already one
  8559. asCDataType to = lctx->type.dataType;
  8560. if( lctx->type.dataType.IsUnsignedType() &&
  8561. lctx->type.dataType.GetSizeInMemoryBytes() < 4 )
  8562. {
  8563. to = asCDataType::CreatePrimitive(ttUInt, false);
  8564. }
  8565. else if( !lctx->type.dataType.IsUnsignedType() )
  8566. {
  8567. asCDataType to;
  8568. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8569. to.SetTokenType(ttInt64);
  8570. else
  8571. to.SetTokenType(ttInt);
  8572. }
  8573. // Do the actual conversion
  8574. asCArray<int> reservedVars;
  8575. rctx->bc.GetVarsUsed(reservedVars);
  8576. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8577. // Verify that the conversion was successful
  8578. if( lctx->type.dataType != to )
  8579. {
  8580. asCString str;
  8581. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8582. Error(str.AddressOf(), node);
  8583. }
  8584. // Right operand must be 32bit uint
  8585. asCArray<int> vars;
  8586. lctx->bc.GetVarsUsed(vars);
  8587. ImplicitConversion(rctx, asCDataType::CreatePrimitive(ttUInt, true), node, asIC_IMPLICIT_CONV, true, &vars);
  8588. if( !rctx->type.dataType.IsUnsignedType() )
  8589. {
  8590. asCString str;
  8591. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "uint");
  8592. Error(str.AddressOf(), node);
  8593. }
  8594. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8595. if( !isConstant )
  8596. {
  8597. ConvertToVariableNotIn(lctx, rctx);
  8598. ConvertToVariableNotIn(rctx, lctx);
  8599. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8600. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8601. if( op == ttShiftLeftAssign || op == ttShiftRightLAssign || op == ttShiftRightAAssign )
  8602. {
  8603. // Compound assignments execute the right hand value first
  8604. MergeExprBytecode(ctx, rctx);
  8605. MergeExprBytecode(ctx, lctx);
  8606. }
  8607. else
  8608. {
  8609. MergeExprBytecode(ctx, lctx);
  8610. MergeExprBytecode(ctx, rctx);
  8611. }
  8612. ProcessDeferredParams(ctx);
  8613. asEBCInstr instruction = asBC_BSLL;
  8614. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8615. {
  8616. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  8617. instruction = asBC_BSLL;
  8618. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  8619. instruction = asBC_BSRL;
  8620. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8621. instruction = asBC_BSRA;
  8622. }
  8623. else
  8624. {
  8625. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  8626. instruction = asBC_BSLL64;
  8627. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  8628. instruction = asBC_BSRL64;
  8629. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8630. instruction = asBC_BSRA64;
  8631. }
  8632. // Do the operation
  8633. int a = AllocateVariable(lctx->type.dataType, true);
  8634. int b = lctx->type.stackOffset;
  8635. int c = rctx->type.stackOffset;
  8636. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8637. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8638. }
  8639. else
  8640. {
  8641. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8642. {
  8643. asDWORD v = 0;
  8644. if( op == ttBitShiftLeft )
  8645. v = lctx->type.dwordValue << rctx->type.dwordValue;
  8646. else if( op == ttBitShiftRight )
  8647. v = lctx->type.dwordValue >> rctx->type.dwordValue;
  8648. else if( op == ttBitShiftRightArith )
  8649. v = lctx->type.intValue >> rctx->type.dwordValue;
  8650. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8651. }
  8652. else
  8653. {
  8654. asQWORD v = 0;
  8655. if( op == ttBitShiftLeft )
  8656. v = lctx->type.qwordValue << rctx->type.dwordValue;
  8657. else if( op == ttBitShiftRight )
  8658. v = lctx->type.qwordValue >> rctx->type.dwordValue;
  8659. else if( op == ttBitShiftRightArith )
  8660. v = asINT64(lctx->type.qwordValue) >> rctx->type.dwordValue;
  8661. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8662. }
  8663. }
  8664. }
  8665. }
  8666. void asCCompiler::CompileComparisonOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8667. {
  8668. // Both operands must be of the same type
  8669. // Implicitly convert the operands to a number type
  8670. asCDataType to;
  8671. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  8672. to.SetTokenType(ttDouble);
  8673. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  8674. to.SetTokenType(ttFloat);
  8675. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8676. {
  8677. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() )
  8678. to.SetTokenType(ttInt64);
  8679. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8680. to.SetTokenType(ttUInt64);
  8681. }
  8682. else
  8683. {
  8684. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() ||
  8685. lctx->type.dataType.IsEnumType() || rctx->type.dataType.IsEnumType() )
  8686. to.SetTokenType(ttInt);
  8687. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8688. to.SetTokenType(ttUInt);
  8689. else if( lctx->type.dataType.IsBooleanType() || rctx->type.dataType.IsBooleanType() )
  8690. to.SetTokenType(ttBool);
  8691. }
  8692. // If doing an operation with double constant and float variable, the constant should be converted to float
  8693. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  8694. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  8695. to.SetTokenType(ttFloat);
  8696. // Is it an operation on signed values?
  8697. bool signMismatch = false;
  8698. if( !lctx->type.dataType.IsUnsignedType() || !rctx->type.dataType.IsUnsignedType() )
  8699. {
  8700. if( lctx->type.dataType.GetTokenType() == ttUInt64 )
  8701. {
  8702. if( !lctx->type.isConstant )
  8703. signMismatch = true;
  8704. else if( lctx->type.qwordValue & (I64(1)<<63) )
  8705. signMismatch = true;
  8706. }
  8707. if( lctx->type.dataType.GetTokenType() == ttUInt )
  8708. {
  8709. if( !lctx->type.isConstant )
  8710. signMismatch = true;
  8711. else if( lctx->type.dwordValue & (1<<31) )
  8712. signMismatch = true;
  8713. }
  8714. if( rctx->type.dataType.GetTokenType() == ttUInt64 )
  8715. {
  8716. if( !rctx->type.isConstant )
  8717. signMismatch = true;
  8718. else if( rctx->type.qwordValue & (I64(1)<<63) )
  8719. signMismatch = true;
  8720. }
  8721. if( rctx->type.dataType.GetTokenType() == ttUInt )
  8722. {
  8723. if( !rctx->type.isConstant )
  8724. signMismatch = true;
  8725. else if( rctx->type.dwordValue & (1<<31) )
  8726. signMismatch = true;
  8727. }
  8728. }
  8729. // Check for signed/unsigned mismatch
  8730. if( signMismatch )
  8731. Warning(TXT_SIGNED_UNSIGNED_MISMATCH, node);
  8732. // Do the actual conversion
  8733. asCArray<int> reservedVars;
  8734. rctx->bc.GetVarsUsed(reservedVars);
  8735. if( lctx->type.dataType.IsReference() )
  8736. ConvertToVariableNotIn(lctx, &reservedVars);
  8737. if( rctx->type.dataType.IsReference() )
  8738. ConvertToVariableNotIn(rctx, &reservedVars);
  8739. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8740. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  8741. // Verify that the conversion was successful
  8742. bool ok = true;
  8743. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  8744. {
  8745. asCString str;
  8746. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8747. Error(str.AddressOf(), node);
  8748. ok = false;
  8749. }
  8750. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  8751. {
  8752. asCString str;
  8753. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8754. Error(str.AddressOf(), node);
  8755. ok = false;
  8756. }
  8757. if( !ok )
  8758. {
  8759. // It wasn't possible to get two valid operands, so we just return
  8760. // a boolean result and let the compiler continue.
  8761. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  8762. return;
  8763. }
  8764. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8765. int op = node->tokenType;
  8766. if( !isConstant )
  8767. {
  8768. if( to.IsBooleanType() )
  8769. {
  8770. int op = node->tokenType;
  8771. if( op == ttEqual || op == ttNotEqual )
  8772. {
  8773. // Must convert to temporary variable, because we are changing the value before comparison
  8774. ConvertToTempVariableNotIn(lctx, rctx);
  8775. ConvertToTempVariableNotIn(rctx, lctx);
  8776. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8777. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8778. // Make sure they are equal if not false
  8779. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  8780. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  8781. MergeExprBytecode(ctx, lctx);
  8782. MergeExprBytecode(ctx, rctx);
  8783. ProcessDeferredParams(ctx);
  8784. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  8785. int b = lctx->type.stackOffset;
  8786. int c = rctx->type.stackOffset;
  8787. if( op == ttEqual )
  8788. {
  8789. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  8790. ctx->bc.Instr(asBC_TZ);
  8791. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8792. }
  8793. else if( op == ttNotEqual )
  8794. {
  8795. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  8796. ctx->bc.Instr(asBC_TNZ);
  8797. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8798. }
  8799. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  8800. }
  8801. else
  8802. {
  8803. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  8804. Error(TXT_ILLEGAL_OPERATION, node);
  8805. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 0);
  8806. }
  8807. }
  8808. else
  8809. {
  8810. ConvertToVariableNotIn(lctx, rctx);
  8811. ConvertToVariableNotIn(rctx, lctx);
  8812. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8813. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8814. MergeExprBytecode(ctx, lctx);
  8815. MergeExprBytecode(ctx, rctx);
  8816. ProcessDeferredParams(ctx);
  8817. asEBCInstr iCmp = asBC_CMPi, iT = asBC_TZ;
  8818. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8819. iCmp = asBC_CMPi;
  8820. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8821. iCmp = asBC_CMPu;
  8822. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8823. iCmp = asBC_CMPi64;
  8824. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8825. iCmp = asBC_CMPu64;
  8826. else if( lctx->type.dataType.IsFloatType() )
  8827. iCmp = asBC_CMPf;
  8828. else if( lctx->type.dataType.IsDoubleType() )
  8829. iCmp = asBC_CMPd;
  8830. else
  8831. asASSERT(false);
  8832. if( op == ttEqual )
  8833. iT = asBC_TZ;
  8834. else if( op == ttNotEqual )
  8835. iT = asBC_TNZ;
  8836. else if( op == ttLessThan )
  8837. iT = asBC_TS;
  8838. else if( op == ttLessThanOrEqual )
  8839. iT = asBC_TNP;
  8840. else if( op == ttGreaterThan )
  8841. iT = asBC_TP;
  8842. else if( op == ttGreaterThanOrEqual )
  8843. iT = asBC_TNS;
  8844. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  8845. int b = lctx->type.stackOffset;
  8846. int c = rctx->type.stackOffset;
  8847. ctx->bc.InstrW_W(iCmp, b, c);
  8848. ctx->bc.Instr(iT);
  8849. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8850. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  8851. }
  8852. }
  8853. else
  8854. {
  8855. if( to.IsBooleanType() )
  8856. {
  8857. int op = node->tokenType;
  8858. if( op == ttEqual || op == ttNotEqual )
  8859. {
  8860. // Make sure they are equal if not false
  8861. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  8862. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  8863. asDWORD v = 0;
  8864. if( op == ttEqual )
  8865. {
  8866. v = lctx->type.intValue - rctx->type.intValue;
  8867. if( v == 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  8868. }
  8869. else if( op == ttNotEqual )
  8870. {
  8871. v = lctx->type.intValue - rctx->type.intValue;
  8872. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  8873. }
  8874. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), v);
  8875. }
  8876. else
  8877. {
  8878. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  8879. Error(TXT_ILLEGAL_OPERATION, node);
  8880. }
  8881. }
  8882. else
  8883. {
  8884. int i = 0;
  8885. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8886. {
  8887. int v = lctx->type.intValue - rctx->type.intValue;
  8888. if( v < 0 ) i = -1;
  8889. if( v > 0 ) i = 1;
  8890. }
  8891. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8892. {
  8893. asDWORD v1 = lctx->type.dwordValue;
  8894. asDWORD v2 = rctx->type.dwordValue;
  8895. if( v1 < v2 ) i = -1;
  8896. if( v1 > v2 ) i = 1;
  8897. }
  8898. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8899. {
  8900. asINT64 v = asINT64(lctx->type.qwordValue) - asINT64(rctx->type.qwordValue);
  8901. if( v < 0 ) i = -1;
  8902. if( v > 0 ) i = 1;
  8903. }
  8904. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8905. {
  8906. asQWORD v1 = lctx->type.qwordValue;
  8907. asQWORD v2 = rctx->type.qwordValue;
  8908. if( v1 < v2 ) i = -1;
  8909. if( v1 > v2 ) i = 1;
  8910. }
  8911. else if( lctx->type.dataType.IsFloatType() )
  8912. {
  8913. float v = lctx->type.floatValue - rctx->type.floatValue;
  8914. if( v < 0 ) i = -1;
  8915. if( v > 0 ) i = 1;
  8916. }
  8917. else if( lctx->type.dataType.IsDoubleType() )
  8918. {
  8919. double v = lctx->type.doubleValue - rctx->type.doubleValue;
  8920. if( v < 0 ) i = -1;
  8921. if( v > 0 ) i = 1;
  8922. }
  8923. if( op == ttEqual )
  8924. i = (i == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8925. else if( op == ttNotEqual )
  8926. i = (i != 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8927. else if( op == ttLessThan )
  8928. i = (i < 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8929. else if( op == ttLessThanOrEqual )
  8930. i = (i <= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8931. else if( op == ttGreaterThan )
  8932. i = (i > 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8933. else if( op == ttGreaterThanOrEqual )
  8934. i = (i >= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8935. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), i);
  8936. }
  8937. }
  8938. }
  8939. void asCCompiler::PushVariableOnStack(asSExprContext *ctx, bool asReference)
  8940. {
  8941. // Put the result on the stack
  8942. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  8943. if( asReference )
  8944. ctx->type.dataType.MakeReference(true);
  8945. else
  8946. {
  8947. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8948. ctx->bc.Instr(asBC_RDS4);
  8949. else
  8950. ctx->bc.Instr(asBC_RDS8);
  8951. }
  8952. }
  8953. void asCCompiler::CompileBooleanOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8954. {
  8955. // Both operands must be booleans
  8956. asCDataType to;
  8957. to.SetTokenType(ttBool);
  8958. // Do the actual conversion
  8959. asCArray<int> reservedVars;
  8960. rctx->bc.GetVarsUsed(reservedVars);
  8961. lctx->bc.GetVarsUsed(reservedVars);
  8962. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8963. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8964. // Verify that the conversion was successful
  8965. if( !lctx->type.dataType.IsBooleanType() )
  8966. {
  8967. asCString str;
  8968. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), "bool");
  8969. Error(str.AddressOf(), node);
  8970. // Force the conversion to allow compilation to proceed
  8971. lctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  8972. }
  8973. if( !rctx->type.dataType.IsBooleanType() )
  8974. {
  8975. asCString str;
  8976. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "bool");
  8977. Error(str.AddressOf(), node);
  8978. // Force the conversion to allow compilation to proceed
  8979. rctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  8980. }
  8981. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8982. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  8983. // What kind of operator is it?
  8984. int op = node->tokenType;
  8985. if( op == ttXor )
  8986. {
  8987. if( !isConstant )
  8988. {
  8989. // Must convert to temporary variable, because we are changing the value before comparison
  8990. ConvertToTempVariableNotIn(lctx, rctx);
  8991. ConvertToTempVariableNotIn(rctx, lctx);
  8992. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8993. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8994. // Make sure they are equal if not false
  8995. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  8996. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  8997. MergeExprBytecode(ctx, lctx);
  8998. MergeExprBytecode(ctx, rctx);
  8999. ProcessDeferredParams(ctx);
  9000. int a = AllocateVariable(ctx->type.dataType, true);
  9001. int b = lctx->type.stackOffset;
  9002. int c = rctx->type.stackOffset;
  9003. ctx->bc.InstrW_W_W(asBC_BXOR,a,b,c);
  9004. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9005. }
  9006. else
  9007. {
  9008. // Make sure they are equal if not false
  9009. #if AS_SIZEOF_BOOL == 1
  9010. if( lctx->type.byteValue != 0 ) lctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  9011. if( rctx->type.byteValue != 0 ) rctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  9012. asBYTE v = 0;
  9013. v = lctx->type.byteValue - rctx->type.byteValue;
  9014. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9015. ctx->type.isConstant = true;
  9016. ctx->type.byteValue = v;
  9017. #else
  9018. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9019. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9020. asDWORD v = 0;
  9021. v = lctx->type.intValue - rctx->type.intValue;
  9022. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9023. ctx->type.isConstant = true;
  9024. ctx->type.dwordValue = v;
  9025. #endif
  9026. }
  9027. }
  9028. else if( op == ttAnd ||
  9029. op == ttOr )
  9030. {
  9031. if( !isConstant )
  9032. {
  9033. // If or-operator and first value is 1 the second value shouldn't be calculated
  9034. // if and-operator and first value is 0 the second value shouldn't be calculated
  9035. ConvertToVariable(lctx);
  9036. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9037. MergeExprBytecode(ctx, lctx);
  9038. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  9039. int label1 = nextLabel++;
  9040. int label2 = nextLabel++;
  9041. if( op == ttAnd )
  9042. {
  9043. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  9044. ctx->bc.Instr(asBC_ClrHi);
  9045. ctx->bc.InstrDWORD(asBC_JNZ, label1);
  9046. ctx->bc.InstrW_DW(asBC_SetV4, (asWORD)offset, 0);
  9047. ctx->bc.InstrINT(asBC_JMP, label2);
  9048. }
  9049. else if( op == ttOr )
  9050. {
  9051. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  9052. ctx->bc.Instr(asBC_ClrHi);
  9053. ctx->bc.InstrDWORD(asBC_JZ, label1);
  9054. #if AS_SIZEOF_BOOL == 1
  9055. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  9056. #else
  9057. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  9058. #endif
  9059. ctx->bc.InstrINT(asBC_JMP, label2);
  9060. }
  9061. ctx->bc.Label((short)label1);
  9062. ConvertToVariable(rctx);
  9063. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9064. rctx->bc.InstrW_W(asBC_CpyVtoV4, offset, rctx->type.stackOffset);
  9065. MergeExprBytecode(ctx, rctx);
  9066. ctx->bc.Label((short)label2);
  9067. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), offset, true);
  9068. }
  9069. else
  9070. {
  9071. #if AS_SIZEOF_BOOL == 1
  9072. asBYTE v = 0;
  9073. if( op == ttAnd )
  9074. v = lctx->type.byteValue && rctx->type.byteValue;
  9075. else if( op == ttOr )
  9076. v = lctx->type.byteValue || rctx->type.byteValue;
  9077. // Remember the result
  9078. ctx->type.isConstant = true;
  9079. ctx->type.byteValue = v;
  9080. #else
  9081. asDWORD v = 0;
  9082. if( op == ttAnd )
  9083. v = lctx->type.dwordValue && rctx->type.dwordValue;
  9084. else if( op == ttOr )
  9085. v = lctx->type.dwordValue || rctx->type.dwordValue;
  9086. // Remember the result
  9087. ctx->type.isConstant = true;
  9088. ctx->type.dwordValue = v;
  9089. #endif
  9090. }
  9091. }
  9092. }
  9093. void asCCompiler::CompileOperatorOnHandles(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9094. {
  9095. // Process the property accessor as get
  9096. ProcessPropertyGetAccessor(lctx, node);
  9097. ProcessPropertyGetAccessor(rctx, node);
  9098. // Make sure lctx doesn't end up with a variable used in rctx
  9099. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  9100. {
  9101. asCArray<int> vars;
  9102. rctx->bc.GetVarsUsed(vars);
  9103. int offset = AllocateVariable(lctx->type.dataType, true);
  9104. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  9105. ReleaseTemporaryVariable(offset, 0);
  9106. }
  9107. // Warn if not both operands are explicit handles
  9108. if( (node->tokenType == ttEqual || node->tokenType == ttNotEqual) &&
  9109. ((!lctx->type.isExplicitHandle && !(lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE))) ||
  9110. (!rctx->type.isExplicitHandle && !(rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE)))) )
  9111. {
  9112. Warning(TXT_HANDLE_COMPARISON, node);
  9113. }
  9114. // If one of the operands is a value type used as handle, we should look for the opEquals method
  9115. if( ((lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) ||
  9116. (rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE))) &&
  9117. (node->tokenType == ttEqual || node->tokenType == ttIs ||
  9118. node->tokenType == ttNotEqual || node->tokenType == ttNotIs) )
  9119. {
  9120. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  9121. // Find the matching opEquals method
  9122. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  9123. if( r == 0 )
  9124. {
  9125. // Try again by switching the order of the operands
  9126. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  9127. }
  9128. if( r == 1 )
  9129. {
  9130. if( node->tokenType == ttNotEqual || node->tokenType == ttNotIs )
  9131. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  9132. // Success, don't continue
  9133. return;
  9134. }
  9135. else if( r == 0 )
  9136. {
  9137. // Couldn't find opEquals method
  9138. Error(TXT_NO_APPROPRIATE_OPEQUALS, node);
  9139. }
  9140. // Compiler error, don't continue
  9141. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  9142. return;
  9143. }
  9144. // Implicitly convert null to the other type
  9145. asCDataType to;
  9146. if( lctx->type.IsNullConstant() )
  9147. to = rctx->type.dataType;
  9148. else if( rctx->type.IsNullConstant() )
  9149. to = lctx->type.dataType;
  9150. else
  9151. {
  9152. // TODO: Use the common base type
  9153. to = lctx->type.dataType;
  9154. }
  9155. // Need to pop the value if it is a null constant
  9156. if( lctx->type.IsNullConstant() )
  9157. lctx->bc.Pop(AS_PTR_SIZE);
  9158. if( rctx->type.IsNullConstant() )
  9159. rctx->bc.Pop(AS_PTR_SIZE);
  9160. // Convert both sides to explicit handles
  9161. to.MakeHandle(true);
  9162. to.MakeReference(false);
  9163. // Do the conversion
  9164. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  9165. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  9166. // Both operands must be of the same type
  9167. // Verify that the conversion was successful
  9168. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  9169. {
  9170. asCString str;
  9171. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9172. Error(str.AddressOf(), node);
  9173. }
  9174. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  9175. {
  9176. asCString str;
  9177. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9178. Error(str.AddressOf(), node);
  9179. }
  9180. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  9181. int op = node->tokenType;
  9182. if( op == ttEqual || op == ttNotEqual || op == ttIs || op == ttNotIs )
  9183. {
  9184. // If the object handle already is in a variable we must manually pop it from the stack
  9185. if( lctx->type.isVariable )
  9186. lctx->bc.Pop(AS_PTR_SIZE);
  9187. if( rctx->type.isVariable )
  9188. rctx->bc.Pop(AS_PTR_SIZE);
  9189. // TODO: optimize: Treat the object handles as two integers, i.e. don't do REFCPY
  9190. ConvertToVariableNotIn(lctx, rctx);
  9191. ConvertToVariable(rctx);
  9192. MergeExprBytecode(ctx, lctx);
  9193. MergeExprBytecode(ctx, rctx);
  9194. int a = AllocateVariable(ctx->type.dataType, true);
  9195. int b = lctx->type.stackOffset;
  9196. int c = rctx->type.stackOffset;
  9197. // TODO: When saving the bytecode we must be able to determine that this is
  9198. // a comparison with a pointer, so that the instruction can be adapted
  9199. // to the pointer size on the platform that will execute it.
  9200. #ifdef AS_64BIT_PTR
  9201. ctx->bc.InstrW_W(asBC_CMPi64, b, c);
  9202. #else
  9203. ctx->bc.InstrW_W(asBC_CMPi, b, c);
  9204. #endif
  9205. if( op == ttEqual || op == ttIs )
  9206. ctx->bc.Instr(asBC_TZ);
  9207. else if( op == ttNotEqual || op == ttNotIs )
  9208. ctx->bc.Instr(asBC_TNZ);
  9209. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9210. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9211. ReleaseTemporaryVariable(lctx->type, &ctx->bc);
  9212. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  9213. ProcessDeferredParams(ctx);
  9214. }
  9215. else
  9216. {
  9217. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  9218. Error(TXT_ILLEGAL_OPERATION, node);
  9219. }
  9220. }
  9221. void asCCompiler::PerformFunctionCall(int funcId, asSExprContext *ctx, bool isConstructor, asCArray<asSExprContext*> *args, asCObjectType *objType, bool useVariable, int varOffset, int funcPtrVar)
  9222. {
  9223. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  9224. // A shared object may not call non-shared functions
  9225. if( outFunc->objectType && outFunc->objectType->IsShared() && !descr->IsShared() )
  9226. {
  9227. asCString msg;
  9228. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, descr->GetDeclarationStr().AddressOf());
  9229. Error(msg.AddressOf(), ctx->exprNode);
  9230. }
  9231. // Check if the function is private
  9232. if( descr->isPrivate && descr->GetObjectType() != outFunc->GetObjectType() )
  9233. {
  9234. asCString msg;
  9235. msg.Format(TXT_PRIVATE_METHOD_CALL_s, descr->GetDeclarationStr().AddressOf());
  9236. Error(msg.AddressOf(), ctx->exprNode);
  9237. }
  9238. int argSize = descr->GetSpaceNeededForArguments();
  9239. if( descr->objectType && descr->returnType.IsReference() &&
  9240. !ctx->type.isVariable && (ctx->type.dataType.IsObjectHandle() || ctx->type.dataType.SupportHandles()) &&
  9241. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_SCOPED) &&
  9242. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_ASHANDLE) )
  9243. {
  9244. // The class method we're calling is returning a reference, which may be to a member of the object.
  9245. // In order to guarantee the lifetime of the reference, we must hold a local reference to the object.
  9246. // TODO: optimize: This can be avoided for local variables (non-handles) as they have a well defined life time
  9247. int tempRef = AllocateVariable(ctx->type.dataType, true);
  9248. ctx->bc.InstrSHORT(asBC_PSF, (short)tempRef);
  9249. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  9250. // Add the release of this reference, as a deferred expression
  9251. asSDeferredParam deferred;
  9252. deferred.origExpr = 0;
  9253. deferred.argInOutFlags = asTM_INREF;
  9254. deferred.argNode = 0;
  9255. deferred.argType.SetVariable(ctx->type.dataType, tempRef, true);
  9256. ctx->deferredParams.PushLast(deferred);
  9257. }
  9258. ctx->type.Set(descr->returnType);
  9259. if( isConstructor )
  9260. {
  9261. // Sometimes the value types are allocated on the heap,
  9262. // which is when this way of constructing them is used.
  9263. asASSERT(useVariable == false);
  9264. ctx->bc.Alloc(asBC_ALLOC, objType, descr->id, argSize+AS_PTR_SIZE);
  9265. // The instruction has already moved the returned object to the variable
  9266. ctx->type.Set(asCDataType::CreatePrimitive(ttVoid, false));
  9267. ctx->type.isLValue = false;
  9268. // Clean up arguments
  9269. if( args )
  9270. AfterFunctionCall(funcId, *args, ctx, false);
  9271. ProcessDeferredParams(ctx);
  9272. return;
  9273. }
  9274. else
  9275. {
  9276. if( descr->objectType )
  9277. argSize += AS_PTR_SIZE;
  9278. #ifndef AS_OLD
  9279. // If the function returns an object by value the address of the location
  9280. // where the value should be stored is passed as an argument too
  9281. if( descr->DoesReturnOnStack() )
  9282. {
  9283. argSize += AS_PTR_SIZE;
  9284. }
  9285. #endif
  9286. if( descr->funcType == asFUNC_IMPORTED )
  9287. ctx->bc.Call(asBC_CALLBND , descr->id, argSize);
  9288. // TODO: Maybe we need two different byte codes
  9289. else if( descr->funcType == asFUNC_INTERFACE || descr->funcType == asFUNC_VIRTUAL )
  9290. ctx->bc.Call(asBC_CALLINTF, descr->id, argSize);
  9291. else if( descr->funcType == asFUNC_SCRIPT )
  9292. ctx->bc.Call(asBC_CALL , descr->id, argSize);
  9293. else if( descr->funcType == asFUNC_SYSTEM )
  9294. ctx->bc.Call(asBC_CALLSYS , descr->id, argSize);
  9295. else if( descr->funcType == asFUNC_FUNCDEF )
  9296. ctx->bc.CallPtr(asBC_CallPtr, funcPtrVar, argSize);
  9297. }
  9298. if( ctx->type.dataType.IsObject() && !descr->returnType.IsReference() )
  9299. {
  9300. int returnOffset = 0;
  9301. #ifndef AS_OLD
  9302. if( descr->DoesReturnOnStack() )
  9303. {
  9304. asASSERT( useVariable );
  9305. // The variable was allocated before the function was called
  9306. returnOffset = varOffset;
  9307. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  9308. // The variable was initialized by the function, so we need to mark it as initialized here
  9309. ctx->bc.ObjInfo(varOffset, asOBJ_INIT);
  9310. }
  9311. else
  9312. #endif
  9313. {
  9314. if( useVariable )
  9315. {
  9316. // Use the given variable
  9317. returnOffset = varOffset;
  9318. ctx->type.SetVariable(descr->returnType, returnOffset, false);
  9319. }
  9320. else
  9321. {
  9322. // Allocate a temporary variable for the returned object
  9323. // The returned object will actually be allocated on the heap, so
  9324. // we must force the allocation of the variable to do the same
  9325. returnOffset = AllocateVariable(descr->returnType, true, true);
  9326. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  9327. }
  9328. // Move the pointer from the object register to the temporary variable
  9329. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  9330. }
  9331. ctx->type.dataType.MakeReference(IsVariableOnHeap(returnOffset));
  9332. ctx->type.isLValue = false; // It is a reference, but not an lvalue
  9333. // Clean up arguments
  9334. if( args )
  9335. AfterFunctionCall(funcId, *args, ctx, false);
  9336. ProcessDeferredParams(ctx);
  9337. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  9338. }
  9339. else if( descr->returnType.IsReference() )
  9340. {
  9341. asASSERT(useVariable == false);
  9342. // We cannot clean up the arguments yet, because the
  9343. // reference might be pointing to one of them.
  9344. // Clean up arguments
  9345. if( args )
  9346. AfterFunctionCall(funcId, *args, ctx, true);
  9347. // Do not process the output parameters yet, because it
  9348. // might invalidate the returned reference
  9349. if( descr->returnType.IsPrimitive() )
  9350. ctx->type.Set(descr->returnType);
  9351. else
  9352. {
  9353. ctx->bc.Instr(asBC_PshRPtr);
  9354. if( descr->returnType.IsObject() &&
  9355. (!descr->returnType.IsObjectHandle() || (descr->returnType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  9356. {
  9357. // We are getting the pointer to the object
  9358. // not a pointer to a object variable
  9359. ctx->type.dataType.MakeReference(false);
  9360. }
  9361. }
  9362. // A returned reference can be used as lvalue
  9363. ctx->type.isLValue = true;
  9364. }
  9365. else
  9366. {
  9367. asASSERT(useVariable == false);
  9368. if( descr->returnType.GetSizeInMemoryBytes() )
  9369. {
  9370. // Allocate a temporary variable to hold the value, but make sure
  9371. // the temporary variable isn't used in any of the deferred arguments
  9372. asCArray<int> vars;
  9373. for( asUINT n = 0; args && n < args->GetLength(); n++ )
  9374. {
  9375. asSExprContext *expr = (*args)[n]->origExpr;
  9376. if( expr )
  9377. expr->bc.GetVarsUsed(vars);
  9378. }
  9379. int offset = AllocateVariableNotIn(descr->returnType, true, &vars);
  9380. ctx->type.SetVariable(descr->returnType, offset, true);
  9381. // Move the value from the return register to the variable
  9382. if( descr->returnType.GetSizeOnStackDWords() == 1 )
  9383. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)offset);
  9384. else if( descr->returnType.GetSizeOnStackDWords() == 2 )
  9385. ctx->bc.InstrSHORT(asBC_CpyRtoV8, (short)offset);
  9386. }
  9387. else
  9388. ctx->type.Set(descr->returnType);
  9389. ctx->type.isLValue = false;
  9390. // Clean up arguments
  9391. if( args )
  9392. AfterFunctionCall(funcId, *args, ctx, false);
  9393. ProcessDeferredParams(ctx);
  9394. }
  9395. }
  9396. // This only merges the bytecode, but doesn't modify the type of the final context
  9397. void asCCompiler::MergeExprBytecode(asSExprContext *before, asSExprContext *after)
  9398. {
  9399. before->bc.AddCode(&after->bc);
  9400. for( asUINT n = 0; n < after->deferredParams.GetLength(); n++ )
  9401. {
  9402. before->deferredParams.PushLast(after->deferredParams[n]);
  9403. after->deferredParams[n].origExpr = 0;
  9404. }
  9405. after->deferredParams.SetLength(0);
  9406. }
  9407. // This merges both bytecode and the type of the final context
  9408. void asCCompiler::MergeExprBytecodeAndType(asSExprContext *before, asSExprContext *after)
  9409. {
  9410. MergeExprBytecode(before, after);
  9411. before->type = after->type;
  9412. before->property_get = after->property_get;
  9413. before->property_set = after->property_set;
  9414. before->property_const = after->property_const;
  9415. before->property_handle = after->property_handle;
  9416. before->property_ref = after->property_ref;
  9417. before->property_arg = after->property_arg;
  9418. before->exprNode = after->exprNode;
  9419. after->property_arg = 0;
  9420. // Do not copy the origExpr member
  9421. }
  9422. void asCCompiler::FilterConst(asCArray<int> &funcs)
  9423. {
  9424. if( funcs.GetLength() == 0 ) return;
  9425. // This is only done for object methods
  9426. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[0]);
  9427. if( desc->objectType == 0 ) return;
  9428. // Check if there are any non-const matches
  9429. asUINT n;
  9430. bool foundNonConst = false;
  9431. for( n = 0; n < funcs.GetLength(); n++ )
  9432. {
  9433. desc = builder->GetFunctionDescription(funcs[n]);
  9434. if( !desc->isReadOnly )
  9435. {
  9436. foundNonConst = true;
  9437. break;
  9438. }
  9439. }
  9440. if( foundNonConst )
  9441. {
  9442. // Remove all const methods
  9443. for( n = 0; n < funcs.GetLength(); n++ )
  9444. {
  9445. desc = builder->GetFunctionDescription(funcs[n]);
  9446. if( desc->isReadOnly )
  9447. {
  9448. if( n == funcs.GetLength() - 1 )
  9449. funcs.PopLast();
  9450. else
  9451. funcs[n] = funcs.PopLast();
  9452. n--;
  9453. }
  9454. }
  9455. }
  9456. }
  9457. END_AS_NAMESPACE