as_compiler.cpp 335 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797
  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. }
  185. else
  186. {
  187. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  188. if( node->tokenType == ttBitNot )
  189. isDestructor = true;
  190. else
  191. m_isConstructor = true;
  192. }
  193. //----------------------------------------------
  194. // Declare parameters
  195. // Find first parameter
  196. while( node && node->nodeType != snParameterList )
  197. node = node->next;
  198. // Register parameters from last to first, otherwise they will be destroyed in the wrong order
  199. asCVariableScope vs(0);
  200. if( node ) node = node->firstChild;
  201. while( node )
  202. {
  203. // Get the parameter type
  204. asCDataType type = builder->CreateDataTypeFromNode(node, script);
  205. asETypeModifiers inoutFlag = asTM_NONE;
  206. type = builder->ModifyDataTypeFromNode(type, node->next, script, &inoutFlag, 0);
  207. // Is the data type allowed?
  208. if( (type.IsReference() && inoutFlag != asTM_INOUTREF && !type.CanBeInstanciated()) ||
  209. (!type.IsReference() && !type.CanBeInstanciated()) )
  210. {
  211. asCString str;
  212. str.Format(TXT_PARAMETER_CANT_BE_s, type.Format().AddressOf());
  213. Error(str.AddressOf(), node);
  214. }
  215. // If the parameter has a name then declare it as variable
  216. node = node->next->next;
  217. if( node && node->nodeType == snIdentifier )
  218. {
  219. asCString name(&script->code[node->tokenPos], node->tokenLength);
  220. if( vs.DeclareVariable(name.AddressOf(), type, stackPos, true) < 0 )
  221. Error(TXT_PARAMETER_ALREADY_DECLARED, node);
  222. // Add marker for variable declaration
  223. byteCode.VarDecl((int)outFunc->variables.GetLength());
  224. outFunc->AddVariable(name, type, stackPos);
  225. node = node->next;
  226. // Skip the default arg
  227. if( node && node->nodeType == snExpression )
  228. node = node->next;
  229. }
  230. else
  231. vs.DeclareVariable("", type, stackPos, true);
  232. // Move to next parameter
  233. stackPos -= type.GetSizeOnStackDWords();
  234. }
  235. int n;
  236. for( n = (int)vs.variables.GetLength() - 1; n >= 0; n-- )
  237. {
  238. variables->DeclareVariable(vs.variables[n]->name.AddressOf(), vs.variables[n]->type, vs.variables[n]->stackOffset, vs.variables[n]->onHeap);
  239. }
  240. // Is the return type allowed?
  241. if( (returnType.GetSizeOnStackDWords() == 0 && returnType != asCDataType::CreatePrimitive(ttVoid, false)) ||
  242. (returnType.IsReference() && !returnType.CanBeInstanciated()) )
  243. {
  244. asCString str;
  245. str.Format(TXT_RETURN_CANT_BE_s, returnType.Format().AddressOf());
  246. Error(str.AddressOf(), func);
  247. }
  248. variables->DeclareVariable("return", returnType, stackPos, true);
  249. //--------------------------------------------
  250. // Compile the statement block
  251. // We need to parse the statement block now
  252. // TODO: memory: We can parse the statement block one statement at a time, thus save even more memory
  253. asCParser parser(builder);
  254. int r = parser.ParseStatementBlock(script, func->lastChild);
  255. if( r < 0 ) return -1;
  256. asCScriptNode *block = parser.GetScriptNode();
  257. bool hasReturn;
  258. asCByteCode bc(engine);
  259. LineInstr(&bc, func->lastChild->tokenPos);
  260. CompileStatementBlock(block, false, &hasReturn, &bc);
  261. LineInstr(&bc, func->lastChild->tokenPos + func->lastChild->tokenLength);
  262. // Make sure there is a return in all paths (if not return type is void)
  263. if( returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  264. {
  265. if( hasReturn == false )
  266. Error(TXT_NOT_ALL_PATHS_RETURN, func->lastChild);
  267. }
  268. //------------------------------------------------
  269. // Concatenate the bytecode
  270. // Insert a JitEntry at the start of the function for JIT compilers
  271. byteCode.InstrWORD(asBC_JitEntry, 0);
  272. // Count total variable size
  273. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  274. byteCode.Push(varSize);
  275. if( outFunc->objectType )
  276. {
  277. // Call the base class' default constructor unless called manually in the code
  278. if( m_isConstructor && !m_isConstructorCalled && outFunc->objectType->derivedFrom )
  279. {
  280. byteCode.InstrSHORT(asBC_PSF, 0);
  281. byteCode.Instr(asBC_RDSPTR);
  282. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  283. }
  284. // Increase the reference for the object pointer, so that it is guaranteed to live during the entire call
  285. // TODO: optimize: This is probably not necessary for constructors as no outside reference to the object is created yet
  286. byteCode.InstrSHORT(asBC_PSF, 0);
  287. byteCode.Instr(asBC_RDSPTR);
  288. byteCode.Call(asBC_CALLSYS, outFunc->objectType->beh.addref, AS_PTR_SIZE);
  289. }
  290. // Add the code for the statement block
  291. byteCode.AddCode(&bc);
  292. // Deallocate all local variables
  293. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  294. {
  295. sVariable *v = variables->variables[n];
  296. if( v->stackOffset > 0 )
  297. {
  298. // Call variables destructors
  299. if( v->name != "return" && v->name != "return address" )
  300. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  301. DeallocateVariable(v->stackOffset);
  302. }
  303. }
  304. // This is the label that return statements jump to
  305. // in order to exit the function
  306. byteCode.Label(0);
  307. // Call destructors for function parameters
  308. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  309. {
  310. sVariable *v = variables->variables[n];
  311. if( v->stackOffset <= 0 )
  312. {
  313. // Call variable destructors here, for variables not yet destroyed
  314. if( v->name != "return" && v->name != "return address" )
  315. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  316. }
  317. // Do not deallocate parameters
  318. }
  319. // Release the object pointer again
  320. if( outFunc->objectType )
  321. {
  322. byteCode.InstrW_PTR(asBC_FREE, 0, outFunc->objectType);
  323. }
  324. // If there are compile errors, there is no reason to build the final code
  325. if( hasCompileErrors || builder->numErrors != buildErrors )
  326. return -1;
  327. // At this point there should be no variables allocated
  328. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  329. // Remove the variable scope
  330. RemoveVariableScope();
  331. // This POP is not necessary as the return will clean up the stack frame anyway.
  332. // The bytecode optimizer would remove this POP, however by not including it here
  333. // it is guaranteed it doesn't have to be adjusted by the asCRestore class when
  334. // a types are of a different size than originally compiled for.
  335. // byteCode.Pop(varSize);
  336. byteCode.Ret(-stackPos);
  337. FinalizeFunction();
  338. #ifdef AS_DEBUG
  339. // DEBUG: output byte code
  340. if( outFunc->objectType )
  341. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  342. else
  343. byteCode.DebugOutput(("__" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  344. #endif
  345. return 0;
  346. }
  347. int asCCompiler::CallCopyConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asSExprContext *arg, asCScriptNode *node, bool isGlobalVar)
  348. {
  349. if( !type.IsObject() )
  350. return 0;
  351. // CallCopyConstructor should not be called for object handles.
  352. asASSERT(!type.IsObjectHandle() || (type.GetObjectType() && (type.GetObjectType()->flags & asOBJ_ASHANDLE)) );
  353. asCArray<asSExprContext*> args;
  354. args.PushLast(arg);
  355. // The reference parameter must be pushed on the stack
  356. asASSERT( arg->type.dataType.GetObjectType() == type.GetObjectType() );
  357. // Since we're calling the copy constructor, we have to trust the function to not do
  358. // anything stupid otherwise we will just enter a loop, as we try to make temporary
  359. // copies of the argument in order to guarantee safety.
  360. if( type.GetObjectType()->flags & asOBJ_REF )
  361. {
  362. asSExprContext ctx(engine);
  363. int func = 0;
  364. asSTypeBehaviour *beh = type.GetBehaviour();
  365. if( beh ) func = beh->copyfactory;
  366. if( func > 0 )
  367. {
  368. if( !isGlobalVar )
  369. {
  370. // Call factory and store the handle in the given variable
  371. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType(), true, offset);
  372. // Pop the reference left by the function call
  373. ctx.bc.Pop(AS_PTR_SIZE);
  374. }
  375. else
  376. {
  377. // Call factory
  378. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType());
  379. // Store the returned handle in the global variable
  380. ctx.bc.Instr(asBC_RDSPTR);
  381. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  382. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  383. ctx.bc.Pop(AS_PTR_SIZE);
  384. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  385. }
  386. bc->AddCode(&ctx.bc);
  387. return 0;
  388. }
  389. }
  390. else
  391. {
  392. asSTypeBehaviour *beh = type.GetBehaviour();
  393. int func = beh ? beh->copyconstruct : 0;
  394. if( func > 0 )
  395. {
  396. // Push the address where the object will be stored on the stack, before the argument
  397. // TODO: When the context is serializable this probably has to be changed, since this
  398. // pointer can remain on the stack while the context is suspended. There is no
  399. // risk the pointer becomes invalid though, there is just no easy way to serialize it.
  400. asCByteCode tmp(engine);
  401. if( isGlobalVar )
  402. tmp.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  403. else if( isObjectOnHeap )
  404. tmp.InstrSHORT(asBC_PSF, (short)offset);
  405. tmp.AddCode(bc);
  406. bc->AddCode(&tmp);
  407. // When the object is allocated on the stack the object pointer
  408. // must be pushed on the stack after the arguments
  409. if( !isObjectOnHeap )
  410. {
  411. asASSERT( !isGlobalVar );
  412. bc->InstrSHORT(asBC_PSF, (short)offset);
  413. }
  414. asSExprContext ctx(engine);
  415. PerformFunctionCall(func, &ctx, isObjectOnHeap, &args, type.GetObjectType());
  416. bc->AddCode(&ctx.bc);
  417. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  418. // Mark the object as initialized
  419. if( !isObjectOnHeap )
  420. bc->ObjInfo(offset, asOBJ_INIT);
  421. return 0;
  422. }
  423. }
  424. // Class has no copy constructor/factory.
  425. asCString str;
  426. str.Format(TXT_NO_COPY_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  427. Error(str.AddressOf(), node);
  428. return -1;
  429. }
  430. int asCCompiler::CallDefaultConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asCScriptNode *node, bool isGlobalVar)
  431. {
  432. if( !type.IsObject() ||
  433. (type.IsObjectHandle() && !(type.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  434. return 0;
  435. if( type.GetObjectType()->flags & asOBJ_REF )
  436. {
  437. asSExprContext ctx(engine);
  438. int func = 0;
  439. asSTypeBehaviour *beh = type.GetBehaviour();
  440. if( beh ) func = beh->factory;
  441. if( func > 0 )
  442. {
  443. if( !isGlobalVar )
  444. {
  445. // Call factory and store the handle in the given variable
  446. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType(), true, offset);
  447. // Pop the reference left by the function call
  448. ctx.bc.Pop(AS_PTR_SIZE);
  449. }
  450. else
  451. {
  452. // Call factory
  453. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  454. // Store the returned handle in the global variable
  455. ctx.bc.Instr(asBC_RDSPTR);
  456. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  457. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  458. ctx.bc.Pop(AS_PTR_SIZE);
  459. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  460. }
  461. bc->AddCode(&ctx.bc);
  462. return 0;
  463. }
  464. }
  465. else
  466. {
  467. asSTypeBehaviour *beh = type.GetBehaviour();
  468. int func = 0;
  469. if( beh ) func = beh->construct;
  470. // Allocate and initialize with the default constructor
  471. if( func != 0 || (type.GetObjectType()->flags & asOBJ_POD) )
  472. {
  473. if( !isObjectOnHeap )
  474. {
  475. asASSERT( !isGlobalVar );
  476. // There is nothing to do if there is no function,
  477. // as the memory is already allocated on the stack
  478. if( func )
  479. {
  480. // Call the constructor as a normal function
  481. bc->InstrSHORT(asBC_PSF, (short)offset);
  482. asSExprContext ctx(engine);
  483. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  484. bc->AddCode(&ctx.bc);
  485. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  486. // Mark the object as initialized
  487. bc->ObjInfo(offset, asOBJ_INIT);
  488. }
  489. }
  490. else
  491. {
  492. if( isGlobalVar )
  493. bc->InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  494. else
  495. bc->InstrSHORT(asBC_PSF, (short)offset);
  496. bc->Alloc(asBC_ALLOC, type.GetObjectType(), func, AS_PTR_SIZE);
  497. }
  498. return 0;
  499. }
  500. }
  501. // Class has no default factory/constructor.
  502. asCString str;
  503. // TODO: funcdef: asCDataType should have a GetTypeName()
  504. if( type.GetFuncDef() )
  505. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetFuncDef()->GetName());
  506. else
  507. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  508. Error(str.AddressOf(), node);
  509. return -1;
  510. }
  511. void asCCompiler::CallDestructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc)
  512. {
  513. if( !type.IsReference() )
  514. {
  515. // Call destructor for the data type
  516. if( type.IsObject() )
  517. {
  518. // ASHANDLE is really a value type and shouldn't be deallocated. Just the destructor should be called
  519. if( isObjectOnHeap || (type.IsObjectHandle() && !(type.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  520. {
  521. // Free the memory
  522. bc->InstrW_PTR(asBC_FREE, (short)offset, type.GetObjectType());
  523. }
  524. else
  525. {
  526. asASSERT( type.GetObjectType()->GetFlags() & asOBJ_VALUE );
  527. if( type.GetBehaviour()->destruct )
  528. {
  529. // Call the destructor as a regular function
  530. bc->InstrSHORT(asBC_PSF, (short)offset);
  531. asSExprContext ctx(engine);
  532. PerformFunctionCall(type.GetBehaviour()->destruct, &ctx);
  533. bc->AddCode(&ctx.bc);
  534. }
  535. // TODO: Value on stack: This probably needs to be done in PerformFunctionCall
  536. // Mark the object as destroyed
  537. bc->ObjInfo(offset, asOBJ_UNINIT);
  538. }
  539. }
  540. }
  541. }
  542. void asCCompiler::LineInstr(asCByteCode *bc, size_t pos)
  543. {
  544. int r, c;
  545. script->ConvertPosToRowCol(pos, &r, &c);
  546. bc->Line(r, c);
  547. }
  548. void asCCompiler::CompileStatementBlock(asCScriptNode *block, bool ownVariableScope, bool *hasReturn, asCByteCode *bc)
  549. {
  550. *hasReturn = false;
  551. bool isFinished = false;
  552. bool hasWarned = false;
  553. if( ownVariableScope )
  554. {
  555. bc->Block(true);
  556. AddVariableScope();
  557. }
  558. asCScriptNode *node = block->firstChild;
  559. while( node )
  560. {
  561. if( !hasWarned && (*hasReturn || isFinished) )
  562. {
  563. hasWarned = true;
  564. Warning(TXT_UNREACHABLE_CODE, node);
  565. }
  566. if( node->nodeType == snBreak || node->nodeType == snContinue )
  567. isFinished = true;
  568. asCByteCode statement(engine);
  569. if( node->nodeType == snDeclaration )
  570. CompileDeclaration(node, &statement);
  571. else
  572. CompileStatement(node, hasReturn, &statement);
  573. LineInstr(bc, node->tokenPos);
  574. bc->AddCode(&statement);
  575. if( !hasCompileErrors )
  576. asASSERT( tempVariables.GetLength() == 0 );
  577. node = node->next;
  578. }
  579. if( ownVariableScope )
  580. {
  581. // Deallocate variables in this block, in reverse order
  582. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  583. {
  584. sVariable *v = variables->variables[n];
  585. // Call variable destructors here, for variables not yet destroyed
  586. // If the block is terminated with a break, continue, or
  587. // return the variables are already destroyed
  588. if( !isFinished && !*hasReturn )
  589. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  590. // Don't deallocate function parameters
  591. if( v->stackOffset > 0 )
  592. DeallocateVariable(v->stackOffset);
  593. }
  594. RemoveVariableScope();
  595. bc->Block(false);
  596. }
  597. }
  598. // Entry
  599. int asCCompiler::CompileGlobalVariable(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, sGlobalVariableDescription *gvar, asCScriptFunction *outFunc)
  600. {
  601. Reset(builder, script, outFunc);
  602. // Add a variable scope (even though variables can't be declared)
  603. AddVariableScope();
  604. asSExprContext ctx(engine);
  605. gvar->isPureConstant = false;
  606. // Parse the initialization nodes
  607. asCParser parser(builder);
  608. if( node )
  609. {
  610. int r = parser.ParseGlobalVarInit(script, node);
  611. if( r < 0 )
  612. return r;
  613. node = parser.GetScriptNode();
  614. }
  615. // Compile the expression
  616. if( node && node->nodeType == snArgList )
  617. {
  618. // Make sure that it is a registered type, and that it isn't a pointer
  619. if( gvar->datatype.GetObjectType() == 0 || gvar->datatype.IsObjectHandle() )
  620. {
  621. Error(TXT_MUST_BE_OBJECT, node);
  622. }
  623. else
  624. {
  625. // Compile the arguments
  626. asCArray<asSExprContext *> args;
  627. if( CompileArgumentList(node, args) >= 0 )
  628. {
  629. // Find all constructors
  630. asCArray<int> funcs;
  631. asSTypeBehaviour *beh = gvar->datatype.GetBehaviour();
  632. if( beh )
  633. {
  634. if( gvar->datatype.GetObjectType()->flags & asOBJ_REF )
  635. funcs = beh->factories;
  636. else
  637. funcs = beh->constructors;
  638. }
  639. asCString str = gvar->datatype.Format();
  640. MatchFunctions(funcs, args, node, str.AddressOf());
  641. if( funcs.GetLength() == 1 )
  642. {
  643. int r = asSUCCESS;
  644. // Add the default values for arguments not explicitly supplied
  645. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  646. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  647. r = CompileDefaultArgs(node, args, func);
  648. if( r == asSUCCESS )
  649. {
  650. if( gvar->datatype.GetObjectType()->flags & asOBJ_REF )
  651. {
  652. MakeFunctionCall(&ctx, funcs[0], 0, args, node);
  653. // Store the returned handle in the global variable
  654. ctx.bc.Instr(asBC_RDSPTR);
  655. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  656. ctx.bc.InstrPTR(asBC_REFCPY, gvar->datatype.GetObjectType());
  657. ctx.bc.Pop(AS_PTR_SIZE);
  658. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  659. }
  660. else
  661. {
  662. // Push the address of the location where the variable will be stored on the stack.
  663. // This reference is safe, because the addresses of the global variables cannot change.
  664. // TODO: When serialization of the context is implemented this will probably have to change,
  665. // because this pointer may be on the stack while the context is suspended, and may
  666. // be difficult to serialize as the context doesn't know that the value represents a
  667. // pointer.
  668. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  669. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  670. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  671. PerformFunctionCall(funcs[0], &ctx, true, &args, gvar->datatype.GetObjectType());
  672. }
  673. }
  674. }
  675. }
  676. // Cleanup
  677. for( asUINT n = 0; n < args.GetLength(); n++ )
  678. if( args[n] )
  679. {
  680. asDELETE(args[n],asSExprContext);
  681. }
  682. }
  683. }
  684. else if( node && node->nodeType == snInitList )
  685. {
  686. asCTypeInfo ti;
  687. ti.Set(gvar->datatype);
  688. ti.isVariable = false;
  689. ti.isTemporary = false;
  690. ti.stackOffset = (short)gvar->index;
  691. ti.isLValue = true;
  692. CompileInitList(&ti, node, &ctx.bc);
  693. node = node->next;
  694. }
  695. else if( node )
  696. {
  697. // Compile the right hand expression
  698. asSExprContext expr(engine);
  699. int r = CompileAssignment(node, &expr); if( r < 0 ) return r;
  700. // Assign the value to the variable
  701. if( gvar->datatype.IsPrimitive() )
  702. {
  703. if( gvar->datatype.IsReadOnly() && expr.type.isConstant )
  704. {
  705. ImplicitConversion(&expr, gvar->datatype, node, asIC_IMPLICIT_CONV);
  706. gvar->isPureConstant = true;
  707. gvar->constantValue = expr.type.qwordValue;
  708. }
  709. asSExprContext lctx(engine);
  710. lctx.type.Set(gvar->datatype);
  711. lctx.type.dataType.MakeReference(true);
  712. lctx.type.dataType.MakeReadOnly(false);
  713. lctx.type.isLValue = true;
  714. // If it is an enum value that is being compiled, then
  715. // we skip this, as the bytecode won't be used anyway
  716. if( !gvar->isEnumValue )
  717. lctx.bc.InstrPTR(asBC_LDG, engine->globalProperties[gvar->index]->GetAddressOfValue());
  718. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  719. }
  720. else
  721. {
  722. // TODO: copy: Here we should look for the best matching constructor, instead of
  723. // just the copy constructor. Only if no appropriate constructor is
  724. // available should the assignment operator be used.
  725. if( (!gvar->datatype.IsObjectHandle() || gvar->datatype.GetObjectType()->flags & asOBJ_ASHANDLE) )
  726. {
  727. // Call the default constructor to have a valid object for the assignment
  728. CallDefaultConstructor(gvar->datatype, gvar->index, true, &ctx.bc, gvar->idNode, true);
  729. }
  730. asSExprContext lexpr(engine);
  731. lexpr.type.Set(gvar->datatype);
  732. lexpr.type.dataType.MakeReference(true);
  733. lexpr.type.dataType.MakeReadOnly(false);
  734. lexpr.type.stackOffset = -1;
  735. lexpr.type.isLValue = true;
  736. if( gvar->datatype.IsObjectHandle() )
  737. lexpr.type.isExplicitHandle = true;
  738. lexpr.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  739. // If left expression resolves into a registered type
  740. // check if the assignment operator is overloaded, and check
  741. // the type of the right hand expression. If none is found
  742. // the default action is a direct copy if it is the same type
  743. // and a simple assignment.
  744. bool assigned = false;
  745. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  746. {
  747. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  748. if( assigned )
  749. {
  750. // Pop the resulting value
  751. ctx.bc.Pop(ctx.type.dataType.GetSizeOnStackDWords());
  752. // Release the argument
  753. ProcessDeferredParams(&ctx);
  754. }
  755. }
  756. if( !assigned )
  757. {
  758. PrepareForAssignment(&lexpr.type.dataType, &expr, node);
  759. // If the expression is constant and the variable also is constant
  760. // then mark the variable as pure constant. This will allow the compiler
  761. // to optimize expressions with this variable.
  762. if( gvar->datatype.IsReadOnly() && expr.type.isConstant )
  763. {
  764. gvar->isPureConstant = true;
  765. gvar->constantValue = expr.type.qwordValue;
  766. }
  767. // Add expression code to bytecode
  768. MergeExprBytecode(&ctx, &expr);
  769. // Add byte code for storing value of expression in variable
  770. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  771. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, node);
  772. // Release temporary variables used by expression
  773. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  774. ctx.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  775. }
  776. }
  777. }
  778. else if( gvar->datatype.IsObject() && (!gvar->datatype.IsObjectHandle() || gvar->datatype.GetObjectType()->flags & asOBJ_ASHANDLE) )
  779. {
  780. // Call the default constructor in case no explicit initialization is given
  781. CallDefaultConstructor(gvar->datatype, gvar->index, true, &ctx.bc, gvar->idNode, true);
  782. }
  783. // Concatenate the bytecode
  784. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  785. // Add information on the line number for the global variable
  786. size_t pos = 0;
  787. if( gvar->idNode )
  788. pos = gvar->idNode->tokenPos;
  789. else if( gvar->nextNode )
  790. pos = gvar->nextNode->tokenPos;
  791. LineInstr(&byteCode, pos);
  792. // We need to push zeroes on the stack to guarantee
  793. // that temporary object handles are clear
  794. int n;
  795. for( n = 0; n < varSize; n++ )
  796. byteCode.InstrINT(asBC_PshC4, 0);
  797. byteCode.AddCode(&ctx.bc);
  798. // Deallocate variables in this block, in reverse order
  799. for( n = (int)variables->variables.GetLength() - 1; n >= 0; --n )
  800. {
  801. sVariable *v = variables->variables[n];
  802. // Call variable destructors here, for variables not yet destroyed
  803. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  804. DeallocateVariable(v->stackOffset);
  805. }
  806. if( hasCompileErrors ) return -1;
  807. // At this point there should be no variables allocated
  808. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  809. // Remove the variable scope again
  810. RemoveVariableScope();
  811. byteCode.Ret(0);
  812. FinalizeFunction();
  813. #ifdef AS_DEBUG
  814. // DEBUG: output byte code
  815. byteCode.DebugOutput(("___init_" + gvar->name + ".txt").AddressOf(), engine, outFunc);
  816. #endif
  817. return 0;
  818. }
  819. void asCCompiler::FinalizeFunction()
  820. {
  821. asUINT n;
  822. // Tell the bytecode which variables are temporary
  823. for( n = 0; n < variableIsTemporary.GetLength(); n++ )
  824. {
  825. if( variableIsTemporary[n] )
  826. byteCode.DefineTemporaryVariable(GetVariableOffset(n));
  827. }
  828. // Finalize the bytecode
  829. byteCode.Finalize();
  830. byteCode.ExtractObjectVariableInfo(outFunc);
  831. // Compile the list of object variables for the exception handler
  832. for( n = 0; n < variableAllocations.GetLength(); n++ )
  833. {
  834. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  835. {
  836. outFunc->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  837. outFunc->objVariablePos.PushLast(GetVariableOffset(n));
  838. outFunc->objVariableIsOnHeap.PushLast(variableIsOnHeap[n]);
  839. }
  840. }
  841. // Copy byte code to the function
  842. outFunc->byteCode.SetLength(byteCode.GetSize());
  843. byteCode.Output(outFunc->byteCode.AddressOf());
  844. outFunc->AddReferences();
  845. outFunc->stackNeeded = byteCode.largestStackUsed;
  846. outFunc->lineNumbers = byteCode.lineNumbers;
  847. }
  848. void asCCompiler::PrepareArgument(asCDataType *paramType, asSExprContext *ctx, asCScriptNode *node, bool isFunction, int refType, asCArray<int> *reservedVars, bool /* forceOnHeap */)
  849. {
  850. asCDataType param = *paramType;
  851. if( paramType->GetTokenType() == ttQuestion )
  852. {
  853. // Since the function is expecting a var type ?, then we don't want to convert the argument to anything else
  854. param = ctx->type.dataType;
  855. param.MakeHandle(ctx->type.isExplicitHandle);
  856. param.MakeReference(paramType->IsReference());
  857. param.MakeReadOnly(paramType->IsReadOnly());
  858. }
  859. else
  860. param = *paramType;
  861. asCDataType dt = param;
  862. // Need to protect arguments by reference
  863. if( isFunction && dt.IsReference() )
  864. {
  865. if( paramType->GetTokenType() == ttQuestion )
  866. {
  867. asCByteCode tmpBC(engine);
  868. // Place the type id on the stack as a hidden parameter
  869. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  870. // Insert the code before the expression code
  871. tmpBC.AddCode(&ctx->bc);
  872. ctx->bc.AddCode(&tmpBC);
  873. }
  874. // Allocate a temporary variable of the same type as the argument
  875. dt.MakeReference(false);
  876. dt.MakeReadOnly(false);
  877. int offset;
  878. if( refType == 1 ) // &in
  879. {
  880. ProcessPropertyGetAccessor(ctx, node);
  881. // If the reference is const, then it is not necessary to make a copy if the value already is a variable
  882. // Even if the same variable is passed in another argument as non-const then there is no problem
  883. if( dt.IsPrimitive() || dt.IsNullHandle() )
  884. {
  885. IsVariableInitialized(&ctx->type, node);
  886. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  887. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true, reservedVars);
  888. if( !(param.IsReadOnly() && ctx->type.isVariable) )
  889. ConvertToTempVariable(ctx);
  890. PushVariableOnStack(ctx, true);
  891. ctx->type.dataType.MakeReadOnly(param.IsReadOnly());
  892. }
  893. else
  894. {
  895. IsVariableInitialized(&ctx->type, node);
  896. ImplicitConversion(ctx, param, node, asIC_IMPLICIT_CONV, true, reservedVars);
  897. if( !ctx->type.dataType.IsEqualExceptRef(param) )
  898. {
  899. asCString str;
  900. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), param.Format().AddressOf());
  901. Error(str.AddressOf(), node);
  902. ctx->type.Set(param);
  903. }
  904. // If the argument already is a temporary
  905. // variable we don't need to allocate another
  906. // If the parameter is read-only and the object already is a local
  907. // variable then it is not necessary to make a copy either
  908. if( !ctx->type.isTemporary && !(param.IsReadOnly() && ctx->type.isVariable) )
  909. {
  910. // Make sure the variable is not used in the expression
  911. asCArray<int> vars;
  912. ctx->bc.GetVarsUsed(vars);
  913. if( reservedVars ) vars.Concatenate(*reservedVars);
  914. offset = AllocateVariableNotIn(dt, true, &vars);
  915. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  916. // Allocate and construct the temporary object
  917. asCByteCode tmpBC(engine);
  918. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  919. // Insert the code before the expression code
  920. tmpBC.AddCode(&ctx->bc);
  921. ctx->bc.AddCode(&tmpBC);
  922. // Assign the evaluated expression to the temporary variable
  923. PrepareForAssignment(&dt, ctx, node);
  924. dt.MakeReference(IsVariableOnHeap(offset));
  925. asCTypeInfo type;
  926. type.Set(dt);
  927. type.isTemporary = true;
  928. type.stackOffset = (short)offset;
  929. if( dt.IsObjectHandle() )
  930. type.isExplicitHandle = true;
  931. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  932. PerformAssignment(&type, &ctx->type, &ctx->bc, node);
  933. ctx->bc.Pop(ctx->type.dataType.GetSizeOnStackDWords());
  934. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  935. ctx->type = type;
  936. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  937. if( dt.IsObject() && !dt.IsObjectHandle() )
  938. ctx->bc.Instr(asBC_RDSPTR);
  939. if( paramType->IsReadOnly() )
  940. ctx->type.dataType.MakeReadOnly(true);
  941. }
  942. }
  943. }
  944. else if( refType == 2 ) // &out
  945. {
  946. // Make sure the variable is not used in the expression
  947. asCArray<int> vars;
  948. ctx->bc.GetVarsUsed(vars);
  949. if( reservedVars ) vars.Concatenate(*reservedVars);
  950. offset = AllocateVariableNotIn(dt, true, &vars);
  951. if( dt.IsPrimitive() )
  952. {
  953. ctx->type.SetVariable(dt, offset, true);
  954. PushVariableOnStack(ctx, true);
  955. }
  956. else
  957. {
  958. // Allocate and construct the temporary object
  959. asCByteCode tmpBC(engine);
  960. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  961. // Insert the code before the expression code
  962. tmpBC.AddCode(&ctx->bc);
  963. ctx->bc.AddCode(&tmpBC);
  964. dt.MakeReference((!dt.IsObject() || dt.IsObjectHandle()));
  965. asCTypeInfo type;
  966. type.Set(dt);
  967. type.isTemporary = true;
  968. type.stackOffset = (short)offset;
  969. ctx->type = type;
  970. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  971. if( dt.IsObject() && !dt.IsObjectHandle() )
  972. ctx->bc.Instr(asBC_RDSPTR);
  973. }
  974. // After the function returns the temporary variable will
  975. // be assigned to the expression, if it is a valid lvalue
  976. }
  977. else if( refType == asTM_INOUTREF )
  978. {
  979. // Literal constants cannot be passed to inout ref arguments
  980. if( !ctx->type.isVariable && ctx->type.isConstant )
  981. {
  982. Error(TXT_NOT_VALID_REFERENCE, node);
  983. }
  984. // Only objects that support object handles
  985. // can be guaranteed to be safe. Local variables are
  986. // already safe, so there is no need to add an extra
  987. // references
  988. if( !engine->ep.allowUnsafeReferences &&
  989. !ctx->type.isVariable &&
  990. ctx->type.dataType.IsObject() &&
  991. !ctx->type.dataType.IsObjectHandle() &&
  992. ctx->type.dataType.GetBehaviour()->addref &&
  993. ctx->type.dataType.GetBehaviour()->release )
  994. {
  995. // Store a handle to the object as local variable
  996. asSExprContext tmp(engine);
  997. asCDataType dt = ctx->type.dataType;
  998. dt.MakeHandle(true);
  999. dt.MakeReference(false);
  1000. asCArray<int> vars;
  1001. ctx->bc.GetVarsUsed(vars);
  1002. if( reservedVars ) vars.Concatenate(*reservedVars);
  1003. offset = AllocateVariableNotIn(dt, true, &vars);
  1004. // Copy the handle
  1005. if( !ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReference() )
  1006. ctx->bc.Instr(asBC_RDSPTR);
  1007. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1008. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  1009. ctx->bc.Pop(AS_PTR_SIZE);
  1010. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1011. dt.MakeHandle(false);
  1012. dt.MakeReference(true);
  1013. // Release previous temporary variable stored in the context (if any)
  1014. if( ctx->type.isTemporary )
  1015. {
  1016. ReleaseTemporaryVariable(ctx->type.stackOffset, &ctx->bc);
  1017. }
  1018. ctx->type.SetVariable(dt, offset, true);
  1019. }
  1020. // Make sure the reference to the value is on the stack
  1021. if( ctx->type.dataType.IsObject() && ctx->type.dataType.IsReference() )
  1022. Dereference(ctx, true);
  1023. else if( ctx->type.isVariable && !ctx->type.dataType.IsObject() )
  1024. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  1025. else if( ctx->type.dataType.IsPrimitive() )
  1026. ctx->bc.Instr(asBC_PshRPtr);
  1027. }
  1028. }
  1029. else
  1030. {
  1031. ProcessPropertyGetAccessor(ctx, node);
  1032. if( dt.IsPrimitive() )
  1033. {
  1034. IsVariableInitialized(&ctx->type, node);
  1035. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  1036. // Implicitly convert primitives to the parameter type
  1037. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true, reservedVars);
  1038. if( ctx->type.isVariable )
  1039. {
  1040. PushVariableOnStack(ctx, dt.IsReference());
  1041. }
  1042. else if( ctx->type.isConstant )
  1043. {
  1044. ConvertToVariable(ctx);
  1045. PushVariableOnStack(ctx, dt.IsReference());
  1046. }
  1047. }
  1048. else
  1049. {
  1050. IsVariableInitialized(&ctx->type, node);
  1051. // Implicitly convert primitives to the parameter type
  1052. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true, reservedVars);
  1053. // Was the conversion successful?
  1054. if( !ctx->type.dataType.IsEqualExceptRef(dt) )
  1055. {
  1056. asCString str;
  1057. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), dt.Format().AddressOf());
  1058. Error(str.AddressOf(), node);
  1059. ctx->type.Set(dt);
  1060. }
  1061. if( dt.IsObjectHandle() )
  1062. ctx->type.isExplicitHandle = true;
  1063. if( dt.IsObject() )
  1064. {
  1065. if( !dt.IsReference() )
  1066. {
  1067. // Objects passed by value must be placed in temporary variables
  1068. // so that they are guaranteed to not be referenced anywhere else.
  1069. // The object must also be allocated on the heap, as the memory will
  1070. // be deleted by in as_callfunc_xxx.
  1071. // TODO: value on stack: How can we avoid this unnecessary allocation?
  1072. PrepareTemporaryObject(node, ctx, reservedVars, true);
  1073. // The implicit conversion shouldn't convert the object to
  1074. // non-reference yet. It will be dereferenced just before the call.
  1075. // Otherwise the object might be missed by the exception handler.
  1076. dt.MakeReference(true);
  1077. }
  1078. else
  1079. {
  1080. // An object passed by reference should place the pointer to
  1081. // the object on the stack.
  1082. dt.MakeReference(false);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. // Don't put any pointer on the stack yet
  1088. if( param.IsReference() || param.IsObject() )
  1089. {
  1090. // &inout parameter may leave the reference on the stack already
  1091. if( refType != 3 )
  1092. {
  1093. ctx->bc.Pop(AS_PTR_SIZE);
  1094. ctx->bc.InstrSHORT(asBC_VAR, ctx->type.stackOffset);
  1095. }
  1096. ProcessDeferredParams(ctx);
  1097. }
  1098. }
  1099. void asCCompiler::PrepareFunctionCall(int funcID, asCByteCode *bc, asCArray<asSExprContext *> &args)
  1100. {
  1101. // When a match has been found, compile the final byte code using correct parameter types
  1102. asCScriptFunction *descr = builder->GetFunctionDescription(funcID);
  1103. // Add code for arguments
  1104. asSExprContext e(engine);
  1105. int n;
  1106. for( n = (int)args.GetLength()-1; n >= 0; n-- )
  1107. {
  1108. // Make sure PrepareArgument doesn't use any variable that is already
  1109. // being used by any of the following argument expressions
  1110. asCArray<int> reservedVars;
  1111. for( int m = n-1; m >= 0; m-- )
  1112. args[m]->bc.GetVarsUsed(reservedVars);
  1113. PrepareArgument2(&e, args[n], &descr->parameterTypes[n], true, descr->inOutFlags[n], &reservedVars);
  1114. }
  1115. bc->AddCode(&e.bc);
  1116. }
  1117. void asCCompiler::MoveArgsToStack(int funcID, asCByteCode *bc, asCArray<asSExprContext *> &args, bool addOneToOffset)
  1118. {
  1119. asCScriptFunction *descr = builder->GetFunctionDescription(funcID);
  1120. int offset = 0;
  1121. if( addOneToOffset )
  1122. offset += AS_PTR_SIZE;
  1123. // Move the objects that are sent by value to the stack just before the call
  1124. for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
  1125. {
  1126. if( descr->parameterTypes[n].IsReference() )
  1127. {
  1128. if( descr->parameterTypes[n].IsObject() && !descr->parameterTypes[n].IsObjectHandle() )
  1129. {
  1130. if( descr->inOutFlags[n] != asTM_INOUTREF )
  1131. {
  1132. if( (args[n]->type.isVariable || args[n]->type.isTemporary) &&
  1133. !IsVariableOnHeap(args[n]->type.stackOffset) )
  1134. // TODO: optimize: Actually the reference can be pushed on the stack directly
  1135. // as the value allocated on the stack is guaranteed to be safe
  1136. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1137. else
  1138. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1139. }
  1140. if( args[n]->type.dataType.IsObjectHandle() )
  1141. bc->InstrWORD(asBC_ChkNullS, (asWORD)offset);
  1142. }
  1143. else if( descr->inOutFlags[n] != asTM_INOUTREF )
  1144. {
  1145. if( descr->parameterTypes[n].GetTokenType() == ttQuestion &&
  1146. args[n]->type.dataType.IsObject() && !args[n]->type.dataType.IsObjectHandle() )
  1147. {
  1148. // Send the object as a reference to the object,
  1149. // and not to the variable holding the object
  1150. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1151. // TODO: optimize: Actually the reference can be pushed on the stack directly
  1152. // as the value allocated on the stack is guaranteed to be safe
  1153. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1154. else
  1155. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1156. }
  1157. else
  1158. {
  1159. if( args[n]->type.dataType.GetObjectType() &&
  1160. (args[n]->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) &&
  1161. args[n]->type.isVariable &&
  1162. IsVariableOnHeap(args[n]->type.stackOffset) )
  1163. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1164. else
  1165. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1166. }
  1167. }
  1168. }
  1169. else if( descr->parameterTypes[n].IsObject() )
  1170. {
  1171. // TODO: value on stack: What can we do to avoid this unnecessary allocation?
  1172. // The object must be allocated on the heap, because this memory will be deleted in as_callfunc_xxx
  1173. asASSERT(IsVariableOnHeap(args[n]->type.stackOffset));
  1174. bc->InstrWORD(asBC_GETOBJ, (asWORD)offset);
  1175. // The temporary variable must not be freed as it will no longer hold an object
  1176. DeallocateVariable(args[n]->type.stackOffset);
  1177. args[n]->type.isTemporary = false;
  1178. }
  1179. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  1180. }
  1181. }
  1182. int asCCompiler::CompileArgumentList(asCScriptNode *node, asCArray<asSExprContext*> &args)
  1183. {
  1184. asASSERT(node->nodeType == snArgList);
  1185. // Count arguments
  1186. asCScriptNode *arg = node->firstChild;
  1187. int argCount = 0;
  1188. while( arg )
  1189. {
  1190. argCount++;
  1191. arg = arg->next;
  1192. }
  1193. // Prepare the arrays
  1194. args.SetLength(argCount);
  1195. int n;
  1196. for( n = 0; n < argCount; n++ )
  1197. args[n] = 0;
  1198. n = argCount-1;
  1199. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1200. bool anyErrors = false;
  1201. arg = node->lastChild;
  1202. while( arg )
  1203. {
  1204. asSExprContext expr(engine);
  1205. int r = CompileAssignment(arg, &expr);
  1206. if( r < 0 ) anyErrors = true;
  1207. args[n] = asNEW(asSExprContext)(engine);
  1208. MergeExprBytecodeAndType(args[n], &expr);
  1209. n--;
  1210. arg = arg->prev;
  1211. }
  1212. return anyErrors ? -1 : 0;
  1213. }
  1214. int asCCompiler::CompileDefaultArgs(asCScriptNode *node, asCArray<asSExprContext*> &args, asCScriptFunction *func)
  1215. {
  1216. bool anyErrors = false;
  1217. asCArray<int> varsUsed;
  1218. int explicitArgs = (int)args.GetLength();
  1219. for( int p = 0; p < explicitArgs; p++ )
  1220. args[p]->bc.GetVarsUsed(varsUsed);
  1221. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1222. args.SetLength(func->parameterTypes.GetLength());
  1223. for( asUINT c = explicitArgs; c < args.GetLength(); c++ )
  1224. args[c] = 0;
  1225. for( int n = (int)func->parameterTypes.GetLength() - 1; n >= explicitArgs; n-- )
  1226. {
  1227. if( func->defaultArgs[n] == 0 ) { anyErrors = true; continue; }
  1228. // Parse the default arg string
  1229. asCParser parser(builder);
  1230. asCScriptCode code;
  1231. code.SetCode("default arg", func->defaultArgs[n]->AddressOf(), false);
  1232. int r = parser.ParseExpression(&code);
  1233. if( r < 0 ) { anyErrors = true; continue; }
  1234. asCScriptNode *arg = parser.GetScriptNode();
  1235. // Temporarily set the script code to the default arg expression
  1236. asCScriptCode *origScript = script;
  1237. script = &code;
  1238. // Don't allow the expression to access local variables
  1239. // TODO: namespace: The default arg should see the symbols declared in the same scope as the function
  1240. isCompilingDefaultArg = true;
  1241. asSExprContext expr(engine);
  1242. r = CompileExpression(arg, &expr);
  1243. isCompilingDefaultArg = false;
  1244. script = origScript;
  1245. if( r < 0 )
  1246. {
  1247. asCString msg;
  1248. msg.Format(TXT_FAILED_TO_COMPILE_DEF_ARG_d_IN_FUNC_s, n, func->GetDeclaration());
  1249. Error(msg.AddressOf(), node);
  1250. anyErrors = true;
  1251. continue;
  1252. }
  1253. args[n] = asNEW(asSExprContext)(engine);
  1254. MergeExprBytecodeAndType(args[n], &expr);
  1255. // Make sure the default arg expression doesn't end up
  1256. // with a variable that is used in a previous expression
  1257. if( args[n]->type.isVariable )
  1258. {
  1259. int offset = args[n]->type.stackOffset;
  1260. if( varsUsed.Exists(offset) )
  1261. {
  1262. // Release the current temporary variable
  1263. ReleaseTemporaryVariable(args[n]->type, 0);
  1264. asCDataType dt = args[n]->type.dataType;
  1265. dt.MakeReference(false);
  1266. int newOffset = AllocateVariableNotIn(dt, true, &varsUsed, IsVariableOnHeap(offset));
  1267. asASSERT( IsVariableOnHeap(offset) == IsVariableOnHeap(newOffset) );
  1268. args[n]->bc.ExchangeVar(offset, newOffset);
  1269. args[n]->type.stackOffset = (short)newOffset;
  1270. args[n]->type.isTemporary = true;
  1271. args[n]->type.isVariable = true;
  1272. }
  1273. }
  1274. }
  1275. return anyErrors ? -1 : 0;
  1276. }
  1277. 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)
  1278. {
  1279. asCArray<int> origFuncs = funcs; // Keep the original list for error message
  1280. asUINT n;
  1281. if( funcs.GetLength() > 0 )
  1282. {
  1283. // Check the number of parameters in the found functions
  1284. for( n = 0; n < funcs.GetLength(); ++n )
  1285. {
  1286. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  1287. if( desc->parameterTypes.GetLength() != args.GetLength() )
  1288. {
  1289. // Count the number of default args
  1290. asUINT defaultArgs = 0;
  1291. for( asUINT d = 0; d < desc->defaultArgs.GetLength(); d++ )
  1292. if( desc->defaultArgs[d] )
  1293. defaultArgs++;
  1294. if( args.GetLength() < desc->parameterTypes.GetLength() - defaultArgs )
  1295. {
  1296. // remove it from the list
  1297. if( n == funcs.GetLength()-1 )
  1298. funcs.PopLast();
  1299. else
  1300. funcs[n] = funcs.PopLast();
  1301. n--;
  1302. }
  1303. }
  1304. }
  1305. // Match functions with the parameters, and discard those that do not match
  1306. asCArray<int> matchingFuncs = funcs;
  1307. for( n = 0; n < args.GetLength(); ++n )
  1308. {
  1309. asCArray<int> tempFuncs;
  1310. MatchArgument(funcs, tempFuncs, &args[n]->type, n, allowObjectConstruct);
  1311. // Intersect the found functions with the list of matching functions
  1312. for( asUINT f = 0; f < matchingFuncs.GetLength(); f++ )
  1313. {
  1314. asUINT c;
  1315. for( c = 0; c < tempFuncs.GetLength(); c++ )
  1316. {
  1317. if( matchingFuncs[f] == tempFuncs[c] )
  1318. break;
  1319. }
  1320. // Was the function a match?
  1321. if( c == tempFuncs.GetLength() )
  1322. {
  1323. // No, remove it from the list
  1324. if( f == matchingFuncs.GetLength()-1 )
  1325. matchingFuncs.PopLast();
  1326. else
  1327. matchingFuncs[f] = matchingFuncs.PopLast();
  1328. f--;
  1329. }
  1330. }
  1331. }
  1332. funcs = matchingFuncs;
  1333. }
  1334. if( !isConstMethod )
  1335. FilterConst(funcs);
  1336. if( funcs.GetLength() != 1 && !silent )
  1337. {
  1338. // Build a readable string of the function with parameter types
  1339. asCString str;
  1340. if( scope != "" )
  1341. {
  1342. if( scope == "::" )
  1343. str = scope;
  1344. else
  1345. str = scope + "::";
  1346. }
  1347. str += name;
  1348. str += "(";
  1349. if( args.GetLength() )
  1350. str += args[0]->type.dataType.Format();
  1351. for( n = 1; n < args.GetLength(); n++ )
  1352. str += ", " + args[n]->type.dataType.Format();
  1353. str += ")";
  1354. if( isConstMethod )
  1355. str += " const";
  1356. if( objectType && scope == "" )
  1357. str = objectType->name + "::" + str;
  1358. if( funcs.GetLength() == 0 )
  1359. {
  1360. str.Format(TXT_NO_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1361. Error(str.AddressOf(), node);
  1362. // Print the list of candidates
  1363. if( origFuncs.GetLength() > 0 )
  1364. {
  1365. int r = 0, c = 0;
  1366. asASSERT( node );
  1367. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  1368. builder->WriteInfo(script->name.AddressOf(), TXT_CANDIDATES_ARE, r, c, false);
  1369. PrintMatchingFuncs(origFuncs, node);
  1370. }
  1371. }
  1372. else
  1373. {
  1374. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1375. Error(str.AddressOf(), node);
  1376. PrintMatchingFuncs(funcs, node);
  1377. }
  1378. }
  1379. }
  1380. void asCCompiler::CompileDeclaration(asCScriptNode *decl, asCByteCode *bc)
  1381. {
  1382. // Get the data type
  1383. asCDataType type = builder->CreateDataTypeFromNode(decl->firstChild, script);
  1384. // Declare all variables in this declaration
  1385. asCScriptNode *node = decl->firstChild->next;
  1386. while( node )
  1387. {
  1388. // Is the type allowed?
  1389. if( !type.CanBeInstanciated() )
  1390. {
  1391. asCString str;
  1392. // TODO: Change to "'type' cannot be declared as variable"
  1393. str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format().AddressOf());
  1394. Error(str.AddressOf(), node);
  1395. // Use int instead to avoid further problems
  1396. type = asCDataType::CreatePrimitive(ttInt, false);
  1397. }
  1398. // Get the name of the identifier
  1399. asCString name(&script->code[node->tokenPos], node->tokenLength);
  1400. // Verify that the name isn't used by a dynamic data type
  1401. if( engine->GetObjectType(name.AddressOf()) != 0 )
  1402. {
  1403. asCString str;
  1404. str.Format(TXT_ILLEGAL_VARIABLE_NAME_s, name.AddressOf());
  1405. Error(str.AddressOf(), node);
  1406. }
  1407. int offset = AllocateVariable(type, false);
  1408. if( variables->DeclareVariable(name.AddressOf(), type, offset, IsVariableOnHeap(offset)) < 0 )
  1409. {
  1410. asCString str;
  1411. str.Format(TXT_s_ALREADY_DECLARED, name.AddressOf());
  1412. Error(str.AddressOf(), node);
  1413. // Don't continue after this error, as it will just
  1414. // lead to more errors that are likely false
  1415. return;
  1416. }
  1417. // Add marker that the variable has been declared
  1418. bc->VarDecl((int)outFunc->variables.GetLength());
  1419. outFunc->AddVariable(name, type, offset);
  1420. // Keep the node for the variable decl
  1421. asCScriptNode *varNode = node;
  1422. node = node->next;
  1423. if( node && node->nodeType == snArgList )
  1424. {
  1425. // Make sure that it is a registered type, and that is isn't a pointer
  1426. if( type.GetObjectType() == 0 || type.IsObjectHandle() )
  1427. {
  1428. Error(TXT_MUST_BE_OBJECT, node);
  1429. }
  1430. else
  1431. {
  1432. // Compile the arguments
  1433. asCArray<asSExprContext *> args;
  1434. if( CompileArgumentList(node, args) >= 0 )
  1435. {
  1436. // Find all constructors
  1437. asCArray<int> funcs;
  1438. asSTypeBehaviour *beh = type.GetBehaviour();
  1439. if( beh )
  1440. {
  1441. if( type.GetObjectType()->flags & asOBJ_REF )
  1442. funcs = beh->factories;
  1443. else
  1444. funcs = beh->constructors;
  1445. }
  1446. asCString str = type.Format();
  1447. MatchFunctions(funcs, args, node, str.AddressOf());
  1448. if( funcs.GetLength() == 1 )
  1449. {
  1450. int r = asSUCCESS;
  1451. // Add the default values for arguments not explicitly supplied
  1452. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  1453. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  1454. r = CompileDefaultArgs(node, args, func);
  1455. if( r == asSUCCESS )
  1456. {
  1457. sVariable *v = variables->GetVariable(name.AddressOf());
  1458. asSExprContext ctx(engine);
  1459. if( v->type.GetObjectType() && (v->type.GetObjectType()->flags & asOBJ_REF) )
  1460. {
  1461. MakeFunctionCall(&ctx, funcs[0], 0, args, node, true, v->stackOffset);
  1462. // Pop the reference left by the function call
  1463. ctx.bc.Pop(AS_PTR_SIZE);
  1464. }
  1465. else
  1466. {
  1467. // When the object is allocated on the heap, the address where the
  1468. // reference will be stored must be pushed on the stack before the
  1469. // arguments. This reference on the stack is safe, even if the script
  1470. // is suspended during the evaluation of the arguments.
  1471. if( v->onHeap )
  1472. ctx.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1473. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  1474. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  1475. // When the object is allocated on the stack, the address to the
  1476. // object is pushed on the stack after the arguments as the object pointer
  1477. if( !v->onHeap )
  1478. ctx.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1479. PerformFunctionCall(funcs[0], &ctx, v->onHeap, &args, type.GetObjectType());
  1480. // TODO: value on stack: This probably has to be done in PerformFunctionCall
  1481. // Mark the object as initialized
  1482. ctx.bc.ObjInfo(v->stackOffset, asOBJ_INIT);
  1483. }
  1484. bc->AddCode(&ctx.bc);
  1485. }
  1486. }
  1487. }
  1488. // Cleanup
  1489. for( asUINT n = 0; n < args.GetLength(); n++ )
  1490. if( args[n] )
  1491. {
  1492. asDELETE(args[n],asSExprContext);
  1493. }
  1494. }
  1495. node = node->next;
  1496. }
  1497. else if( node && node->nodeType == snInitList )
  1498. {
  1499. sVariable *v = variables->GetVariable(name.AddressOf());
  1500. asCTypeInfo ti;
  1501. ti.Set(type);
  1502. ti.isVariable = true;
  1503. ti.isTemporary = false;
  1504. ti.stackOffset = (short)v->stackOffset;
  1505. ti.isLValue = true;
  1506. CompileInitList(&ti, node, bc);
  1507. node = node->next;
  1508. }
  1509. else if( node && node->nodeType == snAssignment )
  1510. {
  1511. asSExprContext ctx(engine);
  1512. // TODO: copy: Here we should look for the best matching constructor, instead of
  1513. // just the copy constructor. Only if no appropriate constructor is
  1514. // available should the assignment operator be used.
  1515. // Call the default constructor here
  1516. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), &ctx.bc, varNode);
  1517. // Compile the expression
  1518. asSExprContext expr(engine);
  1519. int r = CompileAssignment(node, &expr);
  1520. if( r >= 0 )
  1521. {
  1522. if( type.IsPrimitive() )
  1523. {
  1524. if( type.IsReadOnly() && expr.type.isConstant )
  1525. {
  1526. ImplicitConversion(&expr, type, node, asIC_IMPLICIT_CONV);
  1527. sVariable *v = variables->GetVariable(name.AddressOf());
  1528. v->isPureConstant = true;
  1529. v->constantValue = expr.type.qwordValue;
  1530. }
  1531. asSExprContext lctx(engine);
  1532. lctx.type.SetVariable(type, offset, false);
  1533. lctx.type.dataType.MakeReadOnly(false);
  1534. lctx.type.isLValue = true;
  1535. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  1536. ProcessDeferredParams(&ctx);
  1537. }
  1538. else
  1539. {
  1540. // TODO: We can use a copy constructor here
  1541. sVariable *v = variables->GetVariable(name.AddressOf());
  1542. asSExprContext lexpr(engine);
  1543. lexpr.type.Set(type);
  1544. lexpr.type.dataType.MakeReference(v->onHeap);
  1545. // Allow initialization of constant variables
  1546. lexpr.type.dataType.MakeReadOnly(false);
  1547. if( type.IsObjectHandle() )
  1548. lexpr.type.isExplicitHandle = true;
  1549. lexpr.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1550. lexpr.type.stackOffset = (short)v->stackOffset;
  1551. lexpr.type.isVariable = true;
  1552. lexpr.type.isLValue = true;
  1553. // If left expression resolves into a registered type
  1554. // check if the assignment operator is overloaded, and check
  1555. // the type of the right hand expression. If none is found
  1556. // the default action is a direct copy if it is the same type
  1557. // and a simple assignment.
  1558. bool assigned = false;
  1559. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  1560. {
  1561. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  1562. if( assigned )
  1563. {
  1564. // Pop the resulting value
  1565. ctx.bc.Pop(ctx.type.dataType.GetSizeOnStackDWords());
  1566. // Release the argument
  1567. ProcessDeferredParams(&ctx);
  1568. // Release temporary variable that may be allocated by the overloaded operator
  1569. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1570. }
  1571. }
  1572. if( !assigned )
  1573. {
  1574. PrepareForAssignment(&lexpr.type.dataType, &expr, node);
  1575. // If the expression is constant and the variable also is constant
  1576. // then mark the variable as pure constant. This will allow the compiler
  1577. // to optimize expressions with this variable.
  1578. if( v->type.IsReadOnly() && expr.type.isConstant )
  1579. {
  1580. v->isPureConstant = true;
  1581. v->constantValue = expr.type.qwordValue;
  1582. }
  1583. // Add expression code to bytecode
  1584. MergeExprBytecode(&ctx, &expr);
  1585. // Add byte code for storing value of expression in variable
  1586. ctx.bc.AddCode(&lexpr.bc);
  1587. lexpr.type.stackOffset = (short)v->stackOffset;
  1588. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, node->prev);
  1589. // Release temporary variables used by expression
  1590. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  1591. ctx.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  1592. ProcessDeferredParams(&ctx);
  1593. }
  1594. }
  1595. }
  1596. node = node->next;
  1597. bc->AddCode(&ctx.bc);
  1598. // TODO: Can't this leave deferred output params without being compiled?
  1599. }
  1600. else
  1601. {
  1602. // Call the default constructor here if no explicit initialization is done
  1603. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), bc, varNode);
  1604. }
  1605. }
  1606. }
  1607. void asCCompiler::CompileInitList(asCTypeInfo *var, asCScriptNode *node, asCByteCode *bc)
  1608. {
  1609. // Check if the type supports initialization lists
  1610. if( var->dataType.GetObjectType() == 0 ||
  1611. var->dataType.GetBehaviour()->listFactory == 0 ||
  1612. var->dataType.IsObjectHandle() )
  1613. {
  1614. asCString str;
  1615. str.Format(TXT_INIT_LIST_CANNOT_BE_USED_WITH_s, var->dataType.Format().AddressOf());
  1616. Error(str.AddressOf(), node);
  1617. return;
  1618. }
  1619. // Count the number of elements and initialize the array with the correct size
  1620. int countElements = 0;
  1621. asCScriptNode *el = node->firstChild;
  1622. while( el )
  1623. {
  1624. countElements++;
  1625. el = el->next;
  1626. }
  1627. // Construct the array with the size elements
  1628. // TODO: value on stack: This needs to support value types on the stack as well
  1629. // Find the list factory
  1630. // TODO: initlist: Add support for value types as well
  1631. int funcId = var->dataType.GetBehaviour()->listFactory;
  1632. asCArray<asSExprContext *> args;
  1633. asSExprContext arg1(engine);
  1634. arg1.bc.InstrDWORD(asBC_PshC4, countElements);
  1635. arg1.type.Set(asCDataType::CreatePrimitive(ttUInt, false));
  1636. args.PushLast(&arg1);
  1637. asSExprContext ctx(engine);
  1638. PrepareFunctionCall(funcId, &ctx.bc, args);
  1639. MoveArgsToStack(funcId, &ctx.bc, args, false);
  1640. if( var->isVariable )
  1641. {
  1642. // Call factory and store the handle in the given variable
  1643. PerformFunctionCall(funcId, &ctx, false, &args, 0, true, var->stackOffset);
  1644. ctx.bc.Pop(AS_PTR_SIZE);
  1645. }
  1646. else
  1647. {
  1648. PerformFunctionCall(funcId, &ctx, false, &args);
  1649. // Store the returned handle in the global variable
  1650. ctx.bc.Instr(asBC_RDSPTR);
  1651. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  1652. ctx.bc.InstrPTR(asBC_REFCPY, var->dataType.GetObjectType());
  1653. ctx.bc.Pop(AS_PTR_SIZE);
  1654. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  1655. }
  1656. bc->AddCode(&ctx.bc);
  1657. // TODO: initlist: Should we have a special indexing operator for this? How can we support
  1658. // initialization lists with different types for different elements? Maybe
  1659. // by using the variable arguments the initialization can be done with one
  1660. // call, passing all the elements as arguments. The registered function can
  1661. // then traverse them however it wants.
  1662. // Find the indexing operator that is not read-only that will be used for all elements
  1663. asCDataType retType;
  1664. retType = var->dataType.GetSubType();
  1665. retType.MakeReference(true);
  1666. retType.MakeReadOnly(false);
  1667. funcId = 0;
  1668. for( asUINT n = 0; n < var->dataType.GetObjectType()->methods.GetLength(); n++ )
  1669. {
  1670. asCScriptFunction *desc = builder->GetFunctionDescription(var->dataType.GetObjectType()->methods[n]);
  1671. if( !desc->isReadOnly &&
  1672. desc->parameterTypes.GetLength() == 1 &&
  1673. (desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttUInt, false) ||
  1674. desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttInt, false)) &&
  1675. desc->returnType == retType &&
  1676. desc->name == "opIndex" )
  1677. {
  1678. funcId = var->dataType.GetObjectType()->methods[n];
  1679. break;
  1680. }
  1681. }
  1682. if( funcId == 0 )
  1683. {
  1684. Error(TXT_NO_APPROPRIATE_INDEX_OPERATOR, node);
  1685. return;
  1686. }
  1687. asUINT index = 0;
  1688. el = node->firstChild;
  1689. while( el )
  1690. {
  1691. if( el->nodeType == snAssignment || el->nodeType == snInitList )
  1692. {
  1693. asSExprContext lctx(engine);
  1694. asSExprContext rctx(engine);
  1695. if( el->nodeType == snAssignment )
  1696. {
  1697. // Compile the assignment expression
  1698. CompileAssignment(el, &rctx);
  1699. }
  1700. else if( el->nodeType == snInitList )
  1701. {
  1702. int offset = AllocateVariable(var->dataType.GetSubType(), true);
  1703. rctx.type.Set(var->dataType.GetSubType());
  1704. rctx.type.isVariable = true;
  1705. rctx.type.isTemporary = true;
  1706. rctx.type.stackOffset = (short)offset;
  1707. CompileInitList(&rctx.type, el, &rctx.bc);
  1708. // Put the object on the stack
  1709. rctx.bc.InstrSHORT(asBC_PSF, rctx.type.stackOffset);
  1710. // It is a reference that we place on the stack
  1711. rctx.type.dataType.MakeReference(true);
  1712. }
  1713. // Compile the lvalue
  1714. lctx.bc.InstrDWORD(asBC_PshC4, index);
  1715. if( var->isVariable )
  1716. lctx.bc.InstrSHORT(asBC_PSF, var->stackOffset);
  1717. else
  1718. lctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  1719. lctx.bc.Instr(asBC_RDSPTR);
  1720. lctx.bc.Call(asBC_CALLSYS, funcId, 1+AS_PTR_SIZE);
  1721. if( !var->dataType.GetSubType().IsPrimitive() )
  1722. lctx.bc.Instr(asBC_PshRPtr);
  1723. lctx.type.Set(var->dataType.GetSubType());
  1724. if( !lctx.type.dataType.IsObject() || lctx.type.dataType.IsObjectHandle() )
  1725. lctx.type.dataType.MakeReference(true);
  1726. // If the element type is handles, then we're expected to do handle assignments
  1727. if( lctx.type.dataType.IsObjectHandle() )
  1728. lctx.type.isExplicitHandle = true;
  1729. lctx.type.isLValue = true;
  1730. asSExprContext ctx(engine);
  1731. DoAssignment(&ctx, &lctx, &rctx, el, el, ttAssignment, el);
  1732. if( !lctx.type.dataType.IsPrimitive() )
  1733. ctx.bc.Pop(AS_PTR_SIZE);
  1734. // Release temporary variables used by expression
  1735. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1736. ProcessDeferredParams(&ctx);
  1737. bc->AddCode(&ctx.bc);
  1738. }
  1739. el = el->next;
  1740. index++;
  1741. }
  1742. }
  1743. void asCCompiler::CompileStatement(asCScriptNode *statement, bool *hasReturn, asCByteCode *bc)
  1744. {
  1745. *hasReturn = false;
  1746. if( statement->nodeType == snStatementBlock )
  1747. CompileStatementBlock(statement, true, hasReturn, bc);
  1748. else if( statement->nodeType == snIf )
  1749. CompileIfStatement(statement, hasReturn, bc);
  1750. else if( statement->nodeType == snFor )
  1751. CompileForStatement(statement, bc);
  1752. else if( statement->nodeType == snWhile )
  1753. CompileWhileStatement(statement, bc);
  1754. else if( statement->nodeType == snDoWhile )
  1755. CompileDoWhileStatement(statement, bc);
  1756. else if( statement->nodeType == snExpressionStatement )
  1757. CompileExpressionStatement(statement, bc);
  1758. else if( statement->nodeType == snBreak )
  1759. CompileBreakStatement(statement, bc);
  1760. else if( statement->nodeType == snContinue )
  1761. CompileContinueStatement(statement, bc);
  1762. else if( statement->nodeType == snSwitch )
  1763. CompileSwitchStatement(statement, hasReturn, bc);
  1764. else if( statement->nodeType == snReturn )
  1765. {
  1766. CompileReturnStatement(statement, bc);
  1767. *hasReturn = true;
  1768. }
  1769. }
  1770. void asCCompiler::CompileSwitchStatement(asCScriptNode *snode, bool *, asCByteCode *bc)
  1771. {
  1772. // TODO: inheritance: Must guarantee that all options in the switch case call a constructor, or that none call it.
  1773. // Reserve label for break statements
  1774. int breakLabel = nextLabel++;
  1775. breakLabels.PushLast(breakLabel);
  1776. // Add a variable scope that will be used by CompileBreak
  1777. // to know where to stop deallocating variables
  1778. AddVariableScope(true, false);
  1779. //---------------------------
  1780. // Compile the switch expression
  1781. //-------------------------------
  1782. // Compile the switch expression
  1783. asSExprContext expr(engine);
  1784. CompileAssignment(snode->firstChild, &expr);
  1785. // Verify that the expression is a primitive type
  1786. if( !expr.type.dataType.IsIntegerType() && !expr.type.dataType.IsUnsignedType() && !expr.type.dataType.IsEnumType() )
  1787. {
  1788. Error(TXT_SWITCH_MUST_BE_INTEGRAL, snode->firstChild);
  1789. return;
  1790. }
  1791. ProcessPropertyGetAccessor(&expr, snode);
  1792. // TODO: Need to support 64bit integers
  1793. // Convert the expression to a 32bit variable
  1794. asCDataType to;
  1795. if( expr.type.dataType.IsIntegerType() || expr.type.dataType.IsEnumType() )
  1796. to.SetTokenType(ttInt);
  1797. else if( expr.type.dataType.IsUnsignedType() )
  1798. to.SetTokenType(ttUInt);
  1799. // Make sure the value is in a variable
  1800. if( expr.type.dataType.IsReference() )
  1801. ConvertToVariable(&expr);
  1802. ImplicitConversion(&expr, to, snode->firstChild, asIC_IMPLICIT_CONV, true);
  1803. ConvertToVariable(&expr);
  1804. int offset = expr.type.stackOffset;
  1805. ProcessDeferredParams(&expr);
  1806. //-------------------------------
  1807. // Determine case values and labels
  1808. //--------------------------------
  1809. // Remember the first label so that we can later pass the
  1810. // correct label to each CompileCase()
  1811. int firstCaseLabel = nextLabel;
  1812. int defaultLabel = 0;
  1813. asCArray<int> caseValues;
  1814. asCArray<int> caseLabels;
  1815. // Compile all case comparisons and make them jump to the right label
  1816. asCScriptNode *cnode = snode->firstChild->next;
  1817. while( cnode )
  1818. {
  1819. // Each case should have a constant expression
  1820. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  1821. {
  1822. // Compile expression
  1823. asSExprContext c(engine);
  1824. CompileExpression(cnode->firstChild, &c);
  1825. // Verify that the result is a constant
  1826. if( !c.type.isConstant )
  1827. Error(TXT_SWITCH_CASE_MUST_BE_CONSTANT, cnode->firstChild);
  1828. // Verify that the result is an integral number
  1829. if( !c.type.dataType.IsIntegerType() && !c.type.dataType.IsUnsignedType() && !c.type.dataType.IsEnumType() )
  1830. Error(TXT_SWITCH_MUST_BE_INTEGRAL, cnode->firstChild);
  1831. ImplicitConversion(&c, to, cnode->firstChild, asIC_IMPLICIT_CONV, true);
  1832. // Has this case been declared already?
  1833. if( caseValues.IndexOf(c.type.intValue) >= 0 )
  1834. {
  1835. Error(TXT_DUPLICATE_SWITCH_CASE, cnode->firstChild);
  1836. }
  1837. // TODO: Optimize: We can insert the numbers sorted already
  1838. // Store constant for later use
  1839. caseValues.PushLast(c.type.intValue);
  1840. // Reserve label for this case
  1841. caseLabels.PushLast(nextLabel++);
  1842. }
  1843. else
  1844. {
  1845. // Is default the last case?
  1846. if( cnode->next )
  1847. {
  1848. Error(TXT_DEFAULT_MUST_BE_LAST, cnode);
  1849. break;
  1850. }
  1851. // Reserve label for this case
  1852. defaultLabel = nextLabel++;
  1853. }
  1854. cnode = cnode->next;
  1855. }
  1856. // check for empty switch
  1857. if (caseValues.GetLength() == 0)
  1858. {
  1859. Error(TXT_EMPTY_SWITCH, snode);
  1860. return;
  1861. }
  1862. if( defaultLabel == 0 )
  1863. defaultLabel = breakLabel;
  1864. //---------------------------------
  1865. // Output the optimized case comparisons
  1866. // with jumps to the case code
  1867. //------------------------------------
  1868. // Sort the case values by increasing value. Do the sort together with the labels
  1869. // A simple bubble sort is sufficient since we don't expect a huge number of values
  1870. for( asUINT fwd = 1; fwd < caseValues.GetLength(); fwd++ )
  1871. {
  1872. for( int bck = fwd - 1; bck >= 0; bck-- )
  1873. {
  1874. int bckp = bck + 1;
  1875. if( caseValues[bck] > caseValues[bckp] )
  1876. {
  1877. // Swap the values in both arrays
  1878. int swap = caseValues[bckp];
  1879. caseValues[bckp] = caseValues[bck];
  1880. caseValues[bck] = swap;
  1881. swap = caseLabels[bckp];
  1882. caseLabels[bckp] = caseLabels[bck];
  1883. caseLabels[bck] = swap;
  1884. }
  1885. else
  1886. break;
  1887. }
  1888. }
  1889. // Find ranges of consecutive numbers
  1890. asCArray<int> ranges;
  1891. ranges.PushLast(0);
  1892. asUINT n;
  1893. for( n = 1; n < caseValues.GetLength(); ++n )
  1894. {
  1895. // We can join numbers that are less than 5 numbers
  1896. // apart since the output code will still be smaller
  1897. if( caseValues[n] > caseValues[n-1] + 5 )
  1898. ranges.PushLast(n);
  1899. }
  1900. // If the value is larger than the largest case value, jump to default
  1901. int tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1902. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[caseValues.GetLength()-1]);
  1903. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  1904. expr.bc.InstrDWORD(asBC_JP, defaultLabel);
  1905. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1906. // TODO: optimize: We could possibly optimize this even more by doing a
  1907. // binary search instead of a linear search through the ranges
  1908. // For each range
  1909. int range;
  1910. for( range = 0; range < (int)ranges.GetLength(); range++ )
  1911. {
  1912. // Find the largest value in this range
  1913. int maxRange = caseValues[ranges[range]];
  1914. int index = ranges[range];
  1915. for( ; (index < (int)caseValues.GetLength()) && (caseValues[index] <= maxRange + 5); index++ )
  1916. maxRange = caseValues[index];
  1917. // If there are only 2 numbers then it is better to compare them directly
  1918. if( index - ranges[range] > 2 )
  1919. {
  1920. // If the value is smaller than the smallest case value in the range, jump to default
  1921. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1922. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  1923. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  1924. expr.bc.InstrDWORD(asBC_JS, defaultLabel);
  1925. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1926. int nextRangeLabel = nextLabel++;
  1927. // If this is the last range we don't have to make this test
  1928. if( range < (int)ranges.GetLength() - 1 )
  1929. {
  1930. // If the value is larger than the largest case value in the range, jump to the next range
  1931. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1932. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, maxRange);
  1933. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  1934. expr.bc.InstrDWORD(asBC_JP, nextRangeLabel);
  1935. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1936. }
  1937. // Jump forward according to the value
  1938. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1939. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  1940. expr.bc.InstrW_W_W(asBC_SUBi, tmpOffset, offset, tmpOffset);
  1941. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1942. expr.bc.JmpP(tmpOffset, maxRange - caseValues[ranges[range]]);
  1943. // Add the list of jumps to the correct labels (any holes, jump to default)
  1944. index = ranges[range];
  1945. for( int n = caseValues[index]; n <= maxRange; n++ )
  1946. {
  1947. if( caseValues[index] == n )
  1948. expr.bc.InstrINT(asBC_JMP, caseLabels[index++]);
  1949. else
  1950. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  1951. }
  1952. expr.bc.Label((short)nextRangeLabel);
  1953. }
  1954. else
  1955. {
  1956. // Simply make a comparison with each value
  1957. int n;
  1958. for( n = ranges[range]; n < index; ++n )
  1959. {
  1960. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  1961. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[n]);
  1962. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  1963. expr.bc.InstrDWORD(asBC_JZ, caseLabels[n]);
  1964. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  1965. }
  1966. }
  1967. }
  1968. // Catch any value that falls trough
  1969. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  1970. // Release the temporary variable previously stored
  1971. ReleaseTemporaryVariable(expr.type, &expr.bc);
  1972. //----------------------------------
  1973. // Output case implementations
  1974. //----------------------------------
  1975. // Compile case implementations, each one with the label before it
  1976. cnode = snode->firstChild->next;
  1977. while( cnode )
  1978. {
  1979. // Each case should have a constant expression
  1980. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  1981. {
  1982. expr.bc.Label((short)firstCaseLabel++);
  1983. CompileCase(cnode->firstChild->next, &expr.bc);
  1984. }
  1985. else
  1986. {
  1987. expr.bc.Label((short)defaultLabel);
  1988. // Is default the last case?
  1989. if( cnode->next )
  1990. {
  1991. // We've already reported this error
  1992. break;
  1993. }
  1994. CompileCase(cnode->firstChild, &expr.bc);
  1995. }
  1996. cnode = cnode->next;
  1997. }
  1998. //--------------------------------
  1999. bc->AddCode(&expr.bc);
  2000. // Add break label
  2001. bc->Label((short)breakLabel);
  2002. breakLabels.PopLast();
  2003. RemoveVariableScope();
  2004. }
  2005. void asCCompiler::CompileCase(asCScriptNode *node, asCByteCode *bc)
  2006. {
  2007. bool isFinished = false;
  2008. bool hasReturn = false;
  2009. while( node )
  2010. {
  2011. if( hasReturn || isFinished )
  2012. {
  2013. Warning(TXT_UNREACHABLE_CODE, node);
  2014. break;
  2015. }
  2016. if( node->nodeType == snBreak || node->nodeType == snContinue )
  2017. isFinished = true;
  2018. asCByteCode statement(engine);
  2019. if( node->nodeType == snDeclaration )
  2020. {
  2021. Error(TXT_DECL_IN_SWITCH, node);
  2022. // Compile it anyway to avoid further compiler errors
  2023. CompileDeclaration(node, &statement);
  2024. }
  2025. else
  2026. CompileStatement(node, &hasReturn, &statement);
  2027. LineInstr(bc, node->tokenPos);
  2028. bc->AddCode(&statement);
  2029. if( !hasCompileErrors )
  2030. asASSERT( tempVariables.GetLength() == 0 );
  2031. node = node->next;
  2032. }
  2033. }
  2034. void asCCompiler::CompileIfStatement(asCScriptNode *inode, bool *hasReturn, asCByteCode *bc)
  2035. {
  2036. // We will use one label for the if statement
  2037. // and possibly another for the else statement
  2038. int afterLabel = nextLabel++;
  2039. // Compile the expression
  2040. asSExprContext expr(engine);
  2041. CompileAssignment(inode->firstChild, &expr);
  2042. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2043. {
  2044. Error(TXT_EXPR_MUST_BE_BOOL, inode->firstChild);
  2045. expr.type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 1);
  2046. }
  2047. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2048. ProcessDeferredParams(&expr);
  2049. if( !expr.type.isConstant )
  2050. {
  2051. ProcessPropertyGetAccessor(&expr, inode);
  2052. ConvertToVariable(&expr);
  2053. // Add byte code from the expression
  2054. bc->AddCode(&expr.bc);
  2055. // Add a test
  2056. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2057. bc->Instr(asBC_ClrHi);
  2058. bc->InstrDWORD(asBC_JZ, afterLabel);
  2059. ReleaseTemporaryVariable(expr.type, bc);
  2060. }
  2061. else if( expr.type.dwordValue == 0 )
  2062. {
  2063. // Jump to the else case
  2064. bc->InstrINT(asBC_JMP, afterLabel);
  2065. // TODO: Should we warn that the expression will always go to the else?
  2066. }
  2067. // Compile the if statement
  2068. bool origIsConstructorCalled = m_isConstructorCalled;
  2069. bool hasReturn1;
  2070. asCByteCode ifBC(engine);
  2071. CompileStatement(inode->firstChild->next, &hasReturn1, &ifBC);
  2072. // Add the byte code
  2073. LineInstr(bc, inode->firstChild->next->tokenPos);
  2074. bc->AddCode(&ifBC);
  2075. if( inode->firstChild->next->nodeType == snExpressionStatement && inode->firstChild->next->firstChild == 0 )
  2076. {
  2077. // Don't allow if( expr );
  2078. Error(TXT_IF_WITH_EMPTY_STATEMENT, inode->firstChild->next);
  2079. }
  2080. // If one of the statements call the constructor, the other must as well
  2081. // otherwise it is possible the constructor is never called
  2082. bool constructorCall1 = false;
  2083. bool constructorCall2 = false;
  2084. if( !origIsConstructorCalled && m_isConstructorCalled )
  2085. constructorCall1 = true;
  2086. // Do we have an else statement?
  2087. if( inode->firstChild->next != inode->lastChild )
  2088. {
  2089. // Reset the constructor called flag so the else statement can call the constructor too
  2090. m_isConstructorCalled = origIsConstructorCalled;
  2091. int afterElse = 0;
  2092. if( !hasReturn1 )
  2093. {
  2094. afterElse = nextLabel++;
  2095. // Add jump to after the else statement
  2096. bc->InstrINT(asBC_JMP, afterElse);
  2097. }
  2098. // Add label for the else statement
  2099. bc->Label((short)afterLabel);
  2100. bool hasReturn2;
  2101. asCByteCode elseBC(engine);
  2102. CompileStatement(inode->lastChild, &hasReturn2, &elseBC);
  2103. // Add byte code for the else statement
  2104. LineInstr(bc, inode->lastChild->tokenPos);
  2105. bc->AddCode(&elseBC);
  2106. if( inode->lastChild->nodeType == snExpressionStatement && inode->lastChild->firstChild == 0 )
  2107. {
  2108. // Don't allow if( expr ) {} else;
  2109. Error(TXT_ELSE_WITH_EMPTY_STATEMENT, inode->lastChild);
  2110. }
  2111. if( !hasReturn1 )
  2112. {
  2113. // Add label for the end of else statement
  2114. bc->Label((short)afterElse);
  2115. }
  2116. // The if statement only has return if both alternatives have
  2117. *hasReturn = hasReturn1 && hasReturn2;
  2118. if( !origIsConstructorCalled && m_isConstructorCalled )
  2119. constructorCall2 = true;
  2120. }
  2121. else
  2122. {
  2123. // Add label for the end of if statement
  2124. bc->Label((short)afterLabel);
  2125. *hasReturn = false;
  2126. }
  2127. // Make sure both or neither conditions call a constructor
  2128. if( (constructorCall1 && !constructorCall2) ||
  2129. (constructorCall2 && !constructorCall1) )
  2130. {
  2131. Error(TXT_BOTH_CONDITIONS_MUST_CALL_CONSTRUCTOR, inode);
  2132. }
  2133. m_isConstructorCalled = origIsConstructorCalled || constructorCall1 || constructorCall2;
  2134. }
  2135. void asCCompiler::CompileForStatement(asCScriptNode *fnode, asCByteCode *bc)
  2136. {
  2137. // TODO: optimize: We should be able to remove the static JMP to the beginning of the loop by rearranging the
  2138. // byte code a bit.
  2139. //
  2140. // init
  2141. // jump to before
  2142. // begin:
  2143. // statements
  2144. // continue:
  2145. // next
  2146. // before:
  2147. // condition
  2148. // if loop jump to begin
  2149. // break:
  2150. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2151. AddVariableScope(true, true);
  2152. // We will use three labels for the for loop
  2153. int beforeLabel = nextLabel++;
  2154. int afterLabel = nextLabel++;
  2155. int continueLabel = nextLabel++;
  2156. continueLabels.PushLast(continueLabel);
  2157. breakLabels.PushLast(afterLabel);
  2158. //---------------------------------------
  2159. // Compile the initialization statement
  2160. asCByteCode initBC(engine);
  2161. if( fnode->firstChild->nodeType == snDeclaration )
  2162. CompileDeclaration(fnode->firstChild, &initBC);
  2163. else
  2164. CompileExpressionStatement(fnode->firstChild, &initBC);
  2165. //-----------------------------------
  2166. // Compile the condition statement
  2167. asSExprContext expr(engine);
  2168. asCScriptNode *second = fnode->firstChild->next;
  2169. if( second->firstChild )
  2170. {
  2171. int r = CompileAssignment(second->firstChild, &expr);
  2172. if( r >= 0 )
  2173. {
  2174. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2175. Error(TXT_EXPR_MUST_BE_BOOL, second);
  2176. else
  2177. {
  2178. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2179. ProcessDeferredParams(&expr);
  2180. ProcessPropertyGetAccessor(&expr, second);
  2181. // If expression is false exit the loop
  2182. ConvertToVariable(&expr);
  2183. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2184. expr.bc.Instr(asBC_ClrHi);
  2185. expr.bc.InstrDWORD(asBC_JZ, afterLabel);
  2186. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2187. }
  2188. }
  2189. }
  2190. //---------------------------
  2191. // Compile the increment statement
  2192. asCByteCode nextBC(engine);
  2193. asCScriptNode *third = second->next;
  2194. if( third->nodeType == snExpressionStatement )
  2195. CompileExpressionStatement(third, &nextBC);
  2196. //------------------------------
  2197. // Compile loop statement
  2198. bool hasReturn;
  2199. asCByteCode forBC(engine);
  2200. CompileStatement(fnode->lastChild, &hasReturn, &forBC);
  2201. //-------------------------------
  2202. // Join the code pieces
  2203. bc->AddCode(&initBC);
  2204. bc->Label((short)beforeLabel);
  2205. // Add a suspend bytecode inside the loop to guarantee
  2206. // that the application can suspend the execution
  2207. bc->Instr(asBC_SUSPEND);
  2208. bc->InstrWORD(asBC_JitEntry, 0);
  2209. bc->AddCode(&expr.bc);
  2210. LineInstr(bc, fnode->lastChild->tokenPos);
  2211. bc->AddCode(&forBC);
  2212. bc->Label((short)continueLabel);
  2213. bc->AddCode(&nextBC);
  2214. bc->InstrINT(asBC_JMP, beforeLabel);
  2215. bc->Label((short)afterLabel);
  2216. continueLabels.PopLast();
  2217. breakLabels.PopLast();
  2218. // Deallocate variables in this block, in reverse order
  2219. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  2220. {
  2221. sVariable *v = variables->variables[n];
  2222. // Call variable destructors here, for variables not yet destroyed
  2223. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  2224. // Don't deallocate function parameters
  2225. if( v->stackOffset > 0 )
  2226. DeallocateVariable(v->stackOffset);
  2227. }
  2228. RemoveVariableScope();
  2229. }
  2230. void asCCompiler::CompileWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2231. {
  2232. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2233. AddVariableScope(true, true);
  2234. // We will use two labels for the while loop
  2235. int beforeLabel = nextLabel++;
  2236. int afterLabel = nextLabel++;
  2237. continueLabels.PushLast(beforeLabel);
  2238. breakLabels.PushLast(afterLabel);
  2239. // Add label before the expression
  2240. bc->Label((short)beforeLabel);
  2241. // Compile expression
  2242. asSExprContext expr(engine);
  2243. CompileAssignment(wnode->firstChild, &expr);
  2244. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2245. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2246. else
  2247. {
  2248. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2249. ProcessDeferredParams(&expr);
  2250. ProcessPropertyGetAccessor(&expr, wnode);
  2251. // Add byte code for the expression
  2252. ConvertToVariable(&expr);
  2253. bc->AddCode(&expr.bc);
  2254. // Jump to end of statement if expression is false
  2255. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2256. bc->Instr(asBC_ClrHi);
  2257. bc->InstrDWORD(asBC_JZ, afterLabel);
  2258. ReleaseTemporaryVariable(expr.type, bc);
  2259. }
  2260. // Add a suspend bytecode inside the loop to guarantee
  2261. // that the application can suspend the execution
  2262. bc->Instr(asBC_SUSPEND);
  2263. bc->InstrWORD(asBC_JitEntry, 0);
  2264. // Compile statement
  2265. bool hasReturn;
  2266. asCByteCode whileBC(engine);
  2267. CompileStatement(wnode->lastChild, &hasReturn, &whileBC);
  2268. // Add byte code for the statement
  2269. LineInstr(bc, wnode->lastChild->tokenPos);
  2270. bc->AddCode(&whileBC);
  2271. // Jump to the expression
  2272. bc->InstrINT(asBC_JMP, beforeLabel);
  2273. // Add label after the statement
  2274. bc->Label((short)afterLabel);
  2275. continueLabels.PopLast();
  2276. breakLabels.PopLast();
  2277. RemoveVariableScope();
  2278. }
  2279. void asCCompiler::CompileDoWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2280. {
  2281. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2282. AddVariableScope(true, true);
  2283. // We will use two labels for the while loop
  2284. int beforeLabel = nextLabel++;
  2285. int beforeTest = nextLabel++;
  2286. int afterLabel = nextLabel++;
  2287. continueLabels.PushLast(beforeTest);
  2288. breakLabels.PushLast(afterLabel);
  2289. // Add label before the statement
  2290. bc->Label((short)beforeLabel);
  2291. // Compile statement
  2292. bool hasReturn;
  2293. asCByteCode whileBC(engine);
  2294. CompileStatement(wnode->firstChild, &hasReturn, &whileBC);
  2295. // Add byte code for the statement
  2296. LineInstr(bc, wnode->firstChild->tokenPos);
  2297. bc->AddCode(&whileBC);
  2298. // Add label before the expression
  2299. bc->Label((short)beforeTest);
  2300. // Add a suspend bytecode inside the loop to guarantee
  2301. // that the application can suspend the execution
  2302. bc->Instr(asBC_SUSPEND);
  2303. bc->InstrWORD(asBC_JitEntry, 0);
  2304. // Add a line instruction
  2305. LineInstr(bc, wnode->lastChild->tokenPos);
  2306. // Compile expression
  2307. asSExprContext expr(engine);
  2308. CompileAssignment(wnode->lastChild, &expr);
  2309. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2310. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2311. else
  2312. {
  2313. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2314. ProcessDeferredParams(&expr);
  2315. ProcessPropertyGetAccessor(&expr, wnode);
  2316. // Add byte code for the expression
  2317. ConvertToVariable(&expr);
  2318. bc->AddCode(&expr.bc);
  2319. // Jump to next iteration if expression is true
  2320. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2321. bc->Instr(asBC_ClrHi);
  2322. bc->InstrDWORD(asBC_JNZ, beforeLabel);
  2323. ReleaseTemporaryVariable(expr.type, bc);
  2324. }
  2325. // Add label after the statement
  2326. bc->Label((short)afterLabel);
  2327. continueLabels.PopLast();
  2328. breakLabels.PopLast();
  2329. RemoveVariableScope();
  2330. }
  2331. void asCCompiler::CompileBreakStatement(asCScriptNode *node, asCByteCode *bc)
  2332. {
  2333. if( breakLabels.GetLength() == 0 )
  2334. {
  2335. Error(TXT_INVALID_BREAK, node);
  2336. return;
  2337. }
  2338. // Add destructor calls for all variables that will go out of scope
  2339. // Put this clean up in a block to allow exception handler to understand them
  2340. bc->Block(true);
  2341. asCVariableScope *vs = variables;
  2342. while( !vs->isBreakScope )
  2343. {
  2344. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2345. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2346. vs = vs->parent;
  2347. }
  2348. bc->Block(false);
  2349. bc->InstrINT(asBC_JMP, breakLabels[breakLabels.GetLength()-1]);
  2350. }
  2351. void asCCompiler::CompileContinueStatement(asCScriptNode *node, asCByteCode *bc)
  2352. {
  2353. if( continueLabels.GetLength() == 0 )
  2354. {
  2355. Error(TXT_INVALID_CONTINUE, node);
  2356. return;
  2357. }
  2358. // Add destructor calls for all variables that will go out of scope
  2359. // Put this clean up in a block to allow exception handler to understand them
  2360. bc->Block(true);
  2361. asCVariableScope *vs = variables;
  2362. while( !vs->isContinueScope )
  2363. {
  2364. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2365. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2366. vs = vs->parent;
  2367. }
  2368. bc->Block(false);
  2369. bc->InstrINT(asBC_JMP, continueLabels[continueLabels.GetLength()-1]);
  2370. }
  2371. void asCCompiler::CompileExpressionStatement(asCScriptNode *enode, asCByteCode *bc)
  2372. {
  2373. if( enode->firstChild )
  2374. {
  2375. // Compile the expression
  2376. asSExprContext expr(engine);
  2377. CompileAssignment(enode->firstChild, &expr);
  2378. // Pop the value from the stack
  2379. if( !expr.type.dataType.IsPrimitive() )
  2380. expr.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  2381. // Release temporary variables used by expression
  2382. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2383. ProcessDeferredParams(&expr);
  2384. bc->AddCode(&expr.bc);
  2385. }
  2386. }
  2387. void asCCompiler::PrepareTemporaryObject(asCScriptNode *node, asSExprContext *ctx, asCArray<int> *reservedVars, bool forceOnHeap)
  2388. {
  2389. // If the object already is stored in temporary variable then nothing needs to be done
  2390. // Note, a type can be temporary without being a variable, in which case it is holding off
  2391. // on releasing a previously used object.
  2392. if( ctx->type.isTemporary && ctx->type.isVariable &&
  2393. !(forceOnHeap && !IsVariableOnHeap(ctx->type.stackOffset)) )
  2394. {
  2395. // If the temporary object is currently not a reference
  2396. // the expression needs to be reevaluated to a reference
  2397. if( !ctx->type.dataType.IsReference() )
  2398. {
  2399. ctx->bc.Pop(AS_PTR_SIZE);
  2400. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  2401. ctx->type.dataType.MakeReference(true);
  2402. }
  2403. return;
  2404. }
  2405. // Allocate temporary variable
  2406. asCDataType dt = ctx->type.dataType;
  2407. dt.MakeReference(false);
  2408. dt.MakeReadOnly(false);
  2409. int offset = AllocateVariableNotIn(dt, true, reservedVars, forceOnHeap);
  2410. // Objects stored on the stack are not considered references
  2411. dt.MakeReference(IsVariableOnHeap(offset));
  2412. asCTypeInfo lvalue;
  2413. lvalue.Set(dt);
  2414. lvalue.isTemporary = true;
  2415. lvalue.stackOffset = (short)offset;
  2416. lvalue.isVariable = true;
  2417. lvalue.isExplicitHandle = ctx->type.isExplicitHandle;
  2418. if( (!dt.IsObjectHandle() || (dt.GetObjectType() && (dt.GetObjectType()->flags & asOBJ_ASHANDLE))) &&
  2419. dt.GetObjectType() && (dt.GetBehaviour()->copyconstruct || dt.GetBehaviour()->copyfactory) )
  2420. {
  2421. PrepareForAssignment(&lvalue.dataType, ctx, node);
  2422. // Use the copy constructor/factory when available
  2423. CallCopyConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, ctx, node);
  2424. }
  2425. else
  2426. {
  2427. // Allocate and construct the temporary object
  2428. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, node);
  2429. // Assign the object to the temporary variable
  2430. PrepareForAssignment(&lvalue.dataType, ctx, node);
  2431. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2432. PerformAssignment(&lvalue, &ctx->type, &ctx->bc, node);
  2433. // Pop the original reference
  2434. ctx->bc.Pop(AS_PTR_SIZE);
  2435. }
  2436. // If the expression was holding off on releasing a
  2437. // previously used object, we need to release it now
  2438. if( ctx->type.isTemporary )
  2439. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  2440. // Push the reference to the temporary variable on the stack
  2441. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2442. lvalue.dataType.MakeReference(IsVariableOnHeap(offset));
  2443. ctx->type = lvalue;
  2444. }
  2445. void asCCompiler::CompileReturnStatement(asCScriptNode *rnode, asCByteCode *bc)
  2446. {
  2447. // Get return type and location
  2448. sVariable *v = variables->GetVariable("return");
  2449. // Basic validations
  2450. if( v->type.GetSizeOnStackDWords() > 0 && !rnode->firstChild )
  2451. {
  2452. Error(TXT_MUST_RETURN_VALUE, rnode);
  2453. return;
  2454. }
  2455. else if( v->type.GetSizeOnStackDWords() == 0 && rnode->firstChild )
  2456. {
  2457. Error(TXT_CANT_RETURN_VALUE, rnode);
  2458. return;
  2459. }
  2460. // Compile the expression
  2461. if( rnode->firstChild )
  2462. {
  2463. // Compile the expression
  2464. asSExprContext expr(engine);
  2465. int r = CompileAssignment(rnode->firstChild, &expr);
  2466. if( r < 0 ) return;
  2467. if( v->type.IsReference() )
  2468. {
  2469. // The expression that gives the reference must not use any of the
  2470. // variables that must be destroyed upon exit, because then it means
  2471. // reference will stay alive while the clean-up is done, which could
  2472. // potentially mean that the reference is invalidated by the clean-up.
  2473. //
  2474. // When the function is returning a reference, the clean-up of the
  2475. // variables must be done before the evaluation of the expression.
  2476. //
  2477. // A reference to a global variable, or a class member for class methods
  2478. // should be allowed to be returned.
  2479. if( !(expr.type.dataType.IsReference() ||
  2480. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle())) )
  2481. {
  2482. // Clean up the potential deferred parameters
  2483. ProcessDeferredParams(&expr);
  2484. Error(TXT_NOT_VALID_REFERENCE, rnode);
  2485. return;
  2486. }
  2487. // No references to local variables, temporary variables, or parameters
  2488. // are allowed to be returned, since they go out of scope when the function
  2489. // returns. Even reference parameters are disallowed, since it is not possible
  2490. // to know the scope of them. The exception is the 'this' pointer, which
  2491. // is treated by the compiler as a local variable, but isn't really so.
  2492. if( (expr.type.isVariable && !(expr.type.stackOffset == 0 && outFunc->objectType)) || expr.type.isTemporary )
  2493. {
  2494. // Clean up the potential deferred parameters
  2495. ProcessDeferredParams(&expr);
  2496. Error(TXT_CANNOT_RETURN_REF_TO_LOCAL, rnode);
  2497. return;
  2498. }
  2499. // The type must match exactly as we cannot convert
  2500. // the reference without loosing the original value
  2501. if( !(v->type == expr.type.dataType ||
  2502. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle() && v->type.IsEqualExceptRef(expr.type.dataType))) )
  2503. {
  2504. // Clean up the potential deferred parameters
  2505. ProcessDeferredParams(&expr);
  2506. asCString str;
  2507. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2508. Error(str.AddressOf(), rnode);
  2509. return;
  2510. }
  2511. // The expression must not have any deferred expressions, because the evaluation
  2512. // of these cannot be done without keeping the reference which is not safe
  2513. if( expr.deferredParams.GetLength() )
  2514. {
  2515. // Clean up the potential deferred parameters
  2516. ProcessDeferredParams(&expr);
  2517. Error(TXT_REF_CANT_BE_RETURNED_DEFERRED_PARAM, rnode);
  2518. return;
  2519. }
  2520. // Make sure the expression isn't using any local variables that
  2521. // will need to be cleaned up before the function completes
  2522. asCArray<int> usedVars;
  2523. expr.bc.GetVarsUsed(usedVars);
  2524. for( asUINT n = 0; n < usedVars.GetLength(); n++ )
  2525. {
  2526. int var = GetVariableSlot(usedVars[n]);
  2527. if( var != -1 )
  2528. {
  2529. asCDataType dt = variableAllocations[var];
  2530. if( dt.IsObject() )
  2531. {
  2532. ProcessDeferredParams(&expr);
  2533. Error(TXT_REF_CANT_BE_RETURNED_LOCAL_VARS, rnode);
  2534. return;
  2535. }
  2536. }
  2537. }
  2538. // All objects in the function must be cleaned up before the expression
  2539. // is evaluated, otherwise there is a possibility that the cleanup will
  2540. // invalidate the reference.
  2541. // Destroy the local variables before loading
  2542. // the reference into the register. This will
  2543. // be done before the expression is evaluated.
  2544. DestroyVariables(bc);
  2545. // For primitives the reference is already in the register,
  2546. // but for non-primitives the reference is on the stack so we
  2547. // need to load it into the register
  2548. if( !expr.type.dataType.IsPrimitive() )
  2549. {
  2550. if( (!expr.type.dataType.IsObjectHandle() || (expr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) &&
  2551. expr.type.dataType.IsReference() )
  2552. expr.bc.Instr(asBC_RDSPTR);
  2553. expr.bc.Instr(asBC_PopRPtr);
  2554. }
  2555. // There are no temporaries to release so we're done
  2556. }
  2557. else // if( !v->type.IsReference() )
  2558. {
  2559. ProcessPropertyGetAccessor(&expr, rnode);
  2560. // Prepare the value for assignment
  2561. IsVariableInitialized(&expr.type, rnode->firstChild);
  2562. if( v->type.IsPrimitive() )
  2563. {
  2564. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2565. // Implicitly convert the value to the return type
  2566. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  2567. // Verify that the conversion was successful
  2568. if( expr.type.dataType != v->type )
  2569. {
  2570. asCString str;
  2571. str.Format(TXT_NO_CONVERSION_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2572. Error(str.AddressOf(), rnode);
  2573. r = -1;
  2574. }
  2575. else
  2576. {
  2577. ConvertToVariable(&expr);
  2578. // Clean up the local variables and process deferred parameters
  2579. DestroyVariables(&expr.bc);
  2580. ProcessDeferredParams(&expr);
  2581. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2582. // Load the variable in the register
  2583. if( v->type.GetSizeOnStackDWords() == 1 )
  2584. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2585. else
  2586. expr.bc.InstrSHORT(asBC_CpyVtoR8, expr.type.stackOffset);
  2587. }
  2588. }
  2589. else if( v->type.IsObject() )
  2590. {
  2591. // Value types are still returned on the heap, so we must
  2592. // copy the value to an object allocated on the heap here
  2593. PrepareArgument(&v->type, &expr, rnode->firstChild, false, 0, 0, true);
  2594. // Pop the reference to the temporary variable again
  2595. expr.bc.Pop(AS_PTR_SIZE);
  2596. // Clean up the local variables and process deferred parameters
  2597. DestroyVariables(&expr.bc);
  2598. ProcessDeferredParams(&expr);
  2599. // Load the object pointer into the object register
  2600. // LOADOBJ also clears the address in the variable
  2601. expr.bc.InstrSHORT(asBC_LOADOBJ, expr.type.stackOffset);
  2602. // LOADOBJ cleared the address in the variable so the object will not be freed
  2603. // here, but the temporary variable must still be freed so the slot can be reused
  2604. // By releasing without the bytecode we do just that.
  2605. ReleaseTemporaryVariable(expr.type, 0);
  2606. }
  2607. }
  2608. bc->AddCode(&expr.bc);
  2609. }
  2610. else
  2611. {
  2612. // For functions that don't return anything
  2613. // we just detroy the local variables
  2614. DestroyVariables(bc);
  2615. }
  2616. // Jump to the end of the function
  2617. bc->InstrINT(asBC_JMP, 0);
  2618. }
  2619. void asCCompiler::DestroyVariables(asCByteCode *bc)
  2620. {
  2621. // Call destructor on all variables except for the function parameters
  2622. // Put the clean-up in a block to allow exception handler to understand this
  2623. bc->Block(true);
  2624. asCVariableScope *vs = variables;
  2625. while( vs )
  2626. {
  2627. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2628. if( vs->variables[n]->stackOffset > 0 )
  2629. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2630. vs = vs->parent;
  2631. }
  2632. bc->Block(false);
  2633. }
  2634. void asCCompiler::AddVariableScope(bool isBreakScope, bool isContinueScope)
  2635. {
  2636. variables = asNEW(asCVariableScope)(variables);
  2637. variables->isBreakScope = isBreakScope;
  2638. variables->isContinueScope = isContinueScope;
  2639. }
  2640. void asCCompiler::RemoveVariableScope()
  2641. {
  2642. if( variables )
  2643. {
  2644. asCVariableScope *var = variables;
  2645. variables = variables->parent;
  2646. asDELETE(var,asCVariableScope);
  2647. }
  2648. }
  2649. void asCCompiler::Error(const char *msg, asCScriptNode *node)
  2650. {
  2651. asCString str;
  2652. int r = 0, c = 0;
  2653. asASSERT( node );
  2654. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2655. builder->WriteError(script->name.AddressOf(), msg, r, c);
  2656. hasCompileErrors = true;
  2657. }
  2658. void asCCompiler::Warning(const char *msg, asCScriptNode *node)
  2659. {
  2660. asCString str;
  2661. int r = 0, c = 0;
  2662. asASSERT( node );
  2663. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2664. builder->WriteWarning(script->name.AddressOf(), msg, r, c);
  2665. }
  2666. void asCCompiler::Information(const char *msg, asCScriptNode *node)
  2667. {
  2668. asCString str;
  2669. int r = 0, c = 0;
  2670. asASSERT( node );
  2671. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2672. builder->WriteInfo(script->name.AddressOf(), msg, r, c, false);
  2673. }
  2674. void asCCompiler::PrintMatchingFuncs(asCArray<int> &funcs, asCScriptNode *node)
  2675. {
  2676. int r = 0, c = 0;
  2677. asASSERT( node );
  2678. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2679. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  2680. {
  2681. asIScriptFunction *func = builder->GetFunctionDescription(funcs[n]);
  2682. builder->WriteInfo(script->name.AddressOf(), func->GetDeclaration(true), r, c, false);
  2683. }
  2684. }
  2685. int asCCompiler::AllocateVariable(const asCDataType &type, bool isTemporary, bool forceOnHeap)
  2686. {
  2687. return AllocateVariableNotIn(type, isTemporary, 0, forceOnHeap);
  2688. }
  2689. int asCCompiler::AllocateVariableNotIn(const asCDataType &type, bool isTemporary, asCArray<int> *vars, bool forceOnHeap)
  2690. {
  2691. asCDataType t(type);
  2692. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 1 )
  2693. t.SetTokenType(ttInt);
  2694. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 2 )
  2695. t.SetTokenType(ttDouble);
  2696. // Only null handles have the token type unrecognized token
  2697. asASSERT( t.IsObjectHandle() || t.GetTokenType() != ttUnrecognizedToken );
  2698. bool isOnHeap = true;
  2699. // TODO: Remove this once the bugs with value types on stack is fixed
  2700. // forceOnHeap = true;
  2701. if( t.IsPrimitive() ||
  2702. (t.GetObjectType() && (t.GetObjectType()->GetFlags() & asOBJ_VALUE) && !forceOnHeap) )
  2703. {
  2704. // Primitives and value types (unless overridden) are allocated on the stack
  2705. isOnHeap = false;
  2706. }
  2707. // Find a free location with the same type
  2708. for( asUINT n = 0; n < freeVariables.GetLength(); n++ )
  2709. {
  2710. int slot = freeVariables[n];
  2711. if( variableAllocations[slot].IsEqualExceptConst(t) &&
  2712. variableIsTemporary[slot] == isTemporary &&
  2713. variableIsOnHeap[slot] == isOnHeap )
  2714. {
  2715. // We can't return by slot, must count variable sizes
  2716. int offset = GetVariableOffset(slot);
  2717. // Verify that it is not in the list of used variables
  2718. bool isUsed = false;
  2719. if( vars )
  2720. {
  2721. for( asUINT m = 0; m < vars->GetLength(); m++ )
  2722. {
  2723. if( offset == (*vars)[m] )
  2724. {
  2725. isUsed = true;
  2726. break;
  2727. }
  2728. }
  2729. }
  2730. if( !isUsed )
  2731. {
  2732. if( n != freeVariables.GetLength() - 1 )
  2733. freeVariables[n] = freeVariables.PopLast();
  2734. else
  2735. freeVariables.PopLast();
  2736. if( isTemporary )
  2737. tempVariables.PushLast(offset);
  2738. return offset;
  2739. }
  2740. }
  2741. }
  2742. variableAllocations.PushLast(t);
  2743. variableIsTemporary.PushLast(isTemporary);
  2744. variableIsOnHeap.PushLast(isOnHeap);
  2745. int offset = GetVariableOffset((int)variableAllocations.GetLength()-1);
  2746. if( isTemporary )
  2747. tempVariables.PushLast(offset);
  2748. return offset;
  2749. }
  2750. int asCCompiler::GetVariableOffset(int varIndex)
  2751. {
  2752. // Return offset to the last dword on the stack
  2753. int varOffset = 1;
  2754. for( int n = 0; n < varIndex; n++ )
  2755. {
  2756. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  2757. varOffset += variableAllocations[n].GetSizeInMemoryDWords();
  2758. else
  2759. varOffset += variableAllocations[n].GetSizeOnStackDWords();
  2760. }
  2761. if( varIndex < (int)variableAllocations.GetLength() )
  2762. {
  2763. int size;
  2764. if( !variableIsOnHeap[varIndex] && variableAllocations[varIndex].IsObject() )
  2765. size = variableAllocations[varIndex].GetSizeInMemoryDWords();
  2766. else
  2767. size = variableAllocations[varIndex].GetSizeOnStackDWords();
  2768. if( size > 1 )
  2769. varOffset += size-1;
  2770. }
  2771. return varOffset;
  2772. }
  2773. int asCCompiler::GetVariableSlot(int offset)
  2774. {
  2775. int varOffset = 1;
  2776. for( asUINT n = 0; n < variableAllocations.GetLength(); n++ )
  2777. {
  2778. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  2779. varOffset += -1 + variableAllocations[n].GetSizeInMemoryDWords();
  2780. else
  2781. varOffset += -1 + variableAllocations[n].GetSizeOnStackDWords();
  2782. if( varOffset == offset )
  2783. return n;
  2784. varOffset++;
  2785. }
  2786. return -1;
  2787. }
  2788. bool asCCompiler::IsVariableOnHeap(int offset)
  2789. {
  2790. int varSlot = GetVariableSlot(offset);
  2791. if( varSlot < 0 )
  2792. {
  2793. // This happens for function arguments that are considered as on the heap
  2794. return true;
  2795. }
  2796. return variableIsOnHeap[varSlot];
  2797. }
  2798. void asCCompiler::DeallocateVariable(int offset)
  2799. {
  2800. // Remove temporary variable
  2801. int n;
  2802. for( n = 0; n < (int)tempVariables.GetLength(); n++ )
  2803. {
  2804. if( offset == tempVariables[n] )
  2805. {
  2806. if( n == (int)tempVariables.GetLength()-1 )
  2807. tempVariables.PopLast();
  2808. else
  2809. tempVariables[n] = tempVariables.PopLast();
  2810. break;
  2811. }
  2812. }
  2813. n = GetVariableSlot(offset);
  2814. if( n != -1 )
  2815. {
  2816. freeVariables.PushLast(n);
  2817. return;
  2818. }
  2819. // We might get here if the variable was implicitly declared
  2820. // because it was use before a formal declaration, in this case
  2821. // the offset is 0x7FFF
  2822. asASSERT(offset == 0x7FFF);
  2823. }
  2824. void asCCompiler::ReleaseTemporaryVariable(asCTypeInfo &t, asCByteCode *bc)
  2825. {
  2826. if( t.isTemporary )
  2827. {
  2828. ReleaseTemporaryVariable(t.stackOffset, bc);
  2829. t.isTemporary = false;
  2830. }
  2831. }
  2832. void asCCompiler::ReleaseTemporaryVariable(int offset, asCByteCode *bc)
  2833. {
  2834. if( bc )
  2835. {
  2836. // We need to call the destructor on the true variable type
  2837. int n = GetVariableSlot(offset);
  2838. asCDataType dt = variableAllocations[n];
  2839. bool isOnHeap = variableIsOnHeap[n];
  2840. // Call destructor
  2841. CallDestructor(dt, offset, isOnHeap, bc);
  2842. }
  2843. DeallocateVariable(offset);
  2844. }
  2845. void asCCompiler::Dereference(asSExprContext *ctx, bool generateCode)
  2846. {
  2847. if( ctx->type.dataType.IsReference() )
  2848. {
  2849. if( ctx->type.dataType.IsObject() )
  2850. {
  2851. ctx->type.dataType.MakeReference(false);
  2852. if( generateCode )
  2853. {
  2854. ctx->bc.Instr(asBC_CHKREF);
  2855. ctx->bc.Instr(asBC_RDSPTR);
  2856. }
  2857. }
  2858. else
  2859. {
  2860. // This should never happen as primitives are treated differently
  2861. asASSERT(false);
  2862. }
  2863. }
  2864. }
  2865. bool asCCompiler::IsVariableInitialized(asCTypeInfo *type, asCScriptNode *node)
  2866. {
  2867. // Temporary variables are assumed to be initialized
  2868. if( type->isTemporary ) return true;
  2869. // Verify that it is a variable
  2870. if( !type->isVariable ) return true;
  2871. // Find the variable
  2872. sVariable *v = variables->GetVariableByOffset(type->stackOffset);
  2873. // The variable isn't found if it is a constant, in which case it is guaranteed to be initialized
  2874. if( v == 0 ) return true;
  2875. if( v->isInitialized ) return true;
  2876. // Complex types don't need this test
  2877. if( v->type.IsObject() ) return true;
  2878. // Mark as initialized so that the user will not be bothered again
  2879. v->isInitialized = true;
  2880. // Write warning
  2881. asCString str;
  2882. str.Format(TXT_s_NOT_INITIALIZED, (const char *)v->name.AddressOf());
  2883. Warning(str.AddressOf(), node);
  2884. return false;
  2885. }
  2886. void asCCompiler::PrepareOperand(asSExprContext *ctx, asCScriptNode *node)
  2887. {
  2888. // Check if the variable is initialized (if it indeed is a variable)
  2889. IsVariableInitialized(&ctx->type, node);
  2890. asCDataType to = ctx->type.dataType;
  2891. to.MakeReference(false);
  2892. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  2893. ProcessDeferredParams(ctx);
  2894. }
  2895. void asCCompiler::PrepareForAssignment(asCDataType *lvalue, asSExprContext *rctx, asCScriptNode *node, asSExprContext *lvalueExpr)
  2896. {
  2897. ProcessPropertyGetAccessor(rctx, node);
  2898. // Make sure the rvalue is initialized if it is a variable
  2899. IsVariableInitialized(&rctx->type, node);
  2900. if( lvalue->IsPrimitive() )
  2901. {
  2902. if( rctx->type.dataType.IsPrimitive() )
  2903. {
  2904. if( rctx->type.dataType.IsReference() )
  2905. {
  2906. // Cannot do implicit conversion of references so we first convert the reference to a variable
  2907. ConvertToVariableNotIn(rctx, lvalueExpr);
  2908. }
  2909. }
  2910. // Implicitly convert the value to the right type
  2911. asCArray<int> usedVars;
  2912. if( lvalueExpr ) lvalueExpr->bc.GetVarsUsed(usedVars);
  2913. ImplicitConversion(rctx, *lvalue, node, asIC_IMPLICIT_CONV, true, &usedVars);
  2914. // Check data type
  2915. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  2916. {
  2917. asCString str;
  2918. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  2919. Error(str.AddressOf(), node);
  2920. rctx->type.SetDummy();
  2921. }
  2922. // Make sure the rvalue is a variable
  2923. if( !rctx->type.isVariable )
  2924. ConvertToVariableNotIn(rctx, lvalueExpr);
  2925. }
  2926. else
  2927. {
  2928. asCDataType to = *lvalue;
  2929. to.MakeReference(false);
  2930. // TODO: ImplicitConversion should know to do this by itself
  2931. // First convert to a handle which will to a reference cast
  2932. if( !lvalue->IsObjectHandle() &&
  2933. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  2934. to.MakeHandle(true);
  2935. // Don't allow the implicit conversion to create an object
  2936. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, 0, false);
  2937. if( !lvalue->IsObjectHandle() &&
  2938. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  2939. {
  2940. // Then convert to a reference, which will validate the handle
  2941. to.MakeHandle(false);
  2942. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, 0, false);
  2943. }
  2944. // Check data type
  2945. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  2946. {
  2947. asCString str;
  2948. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  2949. Error(str.AddressOf(), node);
  2950. }
  2951. else
  2952. {
  2953. // If the assignment will be made with the copy behaviour then the rvalue must not be a reference
  2954. if( lvalue->IsObject() )
  2955. asASSERT(!rctx->type.dataType.IsReference());
  2956. }
  2957. }
  2958. }
  2959. bool asCCompiler::IsLValue(asCTypeInfo &type)
  2960. {
  2961. if( !type.isLValue ) return false;
  2962. if( type.dataType.IsReadOnly() ) return false;
  2963. if( !type.dataType.IsObject() && !type.isVariable && !type.dataType.IsReference() ) return false;
  2964. return true;
  2965. }
  2966. void asCCompiler::PerformAssignment(asCTypeInfo *lvalue, asCTypeInfo *rvalue, asCByteCode *bc, asCScriptNode *node)
  2967. {
  2968. if( lvalue->dataType.IsReadOnly() )
  2969. Error(TXT_REF_IS_READ_ONLY, node);
  2970. if( lvalue->dataType.IsPrimitive() )
  2971. {
  2972. if( lvalue->isVariable )
  2973. {
  2974. // Copy the value between the variables directly
  2975. if( lvalue->dataType.GetSizeInMemoryDWords() == 1 )
  2976. bc->InstrW_W(asBC_CpyVtoV4, lvalue->stackOffset, rvalue->stackOffset);
  2977. else
  2978. bc->InstrW_W(asBC_CpyVtoV8, lvalue->stackOffset, rvalue->stackOffset);
  2979. // Mark variable as initialized
  2980. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  2981. if( v ) v->isInitialized = true;
  2982. }
  2983. else if( lvalue->dataType.IsReference() )
  2984. {
  2985. // Copy the value of the variable to the reference in the register
  2986. int s = lvalue->dataType.GetSizeInMemoryBytes();
  2987. if( s == 1 )
  2988. bc->InstrSHORT(asBC_WRTV1, rvalue->stackOffset);
  2989. else if( s == 2 )
  2990. bc->InstrSHORT(asBC_WRTV2, rvalue->stackOffset);
  2991. else if( s == 4 )
  2992. bc->InstrSHORT(asBC_WRTV4, rvalue->stackOffset);
  2993. else if( s == 8 )
  2994. bc->InstrSHORT(asBC_WRTV8, rvalue->stackOffset);
  2995. }
  2996. else
  2997. {
  2998. Error(TXT_NOT_VALID_LVALUE, node);
  2999. return;
  3000. }
  3001. }
  3002. else if( !lvalue->isExplicitHandle )
  3003. {
  3004. asSExprContext ctx(engine);
  3005. ctx.type = *lvalue;
  3006. Dereference(&ctx, true);
  3007. *lvalue = ctx.type;
  3008. bc->AddCode(&ctx.bc);
  3009. // TODO: Can't this leave deferred output params unhandled?
  3010. // TODO: Should find the opAssign method that implements the default copy behaviour.
  3011. // The beh->copy member will be removed.
  3012. asSTypeBehaviour *beh = lvalue->dataType.GetBehaviour();
  3013. if( beh->copy )
  3014. {
  3015. // Call the copy operator
  3016. bc->Call(asBC_CALLSYS, (asDWORD)beh->copy, 2*AS_PTR_SIZE);
  3017. bc->Instr(asBC_PshRPtr);
  3018. }
  3019. else
  3020. {
  3021. // Default copy operator
  3022. if( lvalue->dataType.GetSizeInMemoryDWords() == 0 ||
  3023. !(lvalue->dataType.GetObjectType()->flags & asOBJ_POD) )
  3024. {
  3025. Error(TXT_NO_DEFAULT_COPY_OP, node);
  3026. }
  3027. // Copy larger data types from a reference
  3028. bc->InstrSHORT_DW(asBC_COPY, (short)lvalue->dataType.GetSizeInMemoryDWords(), engine->GetTypeIdFromDataType(lvalue->dataType));
  3029. }
  3030. }
  3031. else
  3032. {
  3033. // TODO: The object handle can be stored in a variable as well
  3034. if( !lvalue->dataType.IsReference() )
  3035. {
  3036. Error(TXT_NOT_VALID_REFERENCE, node);
  3037. return;
  3038. }
  3039. // TODO: optimize: Convert to register based
  3040. bc->InstrPTR(asBC_REFCPY, lvalue->dataType.GetObjectType());
  3041. // Mark variable as initialized
  3042. if( variables )
  3043. {
  3044. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3045. if( v ) v->isInitialized = true;
  3046. }
  3047. }
  3048. }
  3049. bool asCCompiler::CompileRefCast(asSExprContext *ctx, const asCDataType &to, bool isExplicit, asCScriptNode *node, bool generateCode)
  3050. {
  3051. bool conversionDone = false;
  3052. asCArray<int> ops;
  3053. asUINT n;
  3054. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT )
  3055. {
  3056. // We need it to be a reference
  3057. if( !ctx->type.dataType.IsReference() )
  3058. {
  3059. asCDataType to = ctx->type.dataType;
  3060. to.MakeReference(true);
  3061. ImplicitConversion(ctx, to, 0, isExplicit ? asIC_EXPLICIT_REF_CAST : asIC_IMPLICIT_CONV, generateCode);
  3062. }
  3063. if( isExplicit )
  3064. {
  3065. // Allow dynamic cast between object handles (only for script objects).
  3066. // At run time this may result in a null handle,
  3067. // which when used will throw an exception
  3068. conversionDone = true;
  3069. if( generateCode )
  3070. {
  3071. ctx->bc.InstrDWORD(asBC_Cast, engine->GetTypeIdFromDataType(to));
  3072. // Allocate a temporary variable for the returned object
  3073. int returnOffset = AllocateVariable(to, true);
  3074. // Move the pointer from the object register to the temporary variable
  3075. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  3076. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  3077. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3078. ctx->type.SetVariable(to, returnOffset, true);
  3079. ctx->type.dataType.MakeReference(true);
  3080. }
  3081. else
  3082. {
  3083. ctx->type.dataType = to;
  3084. ctx->type.dataType.MakeReference(true);
  3085. }
  3086. }
  3087. else
  3088. {
  3089. if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3090. {
  3091. conversionDone = true;
  3092. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3093. }
  3094. }
  3095. }
  3096. else
  3097. {
  3098. // Find a suitable registered behaviour
  3099. asSTypeBehaviour *beh = &ctx->type.dataType.GetObjectType()->beh;
  3100. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3101. {
  3102. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3103. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3104. {
  3105. int funcId = beh->operators[n+1];
  3106. // Is the operator for the output type?
  3107. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3108. if( func->returnType.GetObjectType() != to.GetObjectType() )
  3109. continue;
  3110. ops.PushLast(funcId);
  3111. }
  3112. }
  3113. // It shouldn't be possible to have more than one
  3114. asASSERT( ops.GetLength() <= 1 );
  3115. // Should only have one behaviour for each output type
  3116. if( ops.GetLength() == 1 )
  3117. {
  3118. if( generateCode )
  3119. {
  3120. // TODO: optimize: Instead of producing bytecode for checking if the handle is
  3121. // null, we can create a special CALLSYS instruction that checks
  3122. // if the object pointer is null and if so sets the object register
  3123. // to null directly without executing the function.
  3124. //
  3125. // Alternatively I could force the ref cast behaviours be global
  3126. // functions with 1 parameter, even though they should still be
  3127. // registered with RegisterObjectBehaviour()
  3128. // Add code to avoid calling the cast behaviour if the handle is already null,
  3129. // because that will raise a null pointer exception due to the cast behaviour
  3130. // being a class method, and the this pointer cannot be null.
  3131. if( ctx->type.isVariable )
  3132. ctx->bc.Pop(AS_PTR_SIZE);
  3133. else
  3134. {
  3135. Dereference(ctx, true);
  3136. ConvertToVariable(ctx);
  3137. }
  3138. #ifdef AS_64BIT_PTR
  3139. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttUInt64, false), true);
  3140. ctx->bc.InstrW_QW(asBC_SetV8, (asWORD)offset, 0);
  3141. ctx->bc.InstrW_W(asBC_CMPi64, ctx->type.stackOffset, offset);
  3142. DeallocateVariable(offset);
  3143. #else
  3144. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttUInt, false), true);
  3145. ctx->bc.InstrW_DW(asBC_SetV4, (asWORD)offset, 0);
  3146. ctx->bc.InstrW_W(asBC_CMPi, ctx->type.stackOffset, offset);
  3147. DeallocateVariable(offset);
  3148. #endif
  3149. int afterLabel = nextLabel++;
  3150. ctx->bc.InstrDWORD(asBC_JZ, afterLabel);
  3151. // Call the cast operator
  3152. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3153. ctx->bc.Instr(asBC_RDSPTR);
  3154. ctx->type.dataType.MakeReference(false);
  3155. asCTypeInfo objType = ctx->type;
  3156. asCArray<asSExprContext *> args;
  3157. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  3158. ctx->bc.Pop(AS_PTR_SIZE);
  3159. int endLabel = nextLabel++;
  3160. ctx->bc.InstrINT(asBC_JMP, endLabel);
  3161. ctx->bc.Label((short)afterLabel);
  3162. // Make a NULL pointer
  3163. #ifdef AS_64BIT_PTR
  3164. ctx->bc.InstrW_QW(asBC_SetV8, ctx->type.stackOffset, 0);
  3165. #else
  3166. ctx->bc.InstrW_DW(asBC_SetV4, ctx->type.stackOffset, 0);
  3167. #endif
  3168. ctx->bc.Label((short)endLabel);
  3169. // Since we're receiving a handle, we can release the original variable
  3170. ReleaseTemporaryVariable(objType, &ctx->bc);
  3171. // Push the reference to the handle on the stack
  3172. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3173. }
  3174. else
  3175. {
  3176. asCScriptFunction *func = engine->scriptFunctions[ops[0]];
  3177. ctx->type.Set(func->returnType);
  3178. }
  3179. }
  3180. else if( ops.GetLength() == 0 )
  3181. {
  3182. // Check for the generic ref cast behaviour
  3183. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3184. {
  3185. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3186. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3187. {
  3188. int funcId = beh->operators[n+1];
  3189. // Does the operator take the ?&out parameter?
  3190. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3191. if( func->parameterTypes.GetLength() != 1 ||
  3192. func->parameterTypes[0].GetTokenType() != ttQuestion ||
  3193. func->inOutFlags[0] != asTM_OUTREF )
  3194. continue;
  3195. ops.PushLast(funcId);
  3196. }
  3197. }
  3198. // It shouldn't be possible to have more than one
  3199. asASSERT( ops.GetLength() <= 1 );
  3200. if( ops.GetLength() == 1 )
  3201. {
  3202. if( generateCode )
  3203. {
  3204. asASSERT(to.IsObjectHandle());
  3205. // Allocate a temporary variable of the requested handle type
  3206. asCArray<int> vars;
  3207. ctx->bc.GetVarsUsed(vars);
  3208. int stackOffset = AllocateVariableNotIn(to, true, &vars);
  3209. // Pass the reference of that variable to the function as output parameter
  3210. asCDataType toRef(to);
  3211. toRef.MakeReference(true);
  3212. asCArray<asSExprContext *> args;
  3213. asSExprContext arg(engine);
  3214. arg.bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3215. // Don't mark the variable as temporary, so it won't be freed too early
  3216. arg.type.SetVariable(toRef, stackOffset, false);
  3217. arg.type.isLValue = true;
  3218. arg.type.isExplicitHandle = true;
  3219. args.PushLast(&arg);
  3220. // Call the behaviour method
  3221. MakeFunctionCall(ctx, ops[0], ctx->type.dataType.GetObjectType(), args, node);
  3222. // Use the reference to the variable as the result of the expression
  3223. // Now we can mark the variable as temporary
  3224. ctx->type.SetVariable(toRef, stackOffset, true);
  3225. ctx->bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3226. }
  3227. else
  3228. {
  3229. // All casts are legal
  3230. ctx->type.Set(to);
  3231. }
  3232. }
  3233. }
  3234. }
  3235. return conversionDone;
  3236. }
  3237. void asCCompiler::ImplicitConvPrimitiveToPrimitive(asSExprContext *ctx, const asCDataType &toOrig, asCScriptNode *node, EImplicitConv convType, bool generateCode, asCArray<int> *reservedVars)
  3238. {
  3239. asCDataType to = toOrig;
  3240. to.MakeReference(false);
  3241. asASSERT( !ctx->type.dataType.IsReference() );
  3242. // Start by implicitly converting constant values
  3243. if( ctx->type.isConstant )
  3244. ImplicitConversionConstant(ctx, to, node, convType);
  3245. // A primitive is const or not
  3246. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3247. if( to == ctx->type.dataType )
  3248. return;
  3249. // Allow implicit conversion between numbers
  3250. if( generateCode )
  3251. {
  3252. // Convert smaller types to 32bit first
  3253. int s = ctx->type.dataType.GetSizeInMemoryBytes();
  3254. if( s < 4 )
  3255. {
  3256. ConvertToTempVariableNotIn(ctx, reservedVars);
  3257. if( ctx->type.dataType.IsIntegerType() )
  3258. {
  3259. if( s == 1 )
  3260. ctx->bc.InstrSHORT(asBC_sbTOi, ctx->type.stackOffset);
  3261. else if( s == 2 )
  3262. ctx->bc.InstrSHORT(asBC_swTOi, ctx->type.stackOffset);
  3263. ctx->type.dataType.SetTokenType(ttInt);
  3264. }
  3265. else if( ctx->type.dataType.IsUnsignedType() )
  3266. {
  3267. if( s == 1 )
  3268. ctx->bc.InstrSHORT(asBC_ubTOi, ctx->type.stackOffset);
  3269. else if( s == 2 )
  3270. ctx->bc.InstrSHORT(asBC_uwTOi, ctx->type.stackOffset);
  3271. ctx->type.dataType.SetTokenType(ttUInt);
  3272. }
  3273. }
  3274. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1) ||
  3275. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  3276. {
  3277. if( ctx->type.dataType.IsIntegerType() ||
  3278. ctx->type.dataType.IsUnsignedType() ||
  3279. ctx->type.dataType.IsEnumType() )
  3280. {
  3281. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3282. {
  3283. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3284. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3285. }
  3286. else
  3287. {
  3288. ConvertToTempVariableNotIn(ctx, reservedVars);
  3289. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3290. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3291. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3292. ctx->type.SetVariable(to, offset, true);
  3293. }
  3294. }
  3295. else if( ctx->type.dataType.IsFloatType() )
  3296. {
  3297. ConvertToTempVariableNotIn(ctx, reservedVars);
  3298. ctx->bc.InstrSHORT(asBC_fTOi, ctx->type.stackOffset);
  3299. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3300. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3301. }
  3302. else if( ctx->type.dataType.IsDoubleType() )
  3303. {
  3304. ConvertToTempVariableNotIn(ctx, reservedVars);
  3305. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3306. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3307. ctx->bc.InstrW_W(asBC_dTOi, offset, ctx->type.stackOffset);
  3308. ctx->type.SetVariable(to, offset, true);
  3309. }
  3310. // Convert to smaller integer if necessary
  3311. int s = to.GetSizeInMemoryBytes();
  3312. if( s < 4 )
  3313. {
  3314. ConvertToTempVariableNotIn(ctx, reservedVars);
  3315. if( s == 1 )
  3316. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3317. else if( s == 2 )
  3318. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3319. }
  3320. }
  3321. if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  3322. {
  3323. if( ctx->type.dataType.IsIntegerType() ||
  3324. ctx->type.dataType.IsUnsignedType() ||
  3325. ctx->type.dataType.IsEnumType() )
  3326. {
  3327. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3328. {
  3329. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3330. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3331. }
  3332. else
  3333. {
  3334. ConvertToTempVariableNotIn(ctx, reservedVars);
  3335. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3336. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3337. if( ctx->type.dataType.IsUnsignedType() )
  3338. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3339. else
  3340. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3341. ctx->type.SetVariable(to, offset, true);
  3342. }
  3343. }
  3344. else if( ctx->type.dataType.IsFloatType() )
  3345. {
  3346. ConvertToTempVariableNotIn(ctx, reservedVars);
  3347. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3348. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3349. ctx->bc.InstrW_W(asBC_fTOi64, offset, ctx->type.stackOffset);
  3350. ctx->type.SetVariable(to, offset, true);
  3351. }
  3352. else if( ctx->type.dataType.IsDoubleType() )
  3353. {
  3354. ConvertToTempVariableNotIn(ctx, reservedVars);
  3355. ctx->bc.InstrSHORT(asBC_dTOi64, ctx->type.stackOffset);
  3356. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3357. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3358. }
  3359. }
  3360. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  3361. {
  3362. if( ctx->type.dataType.IsIntegerType() ||
  3363. ctx->type.dataType.IsUnsignedType() ||
  3364. ctx->type.dataType.IsEnumType() )
  3365. {
  3366. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3367. {
  3368. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3369. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3370. }
  3371. else
  3372. {
  3373. ConvertToTempVariableNotIn(ctx, reservedVars);
  3374. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3375. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3376. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3377. ctx->type.SetVariable(to, offset, true);
  3378. }
  3379. }
  3380. else if( ctx->type.dataType.IsFloatType() )
  3381. {
  3382. ConvertToTempVariableNotIn(ctx, reservedVars);
  3383. ctx->bc.InstrSHORT(asBC_fTOu, ctx->type.stackOffset);
  3384. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3385. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3386. }
  3387. else if( ctx->type.dataType.IsDoubleType() )
  3388. {
  3389. ConvertToTempVariableNotIn(ctx, reservedVars);
  3390. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3391. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3392. ctx->bc.InstrW_W(asBC_dTOu, offset, ctx->type.stackOffset);
  3393. ctx->type.SetVariable(to, offset, true);
  3394. }
  3395. // Convert to smaller integer if necessary
  3396. int s = to.GetSizeInMemoryBytes();
  3397. if( s < 4 )
  3398. {
  3399. ConvertToTempVariableNotIn(ctx, reservedVars);
  3400. if( s == 1 )
  3401. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3402. else if( s == 2 )
  3403. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3404. }
  3405. }
  3406. if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  3407. {
  3408. if( ctx->type.dataType.IsIntegerType() ||
  3409. ctx->type.dataType.IsUnsignedType() ||
  3410. ctx->type.dataType.IsEnumType() )
  3411. {
  3412. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3413. {
  3414. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3415. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3416. }
  3417. else
  3418. {
  3419. ConvertToTempVariableNotIn(ctx, reservedVars);
  3420. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3421. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3422. if( ctx->type.dataType.IsUnsignedType() )
  3423. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3424. else
  3425. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3426. ctx->type.SetVariable(to, offset, true);
  3427. }
  3428. }
  3429. else if( ctx->type.dataType.IsFloatType() )
  3430. {
  3431. ConvertToTempVariableNotIn(ctx, reservedVars);
  3432. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3433. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3434. ctx->bc.InstrW_W(asBC_fTOu64, offset, ctx->type.stackOffset);
  3435. ctx->type.SetVariable(to, offset, true);
  3436. }
  3437. else if( ctx->type.dataType.IsDoubleType() )
  3438. {
  3439. ConvertToTempVariableNotIn(ctx, reservedVars);
  3440. ctx->bc.InstrSHORT(asBC_dTOu64, ctx->type.stackOffset);
  3441. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3442. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3443. }
  3444. }
  3445. else if( to.IsFloatType() )
  3446. {
  3447. if( (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType()) && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3448. {
  3449. ConvertToTempVariableNotIn(ctx, reservedVars);
  3450. ctx->bc.InstrSHORT(asBC_iTOf, ctx->type.stackOffset);
  3451. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3452. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3453. }
  3454. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3455. {
  3456. ConvertToTempVariableNotIn(ctx, reservedVars);
  3457. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3458. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3459. ctx->bc.InstrW_W(asBC_i64TOf, offset, ctx->type.stackOffset);
  3460. ctx->type.SetVariable(to, offset, true);
  3461. }
  3462. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3463. {
  3464. ConvertToTempVariableNotIn(ctx, reservedVars);
  3465. ctx->bc.InstrSHORT(asBC_uTOf, ctx->type.stackOffset);
  3466. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3467. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3468. }
  3469. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3470. {
  3471. ConvertToTempVariableNotIn(ctx, reservedVars);
  3472. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3473. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3474. ctx->bc.InstrW_W(asBC_u64TOf, offset, ctx->type.stackOffset);
  3475. ctx->type.SetVariable(to, offset, true);
  3476. }
  3477. else if( ctx->type.dataType.IsDoubleType() )
  3478. {
  3479. ConvertToTempVariableNotIn(ctx, reservedVars);
  3480. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3481. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3482. ctx->bc.InstrW_W(asBC_dTOf, offset, ctx->type.stackOffset);
  3483. ctx->type.SetVariable(to, offset, true);
  3484. }
  3485. }
  3486. else if( to.IsDoubleType() )
  3487. {
  3488. if( (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType()) && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3489. {
  3490. ConvertToTempVariableNotIn(ctx, reservedVars);
  3491. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3492. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3493. ctx->bc.InstrW_W(asBC_iTOd, offset, ctx->type.stackOffset);
  3494. ctx->type.SetVariable(to, offset, true);
  3495. }
  3496. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3497. {
  3498. ConvertToTempVariableNotIn(ctx, reservedVars);
  3499. ctx->bc.InstrSHORT(asBC_i64TOd, ctx->type.stackOffset);
  3500. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3501. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3502. }
  3503. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3504. {
  3505. ConvertToTempVariableNotIn(ctx, reservedVars);
  3506. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3507. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3508. ctx->bc.InstrW_W(asBC_uTOd, offset, ctx->type.stackOffset);
  3509. ctx->type.SetVariable(to, offset, true);
  3510. }
  3511. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3512. {
  3513. ConvertToTempVariableNotIn(ctx, reservedVars);
  3514. ctx->bc.InstrSHORT(asBC_u64TOd, ctx->type.stackOffset);
  3515. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3516. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3517. }
  3518. else if( ctx->type.dataType.IsFloatType() )
  3519. {
  3520. ConvertToTempVariableNotIn(ctx, reservedVars);
  3521. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3522. int offset = AllocateVariableNotIn(to, true, reservedVars);
  3523. ctx->bc.InstrW_W(asBC_fTOd, offset, ctx->type.stackOffset);
  3524. ctx->type.SetVariable(to, offset, true);
  3525. }
  3526. }
  3527. }
  3528. else
  3529. {
  3530. if( (to.IsIntegerType() || to.IsUnsignedType() ||
  3531. to.IsFloatType() || to.IsDoubleType() ||
  3532. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST)) &&
  3533. (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() ||
  3534. ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType() ||
  3535. ctx->type.dataType.IsEnumType()) )
  3536. {
  3537. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3538. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3539. }
  3540. }
  3541. // Primitive types on the stack, can be const or non-const
  3542. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3543. }
  3544. void asCCompiler::ImplicitConversion(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, asCArray<int> *reservedVars, bool allowObjectConstruct)
  3545. {
  3546. asASSERT( ctx->type.dataType.GetTokenType() != ttUnrecognizedToken ||
  3547. ctx->type.dataType.IsNullHandle() );
  3548. // No conversion from void to any other type
  3549. if( ctx->type.dataType.GetTokenType() == ttVoid )
  3550. return;
  3551. // Do we want a var type?
  3552. if( to.GetTokenType() == ttQuestion )
  3553. {
  3554. // Any type can be converted to a var type, but only when not generating code
  3555. asASSERT( !generateCode );
  3556. ctx->type.dataType = to;
  3557. return;
  3558. }
  3559. // Do we want a primitive?
  3560. else if( to.IsPrimitive() )
  3561. {
  3562. if( !ctx->type.dataType.IsPrimitive() )
  3563. ImplicitConvObjectToPrimitive(ctx, to, node, convType, generateCode, reservedVars);
  3564. else
  3565. ImplicitConvPrimitiveToPrimitive(ctx, to, node, convType, generateCode, reservedVars);
  3566. }
  3567. else // The target is a complex type
  3568. {
  3569. if( ctx->type.dataType.IsPrimitive() )
  3570. ImplicitConvPrimitiveToObject(ctx, to, node, convType, generateCode, reservedVars, allowObjectConstruct);
  3571. else if( ctx->type.IsNullConstant() || ctx->type.dataType.GetObjectType() )
  3572. ImplicitConvObjectToObject(ctx, to, node, convType, generateCode, reservedVars, allowObjectConstruct);
  3573. }
  3574. }
  3575. void asCCompiler::ImplicitConvObjectToPrimitive(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, asCArray<int> *reservedVars)
  3576. {
  3577. if( ctx->type.isExplicitHandle )
  3578. {
  3579. // An explicit handle cannot be converted to a primitive
  3580. if( convType != asIC_IMPLICIT_CONV && node )
  3581. {
  3582. asCString str;
  3583. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3584. Error(str.AddressOf(), node);
  3585. }
  3586. return;
  3587. }
  3588. // TODO: Must use the const cast behaviour if the object is read-only
  3589. // Find matching value cast behaviours
  3590. // Here we're only interested in those that convert the type to a primitive type
  3591. asCArray<int> funcs;
  3592. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  3593. if( beh )
  3594. {
  3595. if( convType == asIC_EXPLICIT_VAL_CAST )
  3596. {
  3597. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3598. {
  3599. // accept both implicit and explicit cast
  3600. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  3601. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  3602. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  3603. funcs.PushLast(beh->operators[n+1]);
  3604. }
  3605. }
  3606. else
  3607. {
  3608. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3609. {
  3610. // accept only implicit cast
  3611. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  3612. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  3613. funcs.PushLast(beh->operators[n+1]);
  3614. }
  3615. }
  3616. }
  3617. // This matrix describes the priorities of the types to search for, for each target type
  3618. // The first column is the target type, the priorities goes from left to right
  3619. eTokenType matchMtx[10][10] =
  3620. {
  3621. {ttDouble, ttFloat, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  3622. {ttFloat, ttDouble, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  3623. {ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  3624. {ttUInt64, ttInt64, ttUInt, ttInt, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  3625. {ttInt, ttUInt, ttInt64, ttUInt64, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  3626. {ttUInt, ttInt, ttUInt64, ttInt64, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  3627. {ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttInt8, ttUInt8, ttDouble, ttFloat},
  3628. {ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttUInt8, ttInt8, ttDouble, ttFloat},
  3629. {ttInt8, ttUInt8, ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttDouble, ttFloat},
  3630. {ttUInt8, ttInt8, ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttDouble, ttFloat},
  3631. };
  3632. // Which row to use?
  3633. eTokenType *row = 0;
  3634. for( unsigned int type = 0; type < 10; type++ )
  3635. {
  3636. if( to.GetTokenType() == matchMtx[type][0] )
  3637. {
  3638. row = &matchMtx[type][0];
  3639. break;
  3640. }
  3641. }
  3642. // Find the best matching cast operator
  3643. int funcId = 0;
  3644. if( row )
  3645. {
  3646. asCDataType target(to);
  3647. // Priority goes from left to right in the matrix
  3648. for( unsigned int attempt = 0; attempt < 10 && funcId == 0; attempt++ )
  3649. {
  3650. target.SetTokenType(row[attempt]);
  3651. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  3652. {
  3653. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[n]);
  3654. if( descr->returnType.IsEqualExceptConst(target) )
  3655. {
  3656. funcId = funcs[n];
  3657. break;
  3658. }
  3659. }
  3660. }
  3661. }
  3662. // Did we find a suitable function?
  3663. if( funcId != 0 )
  3664. {
  3665. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  3666. if( generateCode )
  3667. {
  3668. asCTypeInfo objType = ctx->type;
  3669. Dereference(ctx, true);
  3670. PerformFunctionCall(funcId, ctx);
  3671. ReleaseTemporaryVariable(objType, &ctx->bc);
  3672. }
  3673. else
  3674. ctx->type.Set(descr->returnType);
  3675. // Allow one more implicit conversion to another primitive type
  3676. ImplicitConversion(ctx, to, node, convType, generateCode, reservedVars, false);
  3677. }
  3678. else
  3679. {
  3680. if( convType != asIC_IMPLICIT_CONV && node )
  3681. {
  3682. asCString str;
  3683. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3684. Error(str.AddressOf(), node);
  3685. }
  3686. }
  3687. }
  3688. void asCCompiler::ImplicitConvObjectToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, asCArray<int> *reservedVars, bool allowObjectConstruct)
  3689. {
  3690. // Convert null to any object type handle, but not to a non-handle type
  3691. if( ctx->type.IsNullConstant() )
  3692. {
  3693. if( to.IsObjectHandle() )
  3694. ctx->type.dataType = to;
  3695. return;
  3696. }
  3697. asASSERT(ctx->type.dataType.GetObjectType());
  3698. // First attempt to convert the base type without instanciating another instance
  3699. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  3700. {
  3701. // If the to type is an interface and the from type implements it, then we can convert it immediately
  3702. if( ctx->type.dataType.GetObjectType()->Implements(to.GetObjectType()) )
  3703. {
  3704. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3705. }
  3706. // If the to type is a class and the from type derives from it, then we can convert it immediately
  3707. if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3708. {
  3709. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3710. }
  3711. // If the types are not equal yet, then we may still be able to find a reference cast
  3712. if( ctx->type.dataType.GetObjectType() != to.GetObjectType() )
  3713. {
  3714. // A ref cast must not remove the constness
  3715. bool isConst = false;
  3716. if( (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) ||
  3717. (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) )
  3718. isConst = true;
  3719. // We may still be able to find an implicit ref cast behaviour
  3720. CompileRefCast(ctx, to, convType == asIC_EXPLICIT_REF_CAST, node, generateCode);
  3721. ctx->type.dataType.MakeHandleToConst(isConst);
  3722. }
  3723. }
  3724. // If the base type is still different, and we are allowed to instance
  3725. // another object then we can try an implicit value cast
  3726. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  3727. {
  3728. // TODO: Implement support for implicit constructor/factory
  3729. asCArray<int> funcs;
  3730. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  3731. if( beh )
  3732. {
  3733. if( convType == asIC_EXPLICIT_VAL_CAST )
  3734. {
  3735. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3736. {
  3737. // accept both implicit and explicit cast
  3738. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  3739. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  3740. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  3741. funcs.PushLast(beh->operators[n+1]);
  3742. }
  3743. }
  3744. else
  3745. {
  3746. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3747. {
  3748. // accept only implicit cast
  3749. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  3750. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  3751. funcs.PushLast(beh->operators[n+1]);
  3752. }
  3753. }
  3754. }
  3755. // TODO: If there are multiple valid value casts, then we must choose the most appropriate one
  3756. asASSERT( funcs.GetLength() <= 1 );
  3757. if( funcs.GetLength() == 1 )
  3758. {
  3759. asCScriptFunction *f = builder->GetFunctionDescription(funcs[0]);
  3760. if( generateCode )
  3761. {
  3762. asCTypeInfo objType = ctx->type;
  3763. Dereference(ctx, true);
  3764. PerformFunctionCall(funcs[0], ctx);
  3765. ReleaseTemporaryVariable(objType, &ctx->bc);
  3766. }
  3767. else
  3768. ctx->type.Set(f->returnType);
  3769. }
  3770. }
  3771. // If we still haven't converted the base type to the correct type, then there is no need to continue
  3772. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  3773. return;
  3774. // Convert matching function types
  3775. if( to.GetFuncDef() && ctx->type.dataType.GetFuncDef() &&
  3776. to.GetFuncDef() != ctx->type.dataType.GetFuncDef() )
  3777. {
  3778. asCScriptFunction *toFunc = to.GetFuncDef();
  3779. asCScriptFunction *fromFunc = ctx->type.dataType.GetFuncDef();
  3780. if( toFunc->IsSignatureExceptNameEqual(fromFunc) )
  3781. {
  3782. ctx->type.dataType.SetFuncDef(toFunc);
  3783. }
  3784. }
  3785. if( to.IsObjectHandle() )
  3786. {
  3787. // reference to handle -> handle
  3788. // reference -> handle
  3789. // object -> handle
  3790. // handle -> reference to handle
  3791. // reference -> reference to handle
  3792. // object -> reference to handle
  3793. // TODO: If the type is handle, then we can't use IsReadOnly to determine the constness of the basetype
  3794. // If the rvalue is a handle to a const object, then
  3795. // the lvalue must also be a handle to a const object
  3796. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() )
  3797. {
  3798. if( convType != asIC_IMPLICIT_CONV )
  3799. {
  3800. asASSERT(node);
  3801. asCString str;
  3802. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3803. Error(str.AddressOf(), node);
  3804. }
  3805. }
  3806. if( !ctx->type.dataType.IsObjectHandle() )
  3807. {
  3808. // An object type can be directly converted to a handle of the same type
  3809. if( ctx->type.dataType.SupportHandles() )
  3810. {
  3811. ctx->type.dataType.MakeHandle(true);
  3812. }
  3813. if( ctx->type.dataType.IsObjectHandle() )
  3814. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3815. if( to.IsHandleToConst() && ctx->type.dataType.IsObjectHandle() )
  3816. ctx->type.dataType.MakeHandleToConst(true);
  3817. }
  3818. else
  3819. {
  3820. // A handle to non-const can be converted to a
  3821. // handle to const, but not the other way
  3822. if( to.IsHandleToConst() )
  3823. ctx->type.dataType.MakeHandleToConst(true);
  3824. // A const handle can be converted to a non-const
  3825. // handle and vice versa as the handle is just a value
  3826. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3827. }
  3828. if( to.IsReference() && !ctx->type.dataType.IsReference() )
  3829. {
  3830. if( generateCode )
  3831. {
  3832. // If the input type is a handle, then a simple ref copy is enough
  3833. bool isExplicitHandle = ctx->type.isExplicitHandle;
  3834. ctx->type.isExplicitHandle = ctx->type.dataType.IsObjectHandle();
  3835. // If the input type is read-only we'll need to temporarily
  3836. // remove this constness, otherwise the assignment will fail
  3837. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  3838. ctx->type.dataType.MakeReadOnly(false);
  3839. // If the object already is a temporary variable, then the copy
  3840. // doesn't have to be made as it is already a unique object
  3841. PrepareTemporaryObject(node, ctx, reservedVars);
  3842. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  3843. ctx->type.isExplicitHandle = isExplicitHandle;
  3844. }
  3845. // A non-reference can be converted to a reference,
  3846. // by putting the value in a temporary variable
  3847. ctx->type.dataType.MakeReference(true);
  3848. // Since it is a new temporary variable it doesn't have to be const
  3849. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3850. }
  3851. else if( !to.IsReference() && ctx->type.dataType.IsReference() )
  3852. {
  3853. // ASHANDLE is really a value type, even though it looks
  3854. // like a handle, so we shouldn't dereference it
  3855. if( !(ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) ||
  3856. (ctx->type.isVariable && IsVariableOnHeap(ctx->type.stackOffset)) )
  3857. Dereference(ctx, generateCode);
  3858. else
  3859. ctx->type.dataType.MakeReference(false);
  3860. }
  3861. }
  3862. else
  3863. {
  3864. if( !to.IsReference() )
  3865. {
  3866. // reference to handle -> object
  3867. // handle -> object
  3868. // reference -> object
  3869. // An implicit handle can be converted to an object by adding a check for null pointer
  3870. if( ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  3871. {
  3872. if( generateCode )
  3873. ctx->bc.Instr(asBC_CHKREF);
  3874. ctx->type.dataType.MakeHandle(false);
  3875. }
  3876. // A const object can be converted to a non-const object through a copy
  3877. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() &&
  3878. allowObjectConstruct )
  3879. {
  3880. // Does the object type allow a copy to be made?
  3881. if( ctx->type.dataType.CanBeCopied() )
  3882. {
  3883. if( generateCode )
  3884. {
  3885. // Make a temporary object with the copy
  3886. PrepareTemporaryObject(node, ctx, reservedVars);
  3887. }
  3888. // In case the object was already in a temporary variable, then the function
  3889. // didn't really do anything so we need to remove the constness here
  3890. ctx->type.dataType.MakeReadOnly(false);
  3891. }
  3892. }
  3893. if( ctx->type.dataType.IsReference() )
  3894. {
  3895. Dereference(ctx, generateCode);
  3896. // TODO: Can't this leave unhandled deferred output params?
  3897. }
  3898. // A non-const object can be converted to a const object directly
  3899. if( !ctx->type.dataType.IsReadOnly() && to.IsReadOnly() )
  3900. {
  3901. ctx->type.dataType.MakeReadOnly(true);
  3902. }
  3903. }
  3904. else
  3905. {
  3906. // reference to handle -> reference
  3907. // handle -> reference
  3908. // object -> reference
  3909. if( ctx->type.dataType.IsReference() )
  3910. {
  3911. if( ctx->type.isExplicitHandle && ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  3912. {
  3913. // ASHANDLE objects are really value types, so explicit handle can be removed
  3914. ctx->type.isExplicitHandle = false;
  3915. ctx->type.dataType.MakeHandle(false);
  3916. }
  3917. // A reference to a handle can be converted to a reference to an object
  3918. // by first reading the address, then verifying that it is not null
  3919. if( !to.IsObjectHandle() && ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  3920. {
  3921. ctx->type.dataType.MakeHandle(false);
  3922. if( generateCode )
  3923. ctx->bc.Instr(asBC_ChkRefS);
  3924. }
  3925. // A reference to a non-const can be converted to a reference to a const
  3926. if( to.IsReadOnly() )
  3927. ctx->type.dataType.MakeReadOnly(true);
  3928. else if( ctx->type.dataType.IsReadOnly() )
  3929. {
  3930. // A reference to a const can be converted to a reference to a
  3931. // non-const by copying the object to a temporary variable
  3932. ctx->type.dataType.MakeReadOnly(false);
  3933. if( generateCode )
  3934. {
  3935. // If the object already is a temporary variable, then the copy
  3936. // doesn't have to be made as it is already a unique object
  3937. PrepareTemporaryObject(node, ctx, reservedVars);
  3938. }
  3939. }
  3940. }
  3941. else
  3942. {
  3943. // A value type allocated on the stack is differentiated
  3944. // by it not being a reference. But it can be handled as
  3945. // reference by pushing the pointer on the stack
  3946. if( (ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) &&
  3947. (ctx->type.isVariable || ctx->type.isTemporary) &&
  3948. !IsVariableOnHeap(ctx->type.stackOffset) )
  3949. {
  3950. // Actually the pointer is already pushed on the stack in
  3951. // CompileVariableAccess, so we don't need to do anything else
  3952. }
  3953. else if( generateCode )
  3954. {
  3955. // A non-reference can be converted to a reference,
  3956. // by putting the value in a temporary variable
  3957. // If the input type is read-only we'll need to temporarily
  3958. // remove this constness, otherwise the assignment will fail
  3959. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  3960. ctx->type.dataType.MakeReadOnly(false);
  3961. // If the object already is a temporary variable, then the copy
  3962. // doesn't have to be made as it is already a unique object
  3963. PrepareTemporaryObject(node, ctx, reservedVars);
  3964. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  3965. }
  3966. // A handle can be converted to a reference, by checking for a null pointer
  3967. if( ctx->type.dataType.IsObjectHandle() )
  3968. {
  3969. if( generateCode )
  3970. ctx->bc.InstrSHORT(asBC_ChkNullV, ctx->type.stackOffset);
  3971. ctx->type.dataType.MakeHandle(false);
  3972. ctx->type.dataType.MakeReference(true);
  3973. // TODO: Make sure a handle to const isn't converted to non-const reference
  3974. }
  3975. else
  3976. {
  3977. // This may look strange as the conversion was to make the expression a reference
  3978. // but a value type allocated on the stack is a reference even without the type
  3979. // being marked as such.
  3980. ctx->type.dataType.MakeReference(IsVariableOnHeap(ctx->type.stackOffset));
  3981. }
  3982. // TODO: If the variable is an object allocated on the stack, this is not true
  3983. // Since it is a new temporary variable it doesn't have to be const
  3984. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3985. }
  3986. }
  3987. }
  3988. }
  3989. void asCCompiler::ImplicitConvPrimitiveToObject(asSExprContext * /*ctx*/, const asCDataType & /*to*/, asCScriptNode * /*node*/, EImplicitConv /*isExplicit*/, bool /*generateCode*/, asCArray<int> * /*reservedVars*/, bool /*allowObjectConstruct*/)
  3990. {
  3991. // TODO: This function should call the constructor/factory that has been marked as available
  3992. // for implicit conversions. The code will likely be similar to CallCopyConstructor()
  3993. }
  3994. void asCCompiler::ImplicitConversionConstant(asSExprContext *from, const asCDataType &to, asCScriptNode *node, EImplicitConv convType)
  3995. {
  3996. asASSERT(from->type.isConstant);
  3997. // TODO: node should be the node of the value that is
  3998. // converted (not the operator that provokes the implicit
  3999. // conversion)
  4000. // If the base type is correct there is no more to do
  4001. if( to.IsEqualExceptRefAndConst(from->type.dataType) ) return;
  4002. // References cannot be constants
  4003. if( from->type.dataType.IsReference() ) return;
  4004. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1) ||
  4005. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  4006. {
  4007. if( from->type.dataType.IsFloatType() ||
  4008. from->type.dataType.IsDoubleType() ||
  4009. from->type.dataType.IsUnsignedType() ||
  4010. from->type.dataType.IsIntegerType() ||
  4011. from->type.dataType.IsEnumType() )
  4012. {
  4013. // Transform the value
  4014. // Float constants can be implicitly converted to int
  4015. if( from->type.dataType.IsFloatType() )
  4016. {
  4017. float fc = from->type.floatValue;
  4018. int ic = int(fc);
  4019. if( float(ic) != fc )
  4020. {
  4021. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4022. }
  4023. from->type.intValue = ic;
  4024. }
  4025. // Double constants can be implicitly converted to int
  4026. else if( from->type.dataType.IsDoubleType() )
  4027. {
  4028. double fc = from->type.doubleValue;
  4029. int ic = int(fc);
  4030. if( double(ic) != fc )
  4031. {
  4032. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4033. }
  4034. from->type.intValue = ic;
  4035. }
  4036. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4037. {
  4038. // Verify that it is possible to convert to signed without getting negative
  4039. if( from->type.intValue < 0 )
  4040. {
  4041. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4042. }
  4043. // Convert to 32bit
  4044. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4045. from->type.intValue = from->type.byteValue;
  4046. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4047. from->type.intValue = from->type.wordValue;
  4048. }
  4049. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4050. {
  4051. // Convert to 32bit
  4052. from->type.intValue = int(from->type.qwordValue);
  4053. }
  4054. else if( from->type.dataType.IsIntegerType() &&
  4055. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4056. {
  4057. // Convert to 32bit
  4058. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4059. from->type.intValue = (signed char)from->type.byteValue;
  4060. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4061. from->type.intValue = (short)from->type.wordValue;
  4062. }
  4063. else if( from->type.dataType.IsEnumType() )
  4064. {
  4065. // Enum type is already an integer type
  4066. }
  4067. // Set the resulting type
  4068. if( to.IsEnumType() )
  4069. from->type.dataType = to;
  4070. else
  4071. from->type.dataType = asCDataType::CreatePrimitive(ttInt, true);
  4072. }
  4073. // Check if a downsize is necessary
  4074. if( to.IsIntegerType() &&
  4075. from->type.dataType.IsIntegerType() &&
  4076. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4077. {
  4078. // Verify if it is possible
  4079. if( to.GetSizeInMemoryBytes() == 1 )
  4080. {
  4081. if( char(from->type.intValue) != from->type.intValue )
  4082. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4083. from->type.byteValue = char(from->type.intValue);
  4084. }
  4085. else if( to.GetSizeInMemoryBytes() == 2 )
  4086. {
  4087. if( short(from->type.intValue) != from->type.intValue )
  4088. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4089. from->type.wordValue = short(from->type.intValue);
  4090. }
  4091. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4092. }
  4093. }
  4094. else if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  4095. {
  4096. // Float constants can be implicitly converted to int
  4097. if( from->type.dataType.IsFloatType() )
  4098. {
  4099. float fc = from->type.floatValue;
  4100. asINT64 ic = asINT64(fc);
  4101. if( float(ic) != fc )
  4102. {
  4103. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4104. }
  4105. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4106. from->type.qwordValue = ic;
  4107. }
  4108. // Double constants can be implicitly converted to int
  4109. else if( from->type.dataType.IsDoubleType() )
  4110. {
  4111. double fc = from->type.doubleValue;
  4112. asINT64 ic = asINT64(fc);
  4113. if( double(ic) != fc )
  4114. {
  4115. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4116. }
  4117. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4118. from->type.qwordValue = ic;
  4119. }
  4120. else if( from->type.dataType.IsUnsignedType() )
  4121. {
  4122. // Convert to 64bit
  4123. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4124. from->type.qwordValue = from->type.byteValue;
  4125. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4126. from->type.qwordValue = from->type.wordValue;
  4127. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4128. from->type.qwordValue = from->type.dwordValue;
  4129. else if( from->type.dataType.GetSizeInMemoryBytes() == 8 )
  4130. {
  4131. if( asINT64(from->type.qwordValue) < 0 )
  4132. {
  4133. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4134. }
  4135. }
  4136. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4137. }
  4138. else if( from->type.dataType.IsEnumType() )
  4139. {
  4140. from->type.qwordValue = from->type.intValue;
  4141. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4142. }
  4143. else if( from->type.dataType.IsIntegerType() )
  4144. {
  4145. // Convert to 64bit
  4146. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4147. from->type.qwordValue = (signed char)from->type.byteValue;
  4148. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4149. from->type.qwordValue = (short)from->type.wordValue;
  4150. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4151. from->type.qwordValue = from->type.intValue;
  4152. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4153. }
  4154. }
  4155. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  4156. {
  4157. if( from->type.dataType.IsFloatType() )
  4158. {
  4159. float fc = from->type.floatValue;
  4160. // Some compilers set the value to 0 when converting a negative float to unsigned int.
  4161. // To maintain a consistent behaviour across compilers we convert to int first.
  4162. asUINT uic = asUINT(int(fc));
  4163. if( float(uic) != fc )
  4164. {
  4165. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4166. }
  4167. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4168. from->type.intValue = uic;
  4169. // Try once more, in case of a smaller type
  4170. ImplicitConversionConstant(from, to, node, convType);
  4171. }
  4172. else if( from->type.dataType.IsDoubleType() )
  4173. {
  4174. double fc = from->type.doubleValue;
  4175. // Some compilers set the value to 0 when converting a negative double to unsigned int.
  4176. // To maintain a consistent behaviour across compilers we convert to int first.
  4177. asUINT uic = asUINT(int(fc));
  4178. if( double(uic) != fc )
  4179. {
  4180. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4181. }
  4182. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4183. from->type.intValue = uic;
  4184. // Try once more, in case of a smaller type
  4185. ImplicitConversionConstant(from, to, node, convType);
  4186. }
  4187. else if( from->type.dataType.IsEnumType() )
  4188. {
  4189. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4190. // Try once more, in case of a smaller type
  4191. ImplicitConversionConstant(from, to, node, convType);
  4192. }
  4193. else if( from->type.dataType.IsIntegerType() )
  4194. {
  4195. // Verify that it is possible to convert to unsigned without loosing negative
  4196. if( from->type.intValue < 0 )
  4197. {
  4198. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4199. }
  4200. // Convert to 32bit
  4201. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4202. from->type.intValue = (signed char)from->type.byteValue;
  4203. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4204. from->type.intValue = (short)from->type.wordValue;
  4205. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4206. // Try once more, in case of a smaller type
  4207. ImplicitConversionConstant(from, to, node, convType);
  4208. }
  4209. else if( from->type.dataType.IsUnsignedType() &&
  4210. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4211. {
  4212. // Convert to 32bit
  4213. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4214. from->type.dwordValue = from->type.byteValue;
  4215. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4216. from->type.dwordValue = from->type.wordValue;
  4217. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4218. // Try once more, in case of a smaller type
  4219. ImplicitConversionConstant(from, to, node, convType);
  4220. }
  4221. else if( from->type.dataType.IsUnsignedType() &&
  4222. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4223. {
  4224. // Verify if it is possible
  4225. if( to.GetSizeInMemoryBytes() == 1 )
  4226. {
  4227. if( asBYTE(from->type.dwordValue) != from->type.dwordValue )
  4228. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4229. from->type.byteValue = asBYTE(from->type.dwordValue);
  4230. }
  4231. else if( to.GetSizeInMemoryBytes() == 2 )
  4232. {
  4233. if( asWORD(from->type.dwordValue) != from->type.dwordValue )
  4234. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4235. from->type.wordValue = asWORD(from->type.dwordValue);
  4236. }
  4237. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4238. }
  4239. }
  4240. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  4241. {
  4242. if( from->type.dataType.IsFloatType() )
  4243. {
  4244. float fc = from->type.floatValue;
  4245. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  4246. asQWORD uic = asQWORD(asINT64(fc));
  4247. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  4248. // MSVC6 doesn't support this conversion
  4249. if( float(uic) != fc )
  4250. {
  4251. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4252. }
  4253. #endif
  4254. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4255. from->type.qwordValue = uic;
  4256. }
  4257. else if( from->type.dataType.IsDoubleType() )
  4258. {
  4259. double fc = from->type.doubleValue;
  4260. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  4261. asQWORD uic = asQWORD(asINT64(fc));
  4262. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  4263. // MSVC6 doesn't support this conversion
  4264. if( double(uic) != fc )
  4265. {
  4266. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4267. }
  4268. #endif
  4269. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4270. from->type.qwordValue = uic;
  4271. }
  4272. else if( from->type.dataType.IsEnumType() )
  4273. {
  4274. from->type.qwordValue = (asINT64)from->type.intValue;
  4275. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4276. }
  4277. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4278. {
  4279. // Convert to 64bit
  4280. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4281. from->type.qwordValue = (asINT64)(signed char)from->type.byteValue;
  4282. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4283. from->type.qwordValue = (asINT64)(short)from->type.wordValue;
  4284. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4285. from->type.qwordValue = (asINT64)from->type.intValue;
  4286. // Verify that it is possible to convert to unsigned without loosing negative
  4287. if( asINT64(from->type.qwordValue) < 0 )
  4288. {
  4289. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4290. }
  4291. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4292. }
  4293. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4294. {
  4295. // Verify that it is possible to convert to unsigned without loosing negative
  4296. if( asINT64(from->type.qwordValue) < 0 )
  4297. {
  4298. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4299. }
  4300. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4301. }
  4302. else if( from->type.dataType.IsUnsignedType() )
  4303. {
  4304. // Convert to 64bit
  4305. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4306. from->type.qwordValue = from->type.byteValue;
  4307. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4308. from->type.qwordValue = from->type.wordValue;
  4309. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4310. from->type.qwordValue = from->type.dwordValue;
  4311. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4312. }
  4313. }
  4314. else if( to.IsFloatType() )
  4315. {
  4316. if( from->type.dataType.IsDoubleType() )
  4317. {
  4318. double ic = from->type.doubleValue;
  4319. float fc = float(ic);
  4320. // Don't bother warning about this
  4321. // if( double(fc) != ic )
  4322. // {
  4323. // asCString str;
  4324. // str.Format(TXT_POSSIBLE_LOSS_OF_PRECISION);
  4325. // if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(str.AddressOf(), node);
  4326. // }
  4327. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4328. from->type.floatValue = fc;
  4329. }
  4330. else if( from->type.dataType.IsEnumType() )
  4331. {
  4332. float fc = float(from->type.intValue);
  4333. if( int(fc) != from->type.intValue )
  4334. {
  4335. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4336. }
  4337. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4338. from->type.floatValue = fc;
  4339. }
  4340. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4341. {
  4342. // Must properly convert value in case the from value is smaller
  4343. int ic;
  4344. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4345. ic = (signed char)from->type.byteValue;
  4346. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4347. ic = (short)from->type.wordValue;
  4348. else
  4349. ic = from->type.intValue;
  4350. float fc = float(ic);
  4351. if( int(fc) != ic )
  4352. {
  4353. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4354. }
  4355. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4356. from->type.floatValue = fc;
  4357. }
  4358. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4359. {
  4360. float fc = float(asINT64(from->type.qwordValue));
  4361. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  4362. {
  4363. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4364. }
  4365. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4366. from->type.floatValue = fc;
  4367. }
  4368. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4369. {
  4370. // Must properly convert value in case the from value is smaller
  4371. unsigned int uic;
  4372. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4373. uic = from->type.byteValue;
  4374. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4375. uic = from->type.wordValue;
  4376. else
  4377. uic = from->type.dwordValue;
  4378. float fc = float(uic);
  4379. if( (unsigned int)(fc) != uic )
  4380. {
  4381. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4382. }
  4383. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4384. from->type.floatValue = fc;
  4385. }
  4386. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4387. {
  4388. float fc = float((asINT64)from->type.qwordValue);
  4389. if( asQWORD(fc) != from->type.qwordValue )
  4390. {
  4391. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4392. }
  4393. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4394. from->type.floatValue = fc;
  4395. }
  4396. }
  4397. else if( to.IsDoubleType() )
  4398. {
  4399. if( from->type.dataType.IsFloatType() )
  4400. {
  4401. float ic = from->type.floatValue;
  4402. double fc = double(ic);
  4403. // Don't check for float->double
  4404. // if( float(fc) != ic )
  4405. // {
  4406. // acCString str;
  4407. // str.Format(TXT_NOT_EXACT_g_g_g, ic, fc, float(fc));
  4408. // if( !isExplicit ) Warning(str, node);
  4409. // }
  4410. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4411. from->type.doubleValue = fc;
  4412. }
  4413. else if( from->type.dataType.IsEnumType() )
  4414. {
  4415. double fc = double(from->type.intValue);
  4416. if( int(fc) != from->type.intValue )
  4417. {
  4418. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4419. }
  4420. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4421. from->type.doubleValue = fc;
  4422. }
  4423. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4424. {
  4425. // Must properly convert value in case the from value is smaller
  4426. int ic;
  4427. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4428. ic = (signed char)from->type.byteValue;
  4429. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4430. ic = (short)from->type.wordValue;
  4431. else
  4432. ic = from->type.intValue;
  4433. double fc = double(ic);
  4434. if( int(fc) != ic )
  4435. {
  4436. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4437. }
  4438. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4439. from->type.doubleValue = fc;
  4440. }
  4441. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4442. {
  4443. double fc = double(asINT64(from->type.qwordValue));
  4444. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  4445. {
  4446. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4447. }
  4448. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4449. from->type.doubleValue = fc;
  4450. }
  4451. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4452. {
  4453. // Must properly convert value in case the from value is smaller
  4454. unsigned int uic;
  4455. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4456. uic = from->type.byteValue;
  4457. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4458. uic = from->type.wordValue;
  4459. else
  4460. uic = from->type.dwordValue;
  4461. double fc = double(uic);
  4462. if( (unsigned int)(fc) != uic )
  4463. {
  4464. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4465. }
  4466. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4467. from->type.doubleValue = fc;
  4468. }
  4469. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4470. {
  4471. double fc = double((asINT64)from->type.qwordValue);
  4472. if( asQWORD(fc) != from->type.qwordValue )
  4473. {
  4474. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4475. }
  4476. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4477. from->type.doubleValue = fc;
  4478. }
  4479. }
  4480. }
  4481. int asCCompiler::DoAssignment(asSExprContext *ctx, asSExprContext *lctx, asSExprContext *rctx, asCScriptNode *lexpr, asCScriptNode *rexpr, int op, asCScriptNode *opNode)
  4482. {
  4483. // Implicit handle types should always be treated as handles in assignments
  4484. if (lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  4485. {
  4486. lctx->type.dataType.MakeHandle(true);
  4487. lctx->type.isExplicitHandle = true;
  4488. }
  4489. // Urho3D: if there is a handle type, and it does not have an overloaded assignment operator, convert to an explicit handle
  4490. // for scripting convenience. (For the Urho3D handle types, value assignment is not supported)
  4491. if (lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle && !lctx->type.dataType.GetObjectType()->beh.copy)
  4492. lctx->type.isExplicitHandle = true;
  4493. // If the left hand expression is a property accessor, then that should be used
  4494. // to do the assignment instead of the ordinary operator. The exception is when
  4495. // the property accessor is for a handle property, and the operation is a value
  4496. // assignment.
  4497. if( (lctx->property_get || lctx->property_set) &&
  4498. !(lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle) )
  4499. {
  4500. if( op != ttAssignment )
  4501. {
  4502. // TODO: getset: We may actually be able to support this, if we can
  4503. // guarantee that the object reference will stay valid
  4504. // between the calls to the get and set accessors.
  4505. // Process the property to free the memory
  4506. ProcessPropertySetAccessor(lctx, rctx, opNode);
  4507. // Compound assignments are not allowed for properties
  4508. Error(TXT_COMPOUND_ASGN_WITH_PROP, opNode);
  4509. return -1;
  4510. }
  4511. // It is not allowed to do a handle assignment on a property
  4512. // accessor that doesn't take a handle in the set accessor.
  4513. if( lctx->property_set && lctx->type.isExplicitHandle )
  4514. {
  4515. // set_opIndex has 2 arguments, where as normal setters have only 1
  4516. asCArray<asCDataType>& parameterTypes =
  4517. engine->scriptFunctions[lctx->property_set]->parameterTypes;
  4518. if( !parameterTypes[parameterTypes.GetLength() - 1].IsObjectHandle() )
  4519. {
  4520. // Process the property to free the memory
  4521. ProcessPropertySetAccessor(lctx, rctx, opNode);
  4522. Error(TXT_HANDLE_ASSIGN_ON_NON_HANDLE_PROP, opNode);
  4523. return -1;
  4524. }
  4525. }
  4526. MergeExprBytecodeAndType(ctx, lctx);
  4527. return ProcessPropertySetAccessor(ctx, rctx, opNode);
  4528. }
  4529. else if( lctx->property_get && lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  4530. {
  4531. // Get the handle to the object that will be used for the value assignment
  4532. ProcessPropertyGetAccessor(lctx, opNode);
  4533. }
  4534. if( lctx->type.dataType.IsPrimitive() )
  4535. {
  4536. if( !lctx->type.isLValue )
  4537. {
  4538. Error(TXT_NOT_LVALUE, lexpr);
  4539. return -1;
  4540. }
  4541. if( op != ttAssignment )
  4542. {
  4543. // Compute the operator before the assignment
  4544. asCTypeInfo lvalue = lctx->type;
  4545. if( lctx->type.isTemporary && !lctx->type.isVariable )
  4546. {
  4547. // The temporary variable must not be freed until the
  4548. // assignment has been performed. lvalue still holds
  4549. // the information about the temporary variable
  4550. lctx->type.isTemporary = false;
  4551. }
  4552. asSExprContext o(engine);
  4553. CompileOperator(opNode, lctx, rctx, &o);
  4554. MergeExprBytecode(rctx, &o);
  4555. rctx->type = o.type;
  4556. // Convert the rvalue to the right type and validate it
  4557. PrepareForAssignment(&lvalue.dataType, rctx, rexpr);
  4558. MergeExprBytecode(ctx, rctx);
  4559. lctx->type = lvalue;
  4560. // The lvalue continues the same, either it was a variable, or a reference in the register
  4561. }
  4562. else
  4563. {
  4564. // Convert the rvalue to the right type and validate it
  4565. PrepareForAssignment(&lctx->type.dataType, rctx, rexpr, lctx);
  4566. MergeExprBytecode(ctx, rctx);
  4567. MergeExprBytecode(ctx, lctx);
  4568. }
  4569. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4570. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4571. ctx->type = lctx->type;
  4572. }
  4573. else if( lctx->type.isExplicitHandle )
  4574. {
  4575. if( !lctx->type.isLValue )
  4576. {
  4577. Error(TXT_NOT_LVALUE, lexpr);
  4578. return -1;
  4579. }
  4580. // Object handles don't have any compound assignment operators
  4581. if( op != ttAssignment )
  4582. {
  4583. asCString str;
  4584. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4585. Error(str.AddressOf(), lexpr);
  4586. return -1;
  4587. }
  4588. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  4589. {
  4590. // The object is a value type but that should be treated as a handle
  4591. // TODO: handle: Make sure the right hand value is a handle
  4592. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  4593. {
  4594. // An overloaded assignment operator was found (or a compilation error occured)
  4595. return 0;
  4596. }
  4597. // The object must implement the opAssign method
  4598. Error(TXT_NO_APPROPRIATE_OPASSIGN, opNode);
  4599. return -1;
  4600. }
  4601. else
  4602. {
  4603. asCDataType dt = lctx->type.dataType;
  4604. dt.MakeReference(false);
  4605. PrepareArgument(&dt, rctx, rexpr, true, 1);
  4606. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4607. {
  4608. asCString str;
  4609. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  4610. Error(str.AddressOf(), rexpr);
  4611. return -1;
  4612. }
  4613. MergeExprBytecode(ctx, rctx);
  4614. MergeExprBytecode(ctx, lctx);
  4615. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  4616. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4617. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4618. ctx->type = rctx->type;
  4619. }
  4620. }
  4621. else // if( lctx->type.dataType.IsObject() )
  4622. {
  4623. // An ASHANDLE type must not allow a value assignment, as
  4624. // the opAssign operator is used for the handle assignment
  4625. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  4626. {
  4627. asCString str;
  4628. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4629. Error(str.AddressOf(), lexpr);
  4630. return -1;
  4631. }
  4632. // The lvalue reference may be marked as a temporary, if for example
  4633. // it was originated as a handle returned from a function. In such
  4634. // cases it must be possible to assign values to it anyway.
  4635. if( lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  4636. {
  4637. // Convert the handle to a object reference
  4638. asCDataType to;
  4639. to = lctx->type.dataType;
  4640. to.MakeHandle(false);
  4641. ImplicitConversion(lctx, to, lexpr, asIC_IMPLICIT_CONV);
  4642. lctx->type.isLValue = true; // Handle may not have been an lvalue, but the dereferenced object is
  4643. }
  4644. // Check for overloaded assignment operator
  4645. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  4646. {
  4647. // An overloaded assignment operator was found (or a compilation error occured)
  4648. return 0;
  4649. }
  4650. // No registered operator was found. In case the operation is a direct
  4651. // assignment and the rvalue is the same type as the lvalue, then we can
  4652. // still use the byte-for-byte copy to do the assignment
  4653. if( op != ttAssignment )
  4654. {
  4655. asCString str;
  4656. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4657. Error(str.AddressOf(), lexpr);
  4658. return -1;
  4659. }
  4660. // If the left hand expression is simple, i.e. without any
  4661. // function calls or allocations of memory, then we can avoid
  4662. // doing a copy of the right hand expression (done by PrepareArgument).
  4663. // Instead the reference to the value can be placed directly on the
  4664. // stack.
  4665. //
  4666. // This optimization should only be done for value types, where
  4667. // the application developer is responsible for making the
  4668. // implementation safe against unwanted destruction of the input
  4669. // reference before the time.
  4670. bool simpleExpr = (lctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) && lctx->bc.IsSimpleExpression();
  4671. // Implicitly convert the rvalue to the type of the lvalue
  4672. if( !lctx->type.dataType.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4673. simpleExpr = false;
  4674. if( !simpleExpr )
  4675. {
  4676. asCDataType dt = lctx->type.dataType;
  4677. dt.MakeReference(true);
  4678. dt.MakeReadOnly(true);
  4679. PrepareArgument(&dt, rctx, rexpr, true, 1);
  4680. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4681. {
  4682. asCString str;
  4683. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  4684. Error(str.AddressOf(), rexpr);
  4685. return -1;
  4686. }
  4687. }
  4688. else if( rctx->type.dataType.IsReference() && (!(rctx->type.isVariable || rctx->type.isTemporary) || IsVariableOnHeap(rctx->type.stackOffset)) )
  4689. rctx->bc.Instr(asBC_RDSPTR);
  4690. MergeExprBytecode(ctx, rctx);
  4691. MergeExprBytecode(ctx, lctx);
  4692. if( !simpleExpr )
  4693. {
  4694. if( (rctx->type.isVariable || rctx->type.isTemporary) && !IsVariableOnHeap(rctx->type.stackOffset) )
  4695. // TODO: optimize: Actually the reference can be pushed on the stack directly
  4696. // as the value allocated on the stack is guaranteed to be safe
  4697. ctx->bc.InstrWORD(asBC_GETREF, AS_PTR_SIZE);
  4698. else
  4699. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  4700. }
  4701. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4702. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4703. ctx->type = lctx->type;
  4704. }
  4705. return 0;
  4706. }
  4707. int asCCompiler::CompileAssignment(asCScriptNode *expr, asSExprContext *ctx)
  4708. {
  4709. asCScriptNode *lexpr = expr->firstChild;
  4710. if( lexpr->next )
  4711. {
  4712. // Compile the two expression terms
  4713. asSExprContext lctx(engine), rctx(engine);
  4714. int rr = CompileAssignment(lexpr->next->next, &rctx);
  4715. int lr = CompileCondition(lexpr, &lctx);
  4716. if( lr >= 0 && rr >= 0 )
  4717. return DoAssignment(ctx, &lctx, &rctx, lexpr, lexpr->next->next, lexpr->next->tokenType, lexpr->next);
  4718. // Since the operands failed, the assignment was not computed
  4719. ctx->type.SetDummy();
  4720. return -1;
  4721. }
  4722. return CompileCondition(lexpr, ctx);
  4723. }
  4724. int asCCompiler::CompileCondition(asCScriptNode *expr, asSExprContext *ctx)
  4725. {
  4726. asCTypeInfo ctype;
  4727. // Compile the conditional expression
  4728. asCScriptNode *cexpr = expr->firstChild;
  4729. if( cexpr->next )
  4730. {
  4731. //-------------------------------
  4732. // Compile the condition
  4733. asSExprContext e(engine);
  4734. int r = CompileExpression(cexpr, &e);
  4735. if( r < 0 )
  4736. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  4737. if( r >= 0 && !e.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  4738. {
  4739. Error(TXT_EXPR_MUST_BE_BOOL, cexpr);
  4740. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  4741. }
  4742. ctype = e.type;
  4743. ProcessPropertyGetAccessor(&e, cexpr);
  4744. if( e.type.dataType.IsReference() ) ConvertToVariable(&e);
  4745. ProcessDeferredParams(&e);
  4746. //-------------------------------
  4747. // Compile the left expression
  4748. asSExprContext le(engine);
  4749. int lr = CompileAssignment(cexpr->next, &le);
  4750. //-------------------------------
  4751. // Compile the right expression
  4752. asSExprContext re(engine);
  4753. int rr = CompileAssignment(cexpr->next->next, &re);
  4754. if( lr >= 0 && rr >= 0 )
  4755. {
  4756. ProcessPropertyGetAccessor(&le, cexpr->next);
  4757. ProcessPropertyGetAccessor(&re, cexpr->next->next);
  4758. bool isExplicitHandle = le.type.isExplicitHandle || re.type.isExplicitHandle;
  4759. // Allow a 0 or null in the first case to be implicitly converted to the second type
  4760. if( le.type.isConstant && le.type.intValue == 0 && le.type.dataType.IsUnsignedType() )
  4761. {
  4762. asCDataType to = re.type.dataType;
  4763. to.MakeReference(false);
  4764. to.MakeReadOnly(true);
  4765. ImplicitConversionConstant(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  4766. }
  4767. else if( le.type.IsNullConstant() )
  4768. {
  4769. asCDataType to = re.type.dataType;
  4770. to.MakeHandle(true);
  4771. ImplicitConversion(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  4772. }
  4773. //---------------------------------
  4774. // Output the byte code
  4775. int afterLabel = nextLabel++;
  4776. int elseLabel = nextLabel++;
  4777. // If left expression is void, then we don't need to store the result
  4778. if( le.type.dataType.IsEqualExceptConst(asCDataType::CreatePrimitive(ttVoid, false)) )
  4779. {
  4780. // Put the code for the condition expression on the output
  4781. MergeExprBytecode(ctx, &e);
  4782. // Added the branch decision
  4783. ctx->type = e.type;
  4784. ConvertToVariable(ctx);
  4785. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  4786. ctx->bc.Instr(asBC_ClrHi);
  4787. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  4788. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4789. // Add the left expression
  4790. MergeExprBytecode(ctx, &le);
  4791. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  4792. // Add the right expression
  4793. ctx->bc.Label((short)elseLabel);
  4794. MergeExprBytecode(ctx, &re);
  4795. ctx->bc.Label((short)afterLabel);
  4796. // Make sure both expressions have the same type
  4797. if( le.type.dataType != re.type.dataType )
  4798. Error(TXT_BOTH_MUST_BE_SAME, expr);
  4799. // Set the type of the result
  4800. ctx->type = le.type;
  4801. }
  4802. else
  4803. {
  4804. // Allocate temporary variable and copy the result to that one
  4805. asCTypeInfo temp;
  4806. temp = le.type;
  4807. temp.dataType.MakeReference(false);
  4808. temp.dataType.MakeReadOnly(false);
  4809. // Make sure the variable isn't used in the initial expression
  4810. asCArray<int> vars;
  4811. e.bc.GetVarsUsed(vars);
  4812. int offset = AllocateVariableNotIn(temp.dataType, true, &vars);
  4813. temp.SetVariable(temp.dataType, offset, true);
  4814. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  4815. CallDefaultConstructor(temp.dataType, offset, IsVariableOnHeap(offset), &ctx->bc, expr);
  4816. // Put the code for the condition expression on the output
  4817. MergeExprBytecode(ctx, &e);
  4818. // Add the branch decision
  4819. ctx->type = e.type;
  4820. ConvertToVariable(ctx);
  4821. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  4822. ctx->bc.Instr(asBC_ClrHi);
  4823. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  4824. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4825. // Assign the result of the left expression to the temporary variable
  4826. asCTypeInfo rtemp;
  4827. rtemp = temp;
  4828. if( rtemp.dataType.IsObjectHandle() )
  4829. rtemp.isExplicitHandle = true;
  4830. PrepareForAssignment(&rtemp.dataType, &le, cexpr->next);
  4831. MergeExprBytecode(ctx, &le);
  4832. if( !rtemp.dataType.IsPrimitive() )
  4833. {
  4834. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  4835. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  4836. }
  4837. PerformAssignment(&rtemp, &le.type, &ctx->bc, cexpr->next);
  4838. if( !rtemp.dataType.IsPrimitive() )
  4839. ctx->bc.Pop(le.type.dataType.GetSizeOnStackDWords()); // Pop the original value
  4840. // Release the old temporary variable
  4841. ReleaseTemporaryVariable(le.type, &ctx->bc);
  4842. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  4843. // Start of the right expression
  4844. ctx->bc.Label((short)elseLabel);
  4845. // Copy the result to the same temporary variable
  4846. PrepareForAssignment(&rtemp.dataType, &re, cexpr->next);
  4847. MergeExprBytecode(ctx, &re);
  4848. if( !rtemp.dataType.IsPrimitive() )
  4849. {
  4850. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  4851. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  4852. }
  4853. PerformAssignment(&rtemp, &re.type, &ctx->bc, cexpr->next);
  4854. if( !rtemp.dataType.IsPrimitive() )
  4855. ctx->bc.Pop(le.type.dataType.GetSizeOnStackDWords()); // Pop the original value
  4856. // Release the old temporary variable
  4857. ReleaseTemporaryVariable(re.type, &ctx->bc);
  4858. ctx->bc.Label((short)afterLabel);
  4859. // Make sure both expressions have the same type
  4860. if( le.type.dataType != re.type.dataType )
  4861. Error(TXT_BOTH_MUST_BE_SAME, expr);
  4862. // Set the temporary variable as output
  4863. ctx->type = rtemp;
  4864. ctx->type.isExplicitHandle = isExplicitHandle;
  4865. if( !ctx->type.dataType.IsPrimitive() )
  4866. {
  4867. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  4868. ctx->type.dataType.MakeReference(IsVariableOnHeap(offset));
  4869. }
  4870. // Make sure the output isn't marked as being a literal constant
  4871. ctx->type.isConstant = false;
  4872. }
  4873. }
  4874. else
  4875. {
  4876. ctx->type.SetDummy();
  4877. return -1;
  4878. }
  4879. }
  4880. else
  4881. return CompileExpression(cexpr, ctx);
  4882. return 0;
  4883. }
  4884. int asCCompiler::CompileExpression(asCScriptNode *expr, asSExprContext *ctx)
  4885. {
  4886. asASSERT(expr->nodeType == snExpression);
  4887. // Count the nodes
  4888. int count = 0;
  4889. asCScriptNode *node = expr->firstChild;
  4890. while( node )
  4891. {
  4892. count++;
  4893. node = node->next;
  4894. }
  4895. // Convert to polish post fix, i.e: a+b => ab+
  4896. asCArray<asCScriptNode *> stack(count);
  4897. asCArray<asCScriptNode *> stack2(count);
  4898. asCArray<asCScriptNode *> postfix(count);
  4899. node = expr->firstChild;
  4900. while( node )
  4901. {
  4902. int precedence = GetPrecedence(node);
  4903. while( stack.GetLength() > 0 &&
  4904. precedence <= GetPrecedence(stack[stack.GetLength()-1]) )
  4905. stack2.PushLast(stack.PopLast());
  4906. stack.PushLast(node);
  4907. node = node->next;
  4908. }
  4909. while( stack.GetLength() > 0 )
  4910. stack2.PushLast(stack.PopLast());
  4911. // We need to swap operands so that the left
  4912. // operand is always computed before the right
  4913. SwapPostFixOperands(stack2, postfix);
  4914. // Compile the postfix formatted expression
  4915. return CompilePostFixExpression(&postfix, ctx);
  4916. }
  4917. void asCCompiler::SwapPostFixOperands(asCArray<asCScriptNode *> &postfix, asCArray<asCScriptNode *> &target)
  4918. {
  4919. if( postfix.GetLength() == 0 ) return;
  4920. asCScriptNode *node = postfix.PopLast();
  4921. if( node->nodeType == snExprTerm )
  4922. {
  4923. target.PushLast(node);
  4924. return;
  4925. }
  4926. SwapPostFixOperands(postfix, target);
  4927. SwapPostFixOperands(postfix, target);
  4928. target.PushLast(node);
  4929. }
  4930. int asCCompiler::CompilePostFixExpression(asCArray<asCScriptNode *> *postfix, asSExprContext *ctx)
  4931. {
  4932. // Shouldn't send any byte code
  4933. asASSERT(ctx->bc.GetLastInstr() == -1);
  4934. // Set the context to a dummy type to avoid further
  4935. // errors in case the expression fails to compile
  4936. ctx->type.SetDummy();
  4937. // Pop the last node
  4938. asCScriptNode *node = postfix->PopLast();
  4939. ctx->exprNode = node;
  4940. // If term, compile the term
  4941. if( node->nodeType == snExprTerm )
  4942. return CompileExpressionTerm(node, ctx);
  4943. // Compile the two expression terms
  4944. asSExprContext r(engine), l(engine);
  4945. int ret;
  4946. ret = CompilePostFixExpression(postfix, &l); if( ret < 0 ) return ret;
  4947. ret = CompilePostFixExpression(postfix, &r); if( ret < 0 ) return ret;
  4948. // Compile the operation
  4949. return CompileOperator(node, &l, &r, ctx);
  4950. }
  4951. int asCCompiler::CompileExpressionTerm(asCScriptNode *node, asSExprContext *ctx)
  4952. {
  4953. // Shouldn't send any byte code
  4954. asASSERT(ctx->bc.GetLastInstr() == -1);
  4955. // Set the type as a dummy by default, in case of any compiler errors
  4956. ctx->type.SetDummy();
  4957. // Compile the value node
  4958. asCScriptNode *vnode = node->firstChild;
  4959. while( vnode->nodeType != snExprValue )
  4960. vnode = vnode->next;
  4961. asSExprContext v(engine);
  4962. int r = CompileExpressionValue(vnode, &v); if( r < 0 ) return r;
  4963. // Compile post fix operators
  4964. asCScriptNode *pnode = vnode->next;
  4965. while( pnode )
  4966. {
  4967. r = CompileExpressionPostOp(pnode, &v); if( r < 0 ) return r;
  4968. pnode = pnode->next;
  4969. }
  4970. // Compile pre fix operators
  4971. pnode = vnode->prev;
  4972. while( pnode )
  4973. {
  4974. r = CompileExpressionPreOp(pnode, &v); if( r < 0 ) return r;
  4975. pnode = pnode->prev;
  4976. }
  4977. // Return the byte code and final type description
  4978. MergeExprBytecodeAndType(ctx, &v);
  4979. return 0;
  4980. }
  4981. int asCCompiler::CompileVariableAccess(const asCString &name, const asCString &scope, asSExprContext *ctx, asCScriptNode *errNode, bool isOptional, bool noFunction, asCObjectType *objType)
  4982. {
  4983. bool found = false;
  4984. // It is a local variable or parameter?
  4985. // This is not accessible by default arg expressions
  4986. sVariable *v = 0;
  4987. if( !isCompilingDefaultArg && scope == "" && !objType )
  4988. v = variables->GetVariable(name.AddressOf());
  4989. if( v )
  4990. {
  4991. found = true;
  4992. if( v->isPureConstant )
  4993. ctx->type.SetConstantQW(v->type, v->constantValue);
  4994. else if( v->type.IsPrimitive() )
  4995. {
  4996. if( v->type.IsReference() )
  4997. {
  4998. // Copy the reference into the register
  4999. #if AS_PTR_SIZE == 1
  5000. ctx->bc.InstrSHORT(asBC_CpyVtoR4, (short)v->stackOffset);
  5001. #else
  5002. ctx->bc.InstrSHORT(asBC_CpyVtoR8, (short)v->stackOffset);
  5003. #endif
  5004. ctx->type.Set(v->type);
  5005. }
  5006. else
  5007. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5008. ctx->type.isLValue = true;
  5009. }
  5010. else
  5011. {
  5012. ctx->bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  5013. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5014. // If the variable is allocated on the heap we have a reference,
  5015. // otherwise the actual object pointer is pushed on the stack.
  5016. if( v->onHeap || v->type.IsObjectHandle() ) ctx->type.dataType.MakeReference(true);
  5017. // Implicitly dereference handle parameters sent by reference
  5018. if( v->type.IsReference() && (!v->type.IsObject() || v->type.IsObjectHandle()) )
  5019. ctx->bc.Instr(asBC_RDSPTR);
  5020. ctx->type.isLValue = true;
  5021. }
  5022. }
  5023. // Is it a class member?
  5024. // This is not accessible by default arg expressions
  5025. if( !isCompilingDefaultArg && !found && ((objType) || (outFunc && outFunc->objectType && scope == "")) )
  5026. {
  5027. if( name == THIS_TOKEN && !objType )
  5028. {
  5029. asCDataType dt = asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly);
  5030. // The object pointer is located at stack position 0
  5031. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5032. ctx->type.SetVariable(dt, 0, false);
  5033. ctx->type.dataType.MakeReference(true);
  5034. ctx->type.isLValue = true;
  5035. found = true;
  5036. }
  5037. if( !found )
  5038. {
  5039. // See if there are any matching property accessors
  5040. asSExprContext access(engine);
  5041. if( objType )
  5042. access.type.Set(asCDataType::CreateObject(objType, false));
  5043. else
  5044. access.type.Set(asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly));
  5045. access.type.dataType.MakeReference(true);
  5046. int r = 0;
  5047. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5048. {
  5049. // This is an index access, check if there is a property accessor that takes an index arg
  5050. asSExprContext dummyArg(engine);
  5051. r = FindPropertyAccessor(name, &access, &dummyArg, errNode, true);
  5052. }
  5053. if( r == 0 )
  5054. {
  5055. // Normal property access
  5056. r = FindPropertyAccessor(name, &access, errNode, true);
  5057. }
  5058. if( r < 0 ) return -1;
  5059. if( access.property_get || access.property_set )
  5060. {
  5061. if( !objType )
  5062. {
  5063. // Prepare the bytecode for the member access
  5064. // This is only done when accessing through the implicit this pointer
  5065. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5066. }
  5067. MergeExprBytecodeAndType(ctx, &access);
  5068. found = true;
  5069. }
  5070. }
  5071. if( !found )
  5072. {
  5073. asCDataType dt;
  5074. if( objType )
  5075. dt = asCDataType::CreateObject(objType, false);
  5076. else
  5077. dt = asCDataType::CreateObject(outFunc->objectType, false);
  5078. asCObjectProperty *prop = builder->GetObjectProperty(dt, name.AddressOf());
  5079. if( prop )
  5080. {
  5081. if( !objType )
  5082. {
  5083. // The object pointer is located at stack position 0
  5084. // This is only done when accessing through the implicit this pointer
  5085. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5086. ctx->type.SetVariable(dt, 0, false);
  5087. ctx->type.dataType.MakeReference(true);
  5088. Dereference(ctx, true);
  5089. }
  5090. // TODO: This is the same as what is in CompileExpressionPostOp
  5091. // Put the offset on the stack
  5092. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(dt));
  5093. if( prop->type.IsReference() )
  5094. ctx->bc.Instr(asBC_RDSPTR);
  5095. // Reference to primitive must be stored in the temp register
  5096. if( prop->type.IsPrimitive() )
  5097. {
  5098. // TODO: optimize: The ADD offset command should store the reference in the register directly
  5099. ctx->bc.Instr(asBC_PopRPtr);
  5100. }
  5101. // Set the new type (keeping info about temp variable)
  5102. ctx->type.dataType = prop->type;
  5103. ctx->type.dataType.MakeReference(true);
  5104. ctx->type.isVariable = false;
  5105. ctx->type.isLValue = true;
  5106. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  5107. {
  5108. // Objects that are members are not references
  5109. ctx->type.dataType.MakeReference(false);
  5110. }
  5111. // If the object reference is const, the property will also be const
  5112. ctx->type.dataType.MakeReadOnly(outFunc->isReadOnly);
  5113. found = true;
  5114. }
  5115. }
  5116. }
  5117. // Is it a global property?
  5118. if( !found && (scope == "" || scope == "::") && !objType )
  5119. {
  5120. // See if there are any matching global property accessors
  5121. asSExprContext access(engine);
  5122. int r = 0;
  5123. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5124. {
  5125. // This is an index access, check if there is a property accessor that takes an index arg
  5126. asSExprContext dummyArg(engine);
  5127. r = FindPropertyAccessor(name, &access, &dummyArg, errNode);
  5128. }
  5129. if( r == 0 )
  5130. {
  5131. // Normal property access
  5132. r = FindPropertyAccessor(name, &access, errNode);
  5133. }
  5134. if( r < 0 ) return -1;
  5135. if( access.property_get || access.property_set )
  5136. {
  5137. // Prepare the bytecode for the function call
  5138. MergeExprBytecodeAndType(ctx, &access);
  5139. found = true;
  5140. }
  5141. // See if there is any matching global property
  5142. if( !found )
  5143. {
  5144. bool isCompiled = true;
  5145. bool isPureConstant = false;
  5146. asQWORD constantValue;
  5147. asCGlobalProperty *prop = builder->GetGlobalProperty(name.AddressOf(), &isCompiled, &isPureConstant, &constantValue);
  5148. if( prop )
  5149. {
  5150. found = true;
  5151. // Verify that the global property has been compiled already
  5152. if( isCompiled )
  5153. {
  5154. if( ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  5155. {
  5156. ctx->type.dataType.MakeHandle(true);
  5157. ctx->type.isExplicitHandle = true;
  5158. }
  5159. // If the global property is a pure constant
  5160. // we can allow the compiler to optimize it. Pure
  5161. // constants are global constant variables that were
  5162. // initialized by literal constants.
  5163. if( isPureConstant )
  5164. ctx->type.SetConstantQW(prop->type, constantValue);
  5165. else
  5166. {
  5167. ctx->type.Set(prop->type);
  5168. ctx->type.dataType.MakeReference(true);
  5169. ctx->type.isLValue = true;
  5170. if( ctx->type.dataType.IsPrimitive() )
  5171. {
  5172. // Load the address of the variable into the register
  5173. ctx->bc.InstrPTR(asBC_LDG, engine->globalProperties[prop->id]->GetAddressOfValue());
  5174. }
  5175. else
  5176. {
  5177. // Push the address of the variable on the stack
  5178. ctx->bc.InstrPTR(asBC_PGA, engine->globalProperties[prop->id]->GetAddressOfValue());
  5179. // If the object is a value type, then we must validate the existance,
  5180. // as it could potentially be accessed before it is initialized.
  5181. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_VALUE ||
  5182. !ctx->type.dataType.IsObjectHandle() )
  5183. {
  5184. // TODO: optimize: This is not necessary for application registered properties
  5185. ctx->bc.Instr(asBC_ChkRefS);
  5186. }
  5187. }
  5188. }
  5189. }
  5190. else
  5191. {
  5192. asCString str;
  5193. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, prop->name.AddressOf());
  5194. Error(str.AddressOf(), errNode);
  5195. return -1;
  5196. }
  5197. }
  5198. }
  5199. }
  5200. // Is it the name of a global function?
  5201. if( !noFunction && !found && (scope == "" || scope == "::") && !objType )
  5202. {
  5203. asCArray<int> funcs;
  5204. builder->GetFunctionDescriptions(name.AddressOf(), funcs);
  5205. if( funcs.GetLength() > 1 )
  5206. {
  5207. // TODO: funcdef: If multiple functions are found, then the compiler should defer the decision
  5208. // to which one it should use until the value is actually used.
  5209. //
  5210. // - assigning the function pointer to a variable
  5211. // - performing an explicit cast
  5212. // - passing the function pointer to a function as parameter
  5213. asCString str;
  5214. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, name.AddressOf());
  5215. Error(str.AddressOf(), errNode);
  5216. return -1;
  5217. }
  5218. else if( funcs.GetLength() == 1 )
  5219. {
  5220. found = true;
  5221. // Push the function pointer on the stack
  5222. ctx->bc.InstrPTR(asBC_FuncPtr, engine->scriptFunctions[funcs[0]]);
  5223. ctx->type.Set(asCDataType::CreateFuncDef(engine->scriptFunctions[funcs[0]]));
  5224. }
  5225. }
  5226. // Is it an enum value?
  5227. if( !found && !objType )
  5228. {
  5229. asCObjectType *scopeType = 0;
  5230. if( scope != "" )
  5231. {
  5232. // resolve the type before the scope
  5233. scopeType = builder->GetObjectType( scope.AddressOf() );
  5234. }
  5235. asDWORD value = 0;
  5236. asCDataType dt;
  5237. if( scopeType && builder->GetEnumValueFromObjectType(scopeType, name.AddressOf(), dt, value) )
  5238. {
  5239. // scoped enum value found
  5240. found = true;
  5241. }
  5242. else if( scope == "" && !engine->ep.requireEnumScope )
  5243. {
  5244. // look for the enum value with no namespace
  5245. int e = builder->GetEnumValue(name.AddressOf(), dt, value);
  5246. if( e )
  5247. {
  5248. found = true;
  5249. if( e == 2 )
  5250. {
  5251. Error(TXT_FOUND_MULTIPLE_ENUM_VALUES, errNode);
  5252. }
  5253. }
  5254. }
  5255. if( found )
  5256. {
  5257. // an enum value was resolved
  5258. ctx->type.SetConstantDW(dt, value);
  5259. }
  5260. }
  5261. // The name doesn't match any variable
  5262. if( !found )
  5263. {
  5264. // Give dummy value
  5265. ctx->type.SetDummy();
  5266. if( !isOptional )
  5267. {
  5268. // Prepend the scope to the name for the error message
  5269. asCString ename;
  5270. if( scope != "" && scope != "::" )
  5271. ename = scope + "::";
  5272. else
  5273. ename = scope;
  5274. ename += name;
  5275. asCString str;
  5276. str.Format(TXT_s_NOT_DECLARED, ename.AddressOf());
  5277. Error(str.AddressOf(), errNode);
  5278. // Declare the variable now so that it will not be reported again
  5279. variables->DeclareVariable(name.AddressOf(), asCDataType::CreatePrimitive(ttInt, false), 0x7FFF, true);
  5280. // Mark the variable as initialized so that the user will not be bother by it again
  5281. sVariable *v = variables->GetVariable(name.AddressOf());
  5282. asASSERT(v);
  5283. if( v ) v->isInitialized = true;
  5284. }
  5285. // Return -1 to signal that the variable wasn't found
  5286. return -1;
  5287. }
  5288. return 0;
  5289. }
  5290. int asCCompiler::CompileExpressionValue(asCScriptNode *node, asSExprContext *ctx)
  5291. {
  5292. // Shouldn't receive any byte code
  5293. asASSERT(ctx->bc.GetLastInstr() == -1);
  5294. asCScriptNode *vnode = node->firstChild;
  5295. ctx->exprNode = vnode;
  5296. if( vnode->nodeType == snVariableAccess )
  5297. {
  5298. // Determine the scope resolution of the variable
  5299. asCString scope = GetScopeFromNode(vnode);
  5300. // Determine the name of the variable
  5301. vnode = vnode->lastChild;
  5302. asASSERT(vnode->nodeType == snIdentifier );
  5303. asCString name(&script->code[vnode->tokenPos], vnode->tokenLength);
  5304. return CompileVariableAccess(name, scope, ctx, node);
  5305. }
  5306. else if( vnode->nodeType == snConstant )
  5307. {
  5308. if( vnode->tokenType == ttIntConstant )
  5309. {
  5310. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5311. asQWORD val = asStringScanUInt64(value.AddressOf(), 10, 0);
  5312. // Do we need 64 bits?
  5313. if( val>>32 )
  5314. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  5315. else
  5316. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  5317. }
  5318. else if( vnode->tokenType == ttBitsConstant )
  5319. {
  5320. asCString value(&script->code[vnode->tokenPos+2], vnode->tokenLength-2);
  5321. // TODO: Check for overflow
  5322. asQWORD val = asStringScanUInt64(value.AddressOf(), 16, 0);
  5323. // Do we need 64 bits?
  5324. if( val>>32 )
  5325. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  5326. else
  5327. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  5328. }
  5329. else if( vnode->tokenType == ttFloatConstant )
  5330. {
  5331. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5332. // TODO: Check for overflow
  5333. size_t numScanned;
  5334. float v = float(asStringScanDouble(value.AddressOf(), &numScanned));
  5335. ctx->type.SetConstantF(asCDataType::CreatePrimitive(ttFloat, true), v);
  5336. #ifndef AS_USE_DOUBLE_AS_FLOAT
  5337. // Don't check this if we have double as float, because then the whole token would be scanned (i.e. no f suffix)
  5338. asASSERT(numScanned == vnode->tokenLength - 1);
  5339. #endif
  5340. }
  5341. else if( vnode->tokenType == ttDoubleConstant )
  5342. {
  5343. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5344. // TODO: Check for overflow
  5345. size_t numScanned;
  5346. double v = asStringScanDouble(value.AddressOf(), &numScanned);
  5347. ctx->type.SetConstantD(asCDataType::CreatePrimitive(ttDouble, true), v);
  5348. asASSERT(numScanned == vnode->tokenLength);
  5349. }
  5350. else if( vnode->tokenType == ttTrue ||
  5351. vnode->tokenType == ttFalse )
  5352. {
  5353. #if AS_SIZEOF_BOOL == 1
  5354. ctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  5355. #else
  5356. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  5357. #endif
  5358. }
  5359. else if( vnode->tokenType == ttStringConstant ||
  5360. vnode->tokenType == ttMultilineStringConstant ||
  5361. vnode->tokenType == ttHeredocStringConstant )
  5362. {
  5363. asCString str;
  5364. asCScriptNode *snode = vnode->firstChild;
  5365. if( script->code[snode->tokenPos] == '\'' && engine->ep.useCharacterLiterals )
  5366. {
  5367. // Treat the single quoted string as a single character literal
  5368. str.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5369. asDWORD val = 0;
  5370. if( str.GetLength() && (unsigned char)str[0] > 127 && engine->ep.scanner == 1 )
  5371. {
  5372. // This is the start of a UTF8 encoded character. We need to decode it
  5373. val = asStringDecodeUTF8(str.AddressOf(), 0);
  5374. if( val == (asDWORD)-1 )
  5375. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  5376. }
  5377. else
  5378. {
  5379. val = ProcessStringConstant(str, snode);
  5380. if( val == (asDWORD)-1 )
  5381. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  5382. }
  5383. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), val);
  5384. }
  5385. else
  5386. {
  5387. // Process the string constants
  5388. while( snode )
  5389. {
  5390. asCString cat;
  5391. if( snode->tokenType == ttStringConstant )
  5392. {
  5393. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5394. ProcessStringConstant(cat, snode);
  5395. }
  5396. else if( snode->tokenType == ttMultilineStringConstant )
  5397. {
  5398. if( !engine->ep.allowMultilineStrings )
  5399. Error(TXT_MULTILINE_STRINGS_NOT_ALLOWED, snode);
  5400. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5401. ProcessStringConstant(cat, snode);
  5402. }
  5403. else if( snode->tokenType == ttHeredocStringConstant )
  5404. {
  5405. cat.Assign(&script->code[snode->tokenPos+3], snode->tokenLength-6);
  5406. ProcessHeredocStringConstant(cat, snode);
  5407. }
  5408. str += cat;
  5409. snode = snode->next;
  5410. }
  5411. // Call the string factory function to create a string object
  5412. asCScriptFunction *descr = engine->stringFactory;
  5413. if( descr == 0 )
  5414. {
  5415. // Error
  5416. Error(TXT_STRINGS_NOT_RECOGNIZED, vnode);
  5417. // Give dummy value
  5418. ctx->type.SetDummy();
  5419. return -1;
  5420. }
  5421. else
  5422. {
  5423. // Register the constant string with the engine
  5424. int id = engine->AddConstantString(str.AddressOf(), str.GetLength());
  5425. ctx->bc.InstrWORD(asBC_STR, (asWORD)id);
  5426. PerformFunctionCall(descr->id, ctx);
  5427. }
  5428. }
  5429. }
  5430. else if( vnode->tokenType == ttNull )
  5431. {
  5432. #ifndef AS_64BIT_PTR
  5433. ctx->bc.InstrDWORD(asBC_PshC4, 0);
  5434. #else
  5435. ctx->bc.InstrQWORD(asBC_PshC8, 0);
  5436. #endif
  5437. ctx->type.SetNullConstant();
  5438. }
  5439. else
  5440. asASSERT(false);
  5441. }
  5442. else if( vnode->nodeType == snFunctionCall )
  5443. {
  5444. bool found = false;
  5445. // Determine the scope resolution
  5446. asCString scope = GetScopeFromNode(vnode);
  5447. if( outFunc && outFunc->objectType && scope != "::" )
  5448. {
  5449. // TODO: funcdef: There may be a local variable of a function type with the same name
  5450. // Check if a class method is being called
  5451. asCScriptNode *nm = vnode->lastChild->prev;
  5452. asCString name;
  5453. name.Assign(&script->code[nm->tokenPos], nm->tokenLength);
  5454. asCArray<int> funcs;
  5455. // If we're compiling a constructor and the name of the function called
  5456. // is 'super' then the base class' constructor is being called.
  5457. // super cannot be called from another scope, i.e. must not be prefixed
  5458. if( m_isConstructor && name == SUPER_TOKEN && nm->prev == 0 )
  5459. {
  5460. // Actually it is the base class' constructor that is being called,
  5461. // but as we won't use the actual function ids here we can take the
  5462. // object's own constructors and avoid the need to check if the
  5463. // object actually derives from any other class
  5464. funcs = outFunc->objectType->beh.constructors;
  5465. // Must not allow calling constructors multiple times
  5466. if( continueLabels.GetLength() > 0 )
  5467. {
  5468. // If a continue label is set we are in a loop
  5469. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_LOOPS, vnode);
  5470. }
  5471. else if( breakLabels.GetLength() > 0 )
  5472. {
  5473. // TODO: inheritance: Should eventually allow constructors in switch statements
  5474. // If a break label is set we are either in a loop or a switch statements
  5475. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_SWITCH, vnode);
  5476. }
  5477. else if( m_isConstructorCalled )
  5478. {
  5479. Error(TXT_CANNOT_CALL_CONSTRUCTOR_TWICE, vnode);
  5480. }
  5481. m_isConstructorCalled = true;
  5482. }
  5483. else
  5484. builder->GetObjectMethodDescriptions(name.AddressOf(), outFunc->objectType, funcs, false);
  5485. if( funcs.GetLength() )
  5486. {
  5487. asCDataType dt = asCDataType::CreateObject(outFunc->objectType, false);
  5488. // The object pointer is located at stack position 0
  5489. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5490. ctx->type.SetVariable(dt, 0, false);
  5491. ctx->type.dataType.MakeReference(true);
  5492. // TODO: optimize: This adds a CHKREF. Is that really necessary?
  5493. Dereference(ctx, true);
  5494. CompileFunctionCall(vnode, ctx, outFunc->objectType, false, scope);
  5495. found = true;
  5496. }
  5497. }
  5498. if( !found )
  5499. CompileFunctionCall(vnode, ctx, 0, false, scope);
  5500. }
  5501. else if( vnode->nodeType == snConstructCall )
  5502. {
  5503. CompileConstructCall(vnode, ctx);
  5504. }
  5505. else if( vnode->nodeType == snAssignment )
  5506. {
  5507. asSExprContext e(engine);
  5508. int r = CompileAssignment(vnode, &e);
  5509. if( r < 0 )
  5510. {
  5511. ctx->type.SetDummy();
  5512. return r;
  5513. }
  5514. MergeExprBytecodeAndType(ctx, &e);
  5515. }
  5516. else if( vnode->nodeType == snCast )
  5517. {
  5518. // Implement the cast operator
  5519. CompileConversion(vnode, ctx);
  5520. }
  5521. else
  5522. asASSERT(false);
  5523. return 0;
  5524. }
  5525. asCString asCCompiler::GetScopeFromNode(asCScriptNode *node)
  5526. {
  5527. asCString scope;
  5528. asCScriptNode *sn = node->firstChild;
  5529. if( sn->tokenType == ttScope )
  5530. {
  5531. // Global scope
  5532. scope = "::";
  5533. sn = sn->next;
  5534. }
  5535. else if( sn->next && sn->next->tokenType == ttScope )
  5536. {
  5537. scope.Assign(&script->code[sn->tokenPos], sn->tokenLength);
  5538. sn = sn->next->next;
  5539. }
  5540. if( scope != "" )
  5541. {
  5542. // We don't support multiple levels of scope yet
  5543. if( sn->next && sn->next->tokenType == ttScope )
  5544. {
  5545. Error(TXT_INVALID_SCOPE, sn->next);
  5546. }
  5547. }
  5548. return scope;
  5549. }
  5550. asUINT asCCompiler::ProcessStringConstant(asCString &cstr, asCScriptNode *node, bool processEscapeSequences)
  5551. {
  5552. int charLiteral = -1;
  5553. // Process escape sequences
  5554. asCArray<char> str((int)cstr.GetLength());
  5555. for( asUINT n = 0; n < cstr.GetLength(); n++ )
  5556. {
  5557. #ifdef AS_DOUBLEBYTE_CHARSET
  5558. // Double-byte charset is only allowed for ASCII and not UTF16 encoded strings
  5559. if( (cstr[n] & 0x80) && engine->ep.scanner == 0 && engine->ep.stringEncoding != 1 )
  5560. {
  5561. // This is the lead character of a double byte character
  5562. // include the trail character without checking it's value.
  5563. str.PushLast(cstr[n]);
  5564. n++;
  5565. str.PushLast(cstr[n]);
  5566. continue;
  5567. }
  5568. #endif
  5569. asUINT val;
  5570. if( processEscapeSequences && cstr[n] == '\\' )
  5571. {
  5572. ++n;
  5573. if( n == cstr.GetLength() )
  5574. {
  5575. if( charLiteral == -1 ) charLiteral = 0;
  5576. return charLiteral;
  5577. }
  5578. // TODO: Consider deprecating use of hexadecimal escape sequences,
  5579. // as they do not guarantee proper unicode sequences
  5580. if( cstr[n] == 'x' || cstr[n] == 'X' )
  5581. {
  5582. ++n;
  5583. if( n == cstr.GetLength() ) break;
  5584. val = 0;
  5585. int c = engine->ep.stringEncoding == 1 ? 4 : 2;
  5586. for( ; c > 0 && n < cstr.GetLength(); c--, n++ )
  5587. {
  5588. if( cstr[n] >= '0' && cstr[n] <= '9' )
  5589. val = val*16 + cstr[n] - '0';
  5590. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  5591. val = val*16 + cstr[n] - 'a' + 10;
  5592. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  5593. val = val*16 + cstr[n] - 'A' + 10;
  5594. else
  5595. break;
  5596. }
  5597. // Rewind one, since the loop will increment it again
  5598. n--;
  5599. // Hexadecimal escape sequences produce exact value, even if it is not proper unicode chars
  5600. if( engine->ep.stringEncoding == 0 )
  5601. {
  5602. str.PushLast((asBYTE)val);
  5603. }
  5604. else
  5605. {
  5606. #ifndef AS_BIG_ENDIAN
  5607. str.PushLast((asBYTE)val);
  5608. str.PushLast((asBYTE)(val>>8));
  5609. #else
  5610. str.PushLast((asBYTE)(val>>8));
  5611. str.PushLast((asBYTE)val);
  5612. #endif
  5613. }
  5614. if( charLiteral == -1 ) charLiteral = val;
  5615. continue;
  5616. }
  5617. else if( cstr[n] == 'u' || cstr[n] == 'U' )
  5618. {
  5619. // \u expects 4 hex digits
  5620. // \U expects 8 hex digits
  5621. bool expect2 = cstr[n] == 'u';
  5622. int c = expect2 ? 4 : 8;
  5623. val = 0;
  5624. for( ; c > 0; c-- )
  5625. {
  5626. ++n;
  5627. if( n == cstr.GetLength() ) break;
  5628. if( cstr[n] >= '0' && cstr[n] <= '9' )
  5629. val = val*16 + cstr[n] - '0';
  5630. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  5631. val = val*16 + cstr[n] - 'a' + 10;
  5632. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  5633. val = val*16 + cstr[n] - 'A' + 10;
  5634. else
  5635. break;
  5636. }
  5637. if( c != 0 )
  5638. {
  5639. // Give warning about invalid code point
  5640. // TODO: Need code position for warning
  5641. asCString msg;
  5642. msg.Format(TXT_INVALID_UNICODE_FORMAT_EXPECTED_d, expect2 ? 4 : 8);
  5643. Warning(msg.AddressOf(), node);
  5644. continue;
  5645. }
  5646. }
  5647. else
  5648. {
  5649. if( cstr[n] == '"' )
  5650. val = '"';
  5651. else if( cstr[n] == '\'' )
  5652. val = '\'';
  5653. else if( cstr[n] == 'n' )
  5654. val = '\n';
  5655. else if( cstr[n] == 'r' )
  5656. val = '\r';
  5657. else if( cstr[n] == 't' )
  5658. val = '\t';
  5659. else if( cstr[n] == '0' )
  5660. val = '\0';
  5661. else if( cstr[n] == '\\' )
  5662. val = '\\';
  5663. else
  5664. {
  5665. // Invalid escape sequence
  5666. Warning(TXT_INVALID_ESCAPE_SEQUENCE, node);
  5667. continue;
  5668. }
  5669. }
  5670. }
  5671. else
  5672. {
  5673. if( engine->ep.scanner == 1 && (cstr[n] & 0x80) )
  5674. {
  5675. unsigned int len;
  5676. val = asStringDecodeUTF8(&cstr[n], &len);
  5677. if( val == 0xFFFFFFFF )
  5678. {
  5679. // Incorrect UTF8 encoding. Use only the first byte
  5680. // TODO: Need code position for warning
  5681. Warning(TXT_INVALID_UNICODE_SEQUENCE_IN_SRC, node);
  5682. val = (unsigned char)cstr[n];
  5683. }
  5684. else
  5685. n += len-1;
  5686. }
  5687. else
  5688. val = (unsigned char)cstr[n];
  5689. }
  5690. // Add the character to the final string
  5691. char encodedValue[5];
  5692. int len;
  5693. if( engine->ep.scanner == 1 && engine->ep.stringEncoding == 0 )
  5694. {
  5695. // Convert to UTF8 encoded
  5696. len = asStringEncodeUTF8(val, encodedValue);
  5697. }
  5698. else if( engine->ep.stringEncoding == 1 )
  5699. {
  5700. // Convert to 16bit wide character string (even if the script is scanned as ASCII)
  5701. len = asStringEncodeUTF16(val, encodedValue);
  5702. }
  5703. else
  5704. {
  5705. // Do not convert ASCII characters
  5706. encodedValue[0] = (asBYTE)val;
  5707. len = 1;
  5708. }
  5709. if( len < 0 )
  5710. {
  5711. // Give warning about invalid code point
  5712. // TODO: Need code position for warning
  5713. Warning(TXT_INVALID_UNICODE_VALUE, node);
  5714. }
  5715. else
  5716. {
  5717. // Add the encoded value to the final string
  5718. str.Concatenate(encodedValue, len);
  5719. if( charLiteral == -1 ) charLiteral = val;
  5720. }
  5721. }
  5722. cstr.Assign(str.AddressOf(), str.GetLength());
  5723. return charLiteral;
  5724. }
  5725. void asCCompiler::ProcessHeredocStringConstant(asCString &str, asCScriptNode *node)
  5726. {
  5727. // Remove first line if it only contains whitespace
  5728. int start;
  5729. for( start = 0; start < (int)str.GetLength(); start++ )
  5730. {
  5731. if( str[start] == '\n' )
  5732. {
  5733. // Remove the linebreak as well
  5734. start++;
  5735. break;
  5736. }
  5737. if( str[start] != ' ' &&
  5738. str[start] != '\t' &&
  5739. str[start] != '\r' )
  5740. {
  5741. // Don't remove anything
  5742. start = 0;
  5743. break;
  5744. }
  5745. }
  5746. // Remove last line break and the line after that if it only contains whitespaces
  5747. int end;
  5748. for( end = (int)str.GetLength() - 1; end >= 0; end-- )
  5749. {
  5750. if( str[end] == '\n' )
  5751. break;
  5752. if( str[end] != ' ' &&
  5753. str[end] != '\t' &&
  5754. str[end] != '\r' )
  5755. {
  5756. // Don't remove anything
  5757. end = (int)str.GetLength();
  5758. break;
  5759. }
  5760. }
  5761. if( end < 0 ) end = 0;
  5762. asCString tmp;
  5763. if( end > start )
  5764. tmp.Assign(&str[start], end-start);
  5765. ProcessStringConstant(tmp, node, false);
  5766. str = tmp;
  5767. }
  5768. void asCCompiler::CompileConversion(asCScriptNode *node, asSExprContext *ctx)
  5769. {
  5770. asSExprContext expr(engine);
  5771. asCDataType to;
  5772. bool anyErrors = false;
  5773. EImplicitConv convType;
  5774. if( node->nodeType == snConstructCall )
  5775. {
  5776. convType = asIC_EXPLICIT_VAL_CAST;
  5777. // Verify that there is only one argument
  5778. if( node->lastChild->firstChild == 0 ||
  5779. node->lastChild->firstChild != node->lastChild->lastChild )
  5780. {
  5781. Error(TXT_ONLY_ONE_ARGUMENT_IN_CAST, node->lastChild);
  5782. expr.type.SetDummy();
  5783. anyErrors = true;
  5784. }
  5785. else
  5786. {
  5787. // Compile the expression
  5788. int r = CompileAssignment(node->lastChild->firstChild, &expr);
  5789. if( r < 0 )
  5790. anyErrors = true;
  5791. }
  5792. // Determine the requested type
  5793. to = builder->CreateDataTypeFromNode(node->firstChild, script);
  5794. to.MakeReadOnly(true); // Default to const
  5795. asASSERT(to.IsPrimitive());
  5796. }
  5797. else
  5798. {
  5799. convType = asIC_EXPLICIT_REF_CAST;
  5800. // Compile the expression
  5801. int r = CompileAssignment(node->lastChild, &expr);
  5802. if( r < 0 )
  5803. anyErrors = true;
  5804. // Determine the requested type
  5805. to = builder->CreateDataTypeFromNode(node->firstChild, script);
  5806. to = builder->ModifyDataTypeFromNode(to, node->firstChild->next, script, 0, 0);
  5807. // If the type support object handles, then use it
  5808. if( to.SupportHandles() )
  5809. {
  5810. to.MakeHandle(true);
  5811. }
  5812. else if( !to.IsObjectHandle() )
  5813. {
  5814. // The cast<type> operator can only be used for reference casts
  5815. Error(TXT_ILLEGAL_TARGET_TYPE_FOR_REF_CAST, node->firstChild);
  5816. anyErrors = true;
  5817. }
  5818. }
  5819. if( anyErrors )
  5820. {
  5821. // Assume that the error can be fixed and allow the compilation to continue
  5822. ctx->type.SetConstantDW(to, 0);
  5823. return;
  5824. }
  5825. ProcessPropertyGetAccessor(&expr, node);
  5826. // We don't want a reference
  5827. if( expr.type.dataType.IsReference() )
  5828. {
  5829. if( expr.type.dataType.IsObject() )
  5830. {
  5831. // ASHANDLE is actually a value type, even though it looks like a handle
  5832. // For this reason we shouldn't dereference it, unless it is on the heap
  5833. if( !(expr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) ||
  5834. (expr.type.isVariable && IsVariableOnHeap(expr.type.stackOffset)) )
  5835. Dereference(&expr, true);
  5836. }
  5837. else
  5838. ConvertToVariable(&expr);
  5839. }
  5840. ImplicitConversion(&expr, to, node, convType);
  5841. IsVariableInitialized(&expr.type, node);
  5842. // If no type conversion is really tried ignore it
  5843. if( to == expr.type.dataType )
  5844. {
  5845. // This will keep information about constant type
  5846. MergeExprBytecode(ctx, &expr);
  5847. ctx->type = expr.type;
  5848. return;
  5849. }
  5850. if( to.IsEqualExceptConst(expr.type.dataType) && to.IsPrimitive() )
  5851. {
  5852. MergeExprBytecode(ctx, &expr);
  5853. ctx->type = expr.type;
  5854. ctx->type.dataType.MakeReadOnly(true);
  5855. return;
  5856. }
  5857. // The implicit conversion already does most of the conversions permitted,
  5858. // here we'll only treat those conversions that require an explicit cast.
  5859. bool conversionOK = false;
  5860. if( !expr.type.isConstant )
  5861. {
  5862. if( !expr.type.dataType.IsObject() )
  5863. ConvertToTempVariable(&expr);
  5864. if( to.IsObjectHandle() &&
  5865. expr.type.dataType.IsObjectHandle() &&
  5866. !(!to.IsHandleToConst() && expr.type.dataType.IsHandleToConst()) )
  5867. {
  5868. conversionOK = CompileRefCast(&expr, to, true, node);
  5869. MergeExprBytecode(ctx, &expr);
  5870. ctx->type = expr.type;
  5871. }
  5872. }
  5873. if( conversionOK )
  5874. return;
  5875. // Conversion not available
  5876. ctx->type.SetDummy();
  5877. asCString strTo, strFrom;
  5878. strTo = to.Format();
  5879. strFrom = expr.type.dataType.Format();
  5880. asCString msg;
  5881. msg.Format(TXT_NO_CONVERSION_s_TO_s, strFrom.AddressOf(), strTo.AddressOf());
  5882. Error(msg.AddressOf(), node);
  5883. }
  5884. void asCCompiler::AfterFunctionCall(int funcID, asCArray<asSExprContext*> &args, asSExprContext *ctx, bool deferAll)
  5885. {
  5886. asCScriptFunction *descr = builder->GetFunctionDescription(funcID);
  5887. // Parameters that are sent by reference should be assigned
  5888. // to the evaluated expression if it is an lvalue
  5889. // Evaluate the arguments from last to first
  5890. int n = (int)descr->parameterTypes.GetLength() - 1;
  5891. for( ; n >= 0; n-- )
  5892. {
  5893. if( (descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] & asTM_OUTREF)) ||
  5894. (descr->parameterTypes[n].IsObject() && deferAll) )
  5895. {
  5896. asASSERT( !(descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] == asTM_OUTREF)) || args[n]->origExpr );
  5897. // For &inout, only store the argument if it is for a temporary variable
  5898. if( engine->ep.allowUnsafeReferences ||
  5899. descr->inOutFlags[n] != asTM_INOUTREF || args[n]->type.isTemporary )
  5900. {
  5901. // Store the argument for later processing
  5902. asSDeferredParam outParam;
  5903. outParam.argNode = args[n]->exprNode;
  5904. outParam.argType = args[n]->type;
  5905. outParam.argInOutFlags = descr->inOutFlags[n];
  5906. outParam.origExpr = args[n]->origExpr;
  5907. ctx->deferredParams.PushLast(outParam);
  5908. }
  5909. }
  5910. else
  5911. {
  5912. // Release the temporary variable now
  5913. ReleaseTemporaryVariable(args[n]->type, &ctx->bc);
  5914. }
  5915. // Move the argument's deferred expressions over to the final expression
  5916. for( asUINT m = 0; m < args[n]->deferredParams.GetLength(); m++ )
  5917. {
  5918. ctx->deferredParams.PushLast(args[n]->deferredParams[m]);
  5919. args[n]->deferredParams[m].origExpr = 0;
  5920. }
  5921. args[n]->deferredParams.SetLength(0);
  5922. }
  5923. }
  5924. void asCCompiler::ProcessDeferredParams(asSExprContext *ctx)
  5925. {
  5926. if( isProcessingDeferredParams ) return;
  5927. isProcessingDeferredParams = true;
  5928. for( asUINT n = 0; n < ctx->deferredParams.GetLength(); n++ )
  5929. {
  5930. asSDeferredParam outParam = ctx->deferredParams[n];
  5931. if( outParam.argInOutFlags < asTM_OUTREF ) // &in, or not reference
  5932. {
  5933. // Just release the variable
  5934. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  5935. }
  5936. else if( outParam.argInOutFlags == asTM_OUTREF )
  5937. {
  5938. asSExprContext *expr = outParam.origExpr;
  5939. outParam.origExpr = 0;
  5940. if( outParam.argType.dataType.IsObjectHandle() )
  5941. {
  5942. // Implicitly convert the value to a handle
  5943. if( expr->type.dataType.IsObjectHandle() )
  5944. expr->type.isExplicitHandle = true;
  5945. }
  5946. // Verify that the expression result in a lvalue, or a property accessor
  5947. if( IsLValue(expr->type) || expr->property_get || expr->property_set )
  5948. {
  5949. asSExprContext rctx(engine);
  5950. rctx.type = outParam.argType;
  5951. if( rctx.type.dataType.IsPrimitive() )
  5952. rctx.type.dataType.MakeReference(false);
  5953. else
  5954. {
  5955. rctx.bc.InstrSHORT(asBC_PSF, outParam.argType.stackOffset);
  5956. rctx.type.dataType.MakeReference(IsVariableOnHeap(outParam.argType.stackOffset));
  5957. if( expr->type.isExplicitHandle )
  5958. rctx.type.isExplicitHandle = true;
  5959. }
  5960. asSExprContext o(engine);
  5961. DoAssignment(&o, expr, &rctx, outParam.argNode, outParam.argNode, ttAssignment, outParam.argNode);
  5962. if( !o.type.dataType.IsPrimitive() ) o.bc.Pop(AS_PTR_SIZE);
  5963. MergeExprBytecode(ctx, &o);
  5964. }
  5965. else
  5966. {
  5967. // We must still evaluate the expression
  5968. MergeExprBytecode(ctx, expr);
  5969. if( !expr->type.isConstant || expr->type.IsNullConstant() )
  5970. ctx->bc.Pop(expr->type.dataType.GetSizeOnStackDWords());
  5971. // Give a warning, except if the argument is null which indicate the argument is really to be ignored
  5972. if( !expr->type.IsNullConstant() )
  5973. Warning(TXT_ARG_NOT_LVALUE, outParam.argNode);
  5974. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  5975. }
  5976. ReleaseTemporaryVariable(expr->type, &ctx->bc);
  5977. // Delete the original expression context
  5978. asDELETE(expr,asSExprContext);
  5979. }
  5980. else // &inout
  5981. {
  5982. if( outParam.argType.isTemporary )
  5983. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  5984. else if( !outParam.argType.isVariable )
  5985. {
  5986. if( outParam.argType.dataType.IsObject() &&
  5987. outParam.argType.dataType.GetBehaviour()->addref &&
  5988. outParam.argType.dataType.GetBehaviour()->release )
  5989. {
  5990. // Release the object handle that was taken to guarantee the reference
  5991. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  5992. }
  5993. }
  5994. }
  5995. }
  5996. ctx->deferredParams.SetLength(0);
  5997. isProcessingDeferredParams = false;
  5998. }
  5999. void asCCompiler::CompileConstructCall(asCScriptNode *node, asSExprContext *ctx)
  6000. {
  6001. // The first node is a datatype node
  6002. asCString name;
  6003. asCTypeInfo tempObj;
  6004. bool onHeap = true;
  6005. asCArray<int> funcs;
  6006. // It is possible that the name is really a constructor
  6007. asCDataType dt;
  6008. dt = builder->CreateDataTypeFromNode(node->firstChild, script);
  6009. if( dt.IsPrimitive() )
  6010. {
  6011. // This is a cast to a primitive type
  6012. CompileConversion(node, ctx);
  6013. return;
  6014. }
  6015. // Compile the arguments
  6016. asCArray<asSExprContext *> args;
  6017. asCArray<asCTypeInfo> temporaryVariables;
  6018. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6019. {
  6020. // Check for a value cast behaviour
  6021. if( args.GetLength() == 1 && args[0]->type.dataType.GetObjectType() )
  6022. {
  6023. asSExprContext conv(engine);
  6024. conv.type = args[0]->type;
  6025. ImplicitConversion(&conv, dt, node->lastChild, asIC_EXPLICIT_VAL_CAST, false);
  6026. if( conv.type.dataType.IsEqualExceptRef(dt) )
  6027. {
  6028. ImplicitConversion(args[0], dt, node->lastChild, asIC_EXPLICIT_VAL_CAST);
  6029. ctx->bc.AddCode(&args[0]->bc);
  6030. ctx->type = args[0]->type;
  6031. asDELETE(args[0],asSExprContext);
  6032. return;
  6033. }
  6034. }
  6035. // Check for possible constructor/factory
  6036. name = dt.Format();
  6037. asSTypeBehaviour *beh = dt.GetBehaviour();
  6038. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6039. {
  6040. funcs = beh->constructors;
  6041. // Value types and script types are allocated through the constructor
  6042. tempObj.dataType = dt;
  6043. tempObj.stackOffset = (short)AllocateVariable(dt, true);
  6044. tempObj.dataType.MakeReference(true);
  6045. tempObj.isTemporary = true;
  6046. tempObj.isVariable = true;
  6047. onHeap = IsVariableOnHeap(tempObj.stackOffset);
  6048. // Push the address of the object on the stack
  6049. if( onHeap )
  6050. ctx->bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  6051. }
  6052. else
  6053. {
  6054. funcs = beh->factories;
  6055. }
  6056. // Special case: Allow calling func(void) with a void expression.
  6057. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6058. {
  6059. // Evaluate the expression before the function call
  6060. MergeExprBytecode(ctx, args[0]);
  6061. asDELETE(args[0],asSExprContext);
  6062. args.SetLength(0);
  6063. }
  6064. // Special case: If this is an object constructor and there are no arguments use the default constructor.
  6065. // If none has been registered, just allocate the variable and push it on the stack.
  6066. if( args.GetLength() == 0 )
  6067. {
  6068. asSTypeBehaviour *beh = tempObj.dataType.GetBehaviour();
  6069. if( beh && beh->construct == 0 && !(dt.GetObjectType()->flags & asOBJ_REF) )
  6070. {
  6071. // Call the default constructor
  6072. ctx->type = tempObj;
  6073. if( onHeap )
  6074. {
  6075. asASSERT(ctx->bc.GetLastInstr() == asBC_VAR);
  6076. ctx->bc.RemoveLastInstr();
  6077. }
  6078. CallDefaultConstructor(tempObj.dataType, tempObj.stackOffset, IsVariableOnHeap(tempObj.stackOffset), &ctx->bc, node);
  6079. // Push the reference on the stack
  6080. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6081. return;
  6082. }
  6083. }
  6084. MatchFunctions(funcs, args, node, name.AddressOf(), NULL, false);
  6085. if( funcs.GetLength() != 1 )
  6086. {
  6087. // The error was reported by MatchFunctions()
  6088. // Dummy value
  6089. ctx->type.SetDummy();
  6090. }
  6091. else
  6092. {
  6093. int r = asSUCCESS;
  6094. // Add the default values for arguments not explicitly supplied
  6095. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  6096. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  6097. r = CompileDefaultArgs(node, args, func);
  6098. if( r == asSUCCESS )
  6099. {
  6100. asCByteCode objBC(engine);
  6101. PrepareFunctionCall(funcs[0], &ctx->bc, args);
  6102. MoveArgsToStack(funcs[0], &ctx->bc, args, false);
  6103. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6104. {
  6105. // If the object is allocated on the stack, then call the constructor as a normal function
  6106. if( onHeap )
  6107. {
  6108. int offset = 0;
  6109. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  6110. for( asUINT n = 0; n < args.GetLength(); n++ )
  6111. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  6112. ctx->bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  6113. }
  6114. else
  6115. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6116. PerformFunctionCall(funcs[0], ctx, onHeap, &args, tempObj.dataType.GetObjectType());
  6117. // The constructor doesn't return anything,
  6118. // so we have to manually inform the type of
  6119. // the return value
  6120. ctx->type = tempObj;
  6121. if( !onHeap )
  6122. ctx->type.dataType.MakeReference(false);
  6123. // Push the address of the object on the stack again
  6124. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6125. }
  6126. else
  6127. {
  6128. // Call the factory to create the reference type
  6129. PerformFunctionCall(funcs[0], ctx, false, &args);
  6130. }
  6131. }
  6132. }
  6133. }
  6134. else
  6135. {
  6136. // Failed to compile the argument list, set the result to the dummy type
  6137. ctx->type.SetDummy();
  6138. }
  6139. // Cleanup
  6140. for( asUINT n = 0; n < args.GetLength(); n++ )
  6141. if( args[n] )
  6142. {
  6143. asDELETE(args[n],asSExprContext);
  6144. }
  6145. }
  6146. void asCCompiler::CompileFunctionCall(asCScriptNode *node, asSExprContext *ctx, asCObjectType *objectType, bool objIsConst, const asCString &scope)
  6147. {
  6148. asCString name;
  6149. asCTypeInfo tempObj;
  6150. asCArray<int> funcs;
  6151. int r = -1;
  6152. asCScriptNode *nm = node->lastChild->prev;
  6153. name.Assign(&script->code[nm->tokenPos], nm->tokenLength);
  6154. // First check for a local variable of a function type
  6155. // Must not allow function names, nor global variables to be returned in this instance
  6156. asSExprContext funcPtr(engine);
  6157. if( objectType == 0 )
  6158. r = CompileVariableAccess(name, scope, &funcPtr, node, true, true);
  6159. if( r < 0 )
  6160. {
  6161. if( objectType )
  6162. {
  6163. // If we're compiling a constructor and the name of the function is super then
  6164. // the constructor of the base class is being called.
  6165. // super cannot be prefixed with a scope operator
  6166. if( m_isConstructor && name == SUPER_TOKEN && nm->prev == 0 )
  6167. {
  6168. // If the class is not derived from anyone else, calling super should give an error
  6169. if( objectType->derivedFrom )
  6170. funcs = objectType->derivedFrom->beh.constructors;
  6171. }
  6172. else
  6173. builder->GetObjectMethodDescriptions(name.AddressOf(), objectType, funcs, objIsConst, scope);
  6174. // It is still possible that there is a class member of a function type
  6175. if( funcs.GetLength() == 0 )
  6176. CompileVariableAccess(name, scope, &funcPtr, node, true, true, objectType);
  6177. }
  6178. else
  6179. {
  6180. builder->GetFunctionDescriptions(name.AddressOf(), funcs);
  6181. // TODO: funcdef: It is still possible that there is a global variable of a function type
  6182. }
  6183. }
  6184. else if( !funcPtr.type.dataType.GetFuncDef() )
  6185. {
  6186. // The variable is not a function
  6187. asCString msg;
  6188. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  6189. Error(msg.AddressOf(), node);
  6190. return;
  6191. }
  6192. if( funcs.GetLength() == 0 && funcPtr.type.dataType.GetFuncDef() )
  6193. {
  6194. funcs.PushLast(funcPtr.type.dataType.GetFuncDef()->id);
  6195. }
  6196. // Compile the arguments
  6197. asCArray<asSExprContext *> args;
  6198. asCArray<asCTypeInfo> temporaryVariables;
  6199. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6200. {
  6201. // Special case: Allow calling func(void) with a void expression.
  6202. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6203. {
  6204. // Evaluate the expression before the function call
  6205. MergeExprBytecode(ctx, args[0]);
  6206. asDELETE(args[0],asSExprContext);
  6207. args.SetLength(0);
  6208. }
  6209. MatchFunctions(funcs, args, node, name.AddressOf(), objectType, objIsConst, false, true, scope);
  6210. if( funcs.GetLength() != 1 )
  6211. {
  6212. // The error was reported by MatchFunctions()
  6213. // Dummy value
  6214. ctx->type.SetDummy();
  6215. }
  6216. else
  6217. {
  6218. int r = asSUCCESS;
  6219. // Add the default values for arguments not explicitly supplied
  6220. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  6221. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  6222. r = CompileDefaultArgs(node, args, func);
  6223. // TODO: funcdef: Do we have to make sure the handle is stored in a temporary variable, or
  6224. // is it enough to make sure it is in a local variable?
  6225. // For function pointer we must guarantee that the function is safe, i.e.
  6226. // by first storing the function pointer in a local variable (if it isn't already in one)
  6227. if( r == asSUCCESS )
  6228. {
  6229. if( (funcs[0] & 0xFFFF0000) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  6230. {
  6231. if( objectType )
  6232. {
  6233. Dereference(ctx, true); // Dereference the object pointer to access the member
  6234. // The actual function should be called as if a global function
  6235. objectType = 0;
  6236. }
  6237. Dereference(&funcPtr, true);
  6238. ConvertToVariable(&funcPtr);
  6239. ctx->bc.AddCode(&funcPtr.bc);
  6240. if( !funcPtr.type.isTemporary )
  6241. ctx->bc.Pop(AS_PTR_SIZE);
  6242. }
  6243. MakeFunctionCall(ctx, funcs[0], objectType, args, node, false, 0, funcPtr.type.stackOffset);
  6244. // If the function pointer was copied to a local variable for the call, then
  6245. // release it again (temporary local variable)
  6246. if( (funcs[0] & 0xFFFF0000) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  6247. {
  6248. ReleaseTemporaryVariable(funcPtr.type, &ctx->bc);
  6249. }
  6250. }
  6251. }
  6252. }
  6253. else
  6254. {
  6255. // Failed to compile the argument list, set the dummy type and continue compilation
  6256. ctx->type.SetDummy();
  6257. }
  6258. // Cleanup
  6259. for( asUINT n = 0; n < args.GetLength(); n++ )
  6260. if( args[n] )
  6261. {
  6262. asDELETE(args[n],asSExprContext);
  6263. }
  6264. }
  6265. int asCCompiler::CompileExpressionPreOp(asCScriptNode *node, asSExprContext *ctx)
  6266. {
  6267. int op = node->tokenType;
  6268. IsVariableInitialized(&ctx->type, node);
  6269. if( op == ttHandle )
  6270. {
  6271. // Verify that the type allow its handle to be taken
  6272. if( ctx->type.isExplicitHandle ||
  6273. !ctx->type.dataType.IsObject() ||
  6274. !((ctx->type.dataType.GetObjectType()->beh.addref && ctx->type.dataType.GetObjectType()->beh.release) || ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  6275. {
  6276. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  6277. return -1;
  6278. }
  6279. // Objects that are not local variables are not references
  6280. if( !ctx->type.dataType.IsReference() && !(ctx->type.dataType.IsObject() && !ctx->type.isVariable) )
  6281. {
  6282. Error(TXT_NOT_VALID_REFERENCE, node);
  6283. return -1;
  6284. }
  6285. // If this is really an object then the handle created is a const handle
  6286. bool makeConst = !ctx->type.dataType.IsObjectHandle();
  6287. // Mark the type as an object handle
  6288. ctx->type.dataType.MakeHandle(true);
  6289. ctx->type.isExplicitHandle = true;
  6290. if( makeConst )
  6291. ctx->type.dataType.MakeReadOnly(true);
  6292. }
  6293. else if( (op == ttMinus || op == ttBitNot || op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  6294. {
  6295. // Look for the appropriate method
  6296. const char *opName = 0;
  6297. switch( op )
  6298. {
  6299. case ttMinus: opName = "opNeg"; break;
  6300. case ttBitNot: opName = "opCom"; break;
  6301. case ttInc: opName = "opPreInc"; break;
  6302. case ttDec: opName = "opPreDec"; break;
  6303. }
  6304. if( opName )
  6305. {
  6306. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  6307. ProcessPropertyGetAccessor(ctx, node);
  6308. // Is it a const value?
  6309. bool isConst = false;
  6310. if( ctx->type.dataType.IsObjectHandle() )
  6311. isConst = ctx->type.dataType.IsHandleToConst();
  6312. else
  6313. isConst = ctx->type.dataType.IsReadOnly();
  6314. // 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
  6315. // Find the correct method
  6316. asCArray<int> funcs;
  6317. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  6318. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  6319. {
  6320. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  6321. if( func->name == opName &&
  6322. func->parameterTypes.GetLength() == 0 &&
  6323. (!isConst || func->isReadOnly) )
  6324. {
  6325. funcs.PushLast(func->id);
  6326. }
  6327. }
  6328. // Did we find the method?
  6329. if( funcs.GetLength() == 1 )
  6330. {
  6331. asCTypeInfo objType = ctx->type;
  6332. asCArray<asSExprContext *> args;
  6333. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  6334. ReleaseTemporaryVariable(objType, &ctx->bc);
  6335. return 0;
  6336. }
  6337. else if( funcs.GetLength() == 0 )
  6338. {
  6339. asCString str;
  6340. str = asCString(opName) + "()";
  6341. if( isConst )
  6342. str += " const";
  6343. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  6344. Error(str.AddressOf(), node);
  6345. ctx->type.SetDummy();
  6346. return -1;
  6347. }
  6348. else if( funcs.GetLength() > 1 )
  6349. {
  6350. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  6351. PrintMatchingFuncs(funcs, node);
  6352. ctx->type.SetDummy();
  6353. return -1;
  6354. }
  6355. }
  6356. }
  6357. else if( op == ttPlus || op == ttMinus )
  6358. {
  6359. ProcessPropertyGetAccessor(ctx, node);
  6360. asCDataType to = ctx->type.dataType;
  6361. // TODO: The case -2147483648 gives an unecessary warning of changed sign for implicit conversion
  6362. if( ctx->type.dataType.IsUnsignedType() || ctx->type.dataType.IsEnumType() )
  6363. {
  6364. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  6365. to = asCDataType::CreatePrimitive(ttInt8, false);
  6366. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  6367. to = asCDataType::CreatePrimitive(ttInt16, false);
  6368. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  6369. to = asCDataType::CreatePrimitive(ttInt, false);
  6370. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  6371. to = asCDataType::CreatePrimitive(ttInt64, false);
  6372. else
  6373. {
  6374. Error(TXT_INVALID_TYPE, node);
  6375. return -1;
  6376. }
  6377. }
  6378. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  6379. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  6380. if( !ctx->type.isConstant )
  6381. {
  6382. ConvertToTempVariable(ctx);
  6383. asASSERT(!ctx->type.isLValue);
  6384. if( op == ttMinus )
  6385. {
  6386. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6387. ctx->bc.InstrSHORT(asBC_NEGi, ctx->type.stackOffset);
  6388. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  6389. ctx->bc.InstrSHORT(asBC_NEGi64, ctx->type.stackOffset);
  6390. else if( ctx->type.dataType.IsFloatType() )
  6391. ctx->bc.InstrSHORT(asBC_NEGf, ctx->type.stackOffset);
  6392. else if( ctx->type.dataType.IsDoubleType() )
  6393. ctx->bc.InstrSHORT(asBC_NEGd, ctx->type.stackOffset);
  6394. else
  6395. {
  6396. Error(TXT_ILLEGAL_OPERATION, node);
  6397. return -1;
  6398. }
  6399. return 0;
  6400. }
  6401. }
  6402. else
  6403. {
  6404. if( op == ttMinus )
  6405. {
  6406. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6407. ctx->type.intValue = -ctx->type.intValue;
  6408. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  6409. ctx->type.qwordValue = -(asINT64)ctx->type.qwordValue;
  6410. else if( ctx->type.dataType.IsFloatType() )
  6411. ctx->type.floatValue = -ctx->type.floatValue;
  6412. else if( ctx->type.dataType.IsDoubleType() )
  6413. ctx->type.doubleValue = -ctx->type.doubleValue;
  6414. else
  6415. {
  6416. Error(TXT_ILLEGAL_OPERATION, node);
  6417. return -1;
  6418. }
  6419. return 0;
  6420. }
  6421. }
  6422. if( op == ttPlus )
  6423. {
  6424. if( !ctx->type.dataType.IsIntegerType() &&
  6425. !ctx->type.dataType.IsFloatType() &&
  6426. !ctx->type.dataType.IsDoubleType() )
  6427. {
  6428. Error(TXT_ILLEGAL_OPERATION, node);
  6429. return -1;
  6430. }
  6431. }
  6432. }
  6433. else if( op == ttNot )
  6434. {
  6435. if( ctx->type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  6436. {
  6437. if( ctx->type.isConstant )
  6438. {
  6439. ctx->type.dwordValue = (ctx->type.dwordValue == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  6440. return 0;
  6441. }
  6442. ProcessPropertyGetAccessor(ctx, node);
  6443. ConvertToTempVariable(ctx);
  6444. asASSERT(!ctx->type.isLValue);
  6445. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  6446. }
  6447. else
  6448. {
  6449. Error(TXT_ILLEGAL_OPERATION, node);
  6450. return -1;
  6451. }
  6452. }
  6453. else if( op == ttBitNot )
  6454. {
  6455. ProcessPropertyGetAccessor(ctx, node);
  6456. asCDataType to = ctx->type.dataType;
  6457. if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType() )
  6458. {
  6459. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  6460. to = asCDataType::CreatePrimitive(ttUInt8, false);
  6461. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  6462. to = asCDataType::CreatePrimitive(ttUInt16, false);
  6463. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  6464. to = asCDataType::CreatePrimitive(ttUInt, false);
  6465. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  6466. to = asCDataType::CreatePrimitive(ttUInt64, false);
  6467. else
  6468. {
  6469. Error(TXT_INVALID_TYPE, node);
  6470. return -1;
  6471. }
  6472. }
  6473. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  6474. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  6475. if( ctx->type.dataType.IsUnsignedType() )
  6476. {
  6477. if( ctx->type.isConstant )
  6478. {
  6479. ctx->type.qwordValue = ~ctx->type.qwordValue;
  6480. return 0;
  6481. }
  6482. ConvertToTempVariable(ctx);
  6483. asASSERT(!ctx->type.isLValue);
  6484. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6485. ctx->bc.InstrSHORT(asBC_BNOT, ctx->type.stackOffset);
  6486. else
  6487. ctx->bc.InstrSHORT(asBC_BNOT64, ctx->type.stackOffset);
  6488. }
  6489. else
  6490. {
  6491. Error(TXT_ILLEGAL_OPERATION, node);
  6492. return -1;
  6493. }
  6494. }
  6495. else if( op == ttInc || op == ttDec )
  6496. {
  6497. // Need a reference to the primitive that will be updated
  6498. // The result of this expression is the same reference as before
  6499. // Make sure the reference isn't a temporary variable
  6500. if( ctx->type.isTemporary )
  6501. {
  6502. Error(TXT_REF_IS_TEMP, node);
  6503. return -1;
  6504. }
  6505. if( ctx->type.dataType.IsReadOnly() )
  6506. {
  6507. Error(TXT_REF_IS_READ_ONLY, node);
  6508. return -1;
  6509. }
  6510. if( ctx->property_get || ctx->property_set )
  6511. {
  6512. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  6513. return -1;
  6514. }
  6515. if( !ctx->type.isLValue )
  6516. {
  6517. Error(TXT_NOT_LVALUE, node);
  6518. return -1;
  6519. }
  6520. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  6521. ConvertToReference(ctx);
  6522. else if( !ctx->type.dataType.IsReference() )
  6523. {
  6524. Error(TXT_NOT_VALID_REFERENCE, node);
  6525. return -1;
  6526. }
  6527. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  6528. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  6529. {
  6530. if( op == ttInc )
  6531. ctx->bc.Instr(asBC_INCi64);
  6532. else
  6533. ctx->bc.Instr(asBC_DECi64);
  6534. }
  6535. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt, false)) ||
  6536. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt, false)) )
  6537. {
  6538. if( op == ttInc )
  6539. ctx->bc.Instr(asBC_INCi);
  6540. else
  6541. ctx->bc.Instr(asBC_DECi);
  6542. }
  6543. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  6544. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  6545. {
  6546. if( op == ttInc )
  6547. ctx->bc.Instr(asBC_INCi16);
  6548. else
  6549. ctx->bc.Instr(asBC_DECi16);
  6550. }
  6551. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  6552. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  6553. {
  6554. if( op == ttInc )
  6555. ctx->bc.Instr(asBC_INCi8);
  6556. else
  6557. ctx->bc.Instr(asBC_DECi8);
  6558. }
  6559. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttFloat, false)) )
  6560. {
  6561. if( op == ttInc )
  6562. ctx->bc.Instr(asBC_INCf);
  6563. else
  6564. ctx->bc.Instr(asBC_DECf);
  6565. }
  6566. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttDouble, false)) )
  6567. {
  6568. if( op == ttInc )
  6569. ctx->bc.Instr(asBC_INCd);
  6570. else
  6571. ctx->bc.Instr(asBC_DECd);
  6572. }
  6573. else
  6574. {
  6575. Error(TXT_ILLEGAL_OPERATION, node);
  6576. return -1;
  6577. }
  6578. }
  6579. else
  6580. {
  6581. // Unknown operator
  6582. asASSERT(false);
  6583. return -1;
  6584. }
  6585. return 0;
  6586. }
  6587. void asCCompiler::ConvertToReference(asSExprContext *ctx)
  6588. {
  6589. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  6590. {
  6591. ctx->bc.InstrSHORT(asBC_LDV, ctx->type.stackOffset);
  6592. ctx->type.dataType.MakeReference(true);
  6593. ctx->type.SetVariable(ctx->type.dataType, ctx->type.stackOffset, ctx->type.isTemporary);
  6594. }
  6595. }
  6596. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asCScriptNode *node, bool isThisAccess)
  6597. {
  6598. return FindPropertyAccessor(name, ctx, 0, node, isThisAccess);
  6599. }
  6600. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node, bool isThisAccess)
  6601. {
  6602. if( engine->ep.propertyAccessorMode == 0 )
  6603. {
  6604. // Property accessors have been disabled by the application
  6605. return 0;
  6606. }
  6607. int getId = 0, setId = 0;
  6608. asCString getName = "get_" + name;
  6609. asCString setName = "set_" + name;
  6610. asCArray<int> multipleGetFuncs, multipleSetFuncs;
  6611. if( ctx->type.dataType.IsObject() )
  6612. {
  6613. // Check if the object has any methods with the property name prefixed by get_ or set_
  6614. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  6615. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  6616. {
  6617. asCScriptFunction *f = engine->scriptFunctions[ot->methods[n]];
  6618. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  6619. if( f->name == getName && (int)f->parameterTypes.GetLength() == (arg?1:0) )
  6620. {
  6621. if( getId == 0 )
  6622. getId = ot->methods[n];
  6623. else
  6624. {
  6625. if( multipleGetFuncs.GetLength() == 0 )
  6626. multipleGetFuncs.PushLast(getId);
  6627. multipleGetFuncs.PushLast(ot->methods[n]);
  6628. }
  6629. }
  6630. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  6631. if( f->name == setName && (int)f->parameterTypes.GetLength() == (arg?2:1) )
  6632. {
  6633. if( setId == 0 )
  6634. setId = ot->methods[n];
  6635. else
  6636. {
  6637. if( multipleSetFuncs.GetLength() == 0 )
  6638. multipleSetFuncs.PushLast(setId);
  6639. multipleSetFuncs.PushLast(ot->methods[n]);
  6640. }
  6641. }
  6642. }
  6643. }
  6644. else
  6645. {
  6646. // Look for appropriate global functions.
  6647. asCArray<int> funcs;
  6648. asUINT n;
  6649. builder->GetFunctionDescriptions(getName.AddressOf(), funcs);
  6650. for( n = 0; n < funcs.GetLength(); n++ )
  6651. {
  6652. asCScriptFunction *f = engine->scriptFunctions[funcs[n]];
  6653. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  6654. if( (int)f->parameterTypes.GetLength() == (arg?1:0) )
  6655. {
  6656. if( getId == 0 )
  6657. getId = funcs[n];
  6658. else
  6659. {
  6660. if( multipleGetFuncs.GetLength() == 0 )
  6661. multipleGetFuncs.PushLast(getId);
  6662. multipleGetFuncs.PushLast(funcs[n]);
  6663. }
  6664. }
  6665. }
  6666. funcs.SetLength(0);
  6667. builder->GetFunctionDescriptions(setName.AddressOf(), funcs);
  6668. for( n = 0; n < funcs.GetLength(); n++ )
  6669. {
  6670. asCScriptFunction *f = engine->scriptFunctions[funcs[n]];
  6671. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  6672. if( (int)f->parameterTypes.GetLength() == (arg?2:1) )
  6673. {
  6674. if( setId == 0 )
  6675. setId = funcs[n];
  6676. else
  6677. {
  6678. if( multipleSetFuncs.GetLength() == 0 )
  6679. multipleSetFuncs.PushLast(getId);
  6680. multipleSetFuncs.PushLast(funcs[n]);
  6681. }
  6682. }
  6683. }
  6684. }
  6685. // Check for multiple matches
  6686. if( multipleGetFuncs.GetLength() > 0 )
  6687. {
  6688. asCString str;
  6689. str.Format(TXT_MULTIPLE_PROP_GET_ACCESSOR_FOR_s, name.AddressOf());
  6690. Error(str.AddressOf(), node);
  6691. PrintMatchingFuncs(multipleGetFuncs, node);
  6692. return -1;
  6693. }
  6694. if( multipleSetFuncs.GetLength() > 0 )
  6695. {
  6696. asCString str;
  6697. str.Format(TXT_MULTIPLE_PROP_SET_ACCESSOR_FOR_s, name.AddressOf());
  6698. Error(str.AddressOf(), node);
  6699. PrintMatchingFuncs(multipleSetFuncs, node);
  6700. return -1;
  6701. }
  6702. // Check for type compatibility between get and set accessor
  6703. if( getId && setId )
  6704. {
  6705. asCScriptFunction *getFunc = engine->scriptFunctions[getId];
  6706. asCScriptFunction *setFunc = engine->scriptFunctions[setId];
  6707. // It is permitted for a getter to return a handle and the setter to take a reference
  6708. int idx = (arg?1:0);
  6709. if( !getFunc->returnType.IsEqualExceptRefAndConst(setFunc->parameterTypes[idx]) &&
  6710. !((getFunc->returnType.IsObjectHandle() && !setFunc->parameterTypes[idx].IsObjectHandle()) &&
  6711. (getFunc->returnType.GetObjectType() == setFunc->parameterTypes[idx].GetObjectType())) )
  6712. {
  6713. asCString str;
  6714. str.Format(TXT_GET_SET_ACCESSOR_TYPE_MISMATCH_FOR_s, name.AddressOf());
  6715. Error(str.AddressOf(), node);
  6716. asCArray<int> funcs;
  6717. funcs.PushLast(getId);
  6718. funcs.PushLast(setId);
  6719. PrintMatchingFuncs(funcs, node);
  6720. return -1;
  6721. }
  6722. }
  6723. // Check if we are within one of the accessors
  6724. int realGetId = getId;
  6725. int realSetId = setId;
  6726. if( outFunc->objectType && isThisAccess )
  6727. {
  6728. // The property accessors would be virtual functions, so we need to find the real implementation
  6729. asCScriptFunction *getFunc = getId ? engine->scriptFunctions[getId] : 0;
  6730. if( getFunc &&
  6731. getFunc->funcType == asFUNC_VIRTUAL &&
  6732. outFunc->objectType->DerivesFrom(getFunc->objectType) )
  6733. realGetId = outFunc->objectType->virtualFunctionTable[getFunc->vfTableIdx]->id;
  6734. asCScriptFunction *setFunc = setId ? engine->scriptFunctions[setId] : 0;
  6735. if( setFunc &&
  6736. setFunc->funcType == asFUNC_VIRTUAL &&
  6737. outFunc->objectType->DerivesFrom(setFunc->objectType) )
  6738. realSetId = outFunc->objectType->virtualFunctionTable[setFunc->vfTableIdx]->id;
  6739. }
  6740. // Avoid recursive call, by not treating this as a property accessor call.
  6741. // This will also allow having the real property with the same name as the accessors.
  6742. if( (isThisAccess || outFunc->objectType == 0) &&
  6743. ((realGetId && realGetId == outFunc->id) ||
  6744. (realSetId && realSetId == outFunc->id)) )
  6745. {
  6746. getId = 0;
  6747. setId = 0;
  6748. }
  6749. // Check if the application has disabled script written property accessors
  6750. if( engine->ep.propertyAccessorMode == 1 )
  6751. {
  6752. if( getId && engine->scriptFunctions[getId]->funcType != asFUNC_SYSTEM )
  6753. getId = 0;
  6754. if( setId && engine->scriptFunctions[setId]->funcType != asFUNC_SYSTEM )
  6755. setId = 0;
  6756. }
  6757. if( getId || setId )
  6758. {
  6759. // Property accessors were found, but we don't know which is to be used yet, so
  6760. // we just prepare the bytecode for the method call, and then store the function ids
  6761. // so that the right one can be used when we get there.
  6762. ctx->property_get = getId;
  6763. ctx->property_set = setId;
  6764. if( ctx->type.dataType.IsObject() )
  6765. {
  6766. // If the object is read-only then we need to remember that
  6767. if( (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) ||
  6768. (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) )
  6769. ctx->property_const = true;
  6770. else
  6771. ctx->property_const = false;
  6772. // If the object is a handle then we need to remember that
  6773. ctx->property_handle = ctx->type.dataType.IsObjectHandle();
  6774. ctx->property_ref = ctx->type.dataType.IsReference();
  6775. }
  6776. // The setter's parameter type is used as the property type,
  6777. // unless only the getter is available
  6778. asCDataType dt;
  6779. if( setId )
  6780. dt = engine->scriptFunctions[setId]->parameterTypes[(arg?1:0)];
  6781. else
  6782. dt = engine->scriptFunctions[getId]->returnType;
  6783. // Just change the type, the context must still maintain information
  6784. // about previous variable offset and the indicator of temporary variable.
  6785. int offset = ctx->type.stackOffset;
  6786. bool isTemp = ctx->type.isTemporary;
  6787. ctx->type.Set(dt);
  6788. ctx->type.stackOffset = (short)offset;
  6789. ctx->type.isTemporary = isTemp;
  6790. ctx->exprNode = node;
  6791. // Store the argument for later use
  6792. if( arg )
  6793. {
  6794. ctx->property_arg = asNEW(asSExprContext)(engine);
  6795. MergeExprBytecodeAndType(ctx->property_arg, arg);
  6796. }
  6797. return 1;
  6798. }
  6799. // No accessor was found
  6800. return 0;
  6801. }
  6802. int asCCompiler::ProcessPropertySetAccessor(asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node)
  6803. {
  6804. // TODO: A lot of this code is similar to ProcessPropertyGetAccessor. Can we unify them?
  6805. if( !ctx->property_set )
  6806. {
  6807. Error(TXT_PROPERTY_HAS_NO_SET_ACCESSOR, node);
  6808. return -1;
  6809. }
  6810. asCTypeInfo objType = ctx->type;
  6811. asCScriptFunction *func = engine->scriptFunctions[ctx->property_set];
  6812. // Make sure the arg match the property
  6813. asCArray<int> funcs;
  6814. funcs.PushLast(ctx->property_set);
  6815. asCArray<asSExprContext *> args;
  6816. if( ctx->property_arg )
  6817. args.PushLast(ctx->property_arg);
  6818. args.PushLast(arg);
  6819. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  6820. if( funcs.GetLength() == 0 )
  6821. {
  6822. // MatchFunctions already reported the error
  6823. if( ctx->property_arg )
  6824. {
  6825. asDELETE(ctx->property_arg, asSExprContext);
  6826. ctx->property_arg = 0;
  6827. }
  6828. return -1;
  6829. }
  6830. if( func->objectType )
  6831. {
  6832. // Setup the context with the original type so the method call gets built correctly
  6833. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  6834. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  6835. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  6836. // Don't allow the call if the object is read-only and the property accessor is not const
  6837. if( ctx->property_const && !func->isReadOnly )
  6838. {
  6839. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  6840. asCArray<int> funcs;
  6841. funcs.PushLast(ctx->property_set);
  6842. PrintMatchingFuncs(funcs, node);
  6843. }
  6844. }
  6845. // Call the accessor
  6846. MakeFunctionCall(ctx, ctx->property_set, func->objectType, args, node);
  6847. if( func->objectType )
  6848. {
  6849. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  6850. if( objType.isTemporary &&
  6851. ctx->type.dataType.IsReference() &&
  6852. !ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  6853. {
  6854. // Remember the original object's variable, so that it can be released
  6855. // later on when the reference to its member goes out of scope
  6856. ctx->type.isTemporary = true;
  6857. ctx->type.stackOffset = objType.stackOffset;
  6858. }
  6859. else
  6860. {
  6861. // As the method didn't return a reference to a member
  6862. // we can safely release the original object now
  6863. ReleaseTemporaryVariable(objType, &ctx->bc);
  6864. }
  6865. }
  6866. ctx->property_get = 0;
  6867. ctx->property_set = 0;
  6868. if( ctx->property_arg )
  6869. {
  6870. asDELETE(ctx->property_arg, asSExprContext);
  6871. ctx->property_arg = 0;
  6872. }
  6873. return 0;
  6874. }
  6875. void asCCompiler::ProcessPropertyGetAccessor(asSExprContext *ctx, asCScriptNode *node)
  6876. {
  6877. // If no property accessor has been prepared then don't do anything
  6878. if( !ctx->property_get && !ctx->property_set )
  6879. return;
  6880. if( !ctx->property_get )
  6881. {
  6882. // Raise error on missing accessor
  6883. Error(TXT_PROPERTY_HAS_NO_GET_ACCESSOR, node);
  6884. ctx->type.SetDummy();
  6885. return;
  6886. }
  6887. asCTypeInfo objType = ctx->type;
  6888. asCScriptFunction *func = engine->scriptFunctions[ctx->property_get];
  6889. // Make sure the arg match the property
  6890. asCArray<int> funcs;
  6891. funcs.PushLast(ctx->property_get);
  6892. asCArray<asSExprContext *> args;
  6893. if( ctx->property_arg )
  6894. args.PushLast(ctx->property_arg);
  6895. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  6896. if( funcs.GetLength() == 0 )
  6897. {
  6898. // MatchFunctions already reported the error
  6899. if( ctx->property_arg )
  6900. {
  6901. asDELETE(ctx->property_arg, asSExprContext);
  6902. ctx->property_arg = 0;
  6903. }
  6904. ctx->type.SetDummy();
  6905. return;
  6906. }
  6907. if( func->objectType )
  6908. {
  6909. // Setup the context with the original type so the method call gets built correctly
  6910. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  6911. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  6912. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  6913. // Don't allow the call if the object is read-only and the property accessor is not const
  6914. if( ctx->property_const && !func->isReadOnly )
  6915. {
  6916. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  6917. asCArray<int> funcs;
  6918. funcs.PushLast(ctx->property_get);
  6919. PrintMatchingFuncs(funcs, node);
  6920. }
  6921. }
  6922. // Call the accessor
  6923. MakeFunctionCall(ctx, ctx->property_get, func->objectType, args, node);
  6924. if( func->objectType )
  6925. {
  6926. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  6927. if( objType.isTemporary &&
  6928. ctx->type.dataType.IsReference() &&
  6929. !ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  6930. {
  6931. // Remember the original object's variable, so that it can be released
  6932. // later on when the reference to its member goes out of scope
  6933. ctx->type.isTemporary = true;
  6934. ctx->type.stackOffset = objType.stackOffset;
  6935. }
  6936. else
  6937. {
  6938. // As the method didn't return a reference to a member
  6939. // we can safely release the original object now
  6940. ReleaseTemporaryVariable(objType, &ctx->bc);
  6941. }
  6942. }
  6943. ctx->property_get = 0;
  6944. ctx->property_set = 0;
  6945. if( ctx->property_arg )
  6946. {
  6947. asDELETE(ctx->property_arg, asSExprContext);
  6948. ctx->property_arg = 0;
  6949. }
  6950. }
  6951. int asCCompiler::CompileExpressionPostOp(asCScriptNode *node, asSExprContext *ctx)
  6952. {
  6953. int op = node->tokenType;
  6954. // Check if the variable is initialized (if it indeed is a variable)
  6955. IsVariableInitialized(&ctx->type, node);
  6956. if( (op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  6957. {
  6958. const char *opName = 0;
  6959. switch( op )
  6960. {
  6961. case ttInc: opName = "opPostInc"; break;
  6962. case ttDec: opName = "opPostDec"; break;
  6963. }
  6964. if( opName )
  6965. {
  6966. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  6967. ProcessPropertyGetAccessor(ctx, node);
  6968. // Is it a const value?
  6969. bool isConst = false;
  6970. if( ctx->type.dataType.IsObjectHandle() )
  6971. isConst = ctx->type.dataType.IsHandleToConst();
  6972. else
  6973. isConst = ctx->type.dataType.IsReadOnly();
  6974. // 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
  6975. // Find the correct method
  6976. asCArray<int> funcs;
  6977. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  6978. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  6979. {
  6980. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  6981. if( func->name == opName &&
  6982. func->parameterTypes.GetLength() == 0 &&
  6983. (!isConst || func->isReadOnly) )
  6984. {
  6985. funcs.PushLast(func->id);
  6986. }
  6987. }
  6988. // Did we find the method?
  6989. if( funcs.GetLength() == 1 )
  6990. {
  6991. asCTypeInfo objType = ctx->type;
  6992. asCArray<asSExprContext *> args;
  6993. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  6994. ReleaseTemporaryVariable(objType, &ctx->bc);
  6995. return 0;
  6996. }
  6997. else if( funcs.GetLength() == 0 )
  6998. {
  6999. asCString str;
  7000. str = asCString(opName) + "()";
  7001. if( isConst )
  7002. str += " const";
  7003. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  7004. Error(str.AddressOf(), node);
  7005. ctx->type.SetDummy();
  7006. return -1;
  7007. }
  7008. else if( funcs.GetLength() > 1 )
  7009. {
  7010. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  7011. PrintMatchingFuncs(funcs, node);
  7012. ctx->type.SetDummy();
  7013. return -1;
  7014. }
  7015. }
  7016. }
  7017. else if( op == ttInc || op == ttDec )
  7018. {
  7019. // Make sure the reference isn't a temporary variable
  7020. if( ctx->type.isTemporary )
  7021. {
  7022. Error(TXT_REF_IS_TEMP, node);
  7023. return -1;
  7024. }
  7025. if( ctx->type.dataType.IsReadOnly() )
  7026. {
  7027. Error(TXT_REF_IS_READ_ONLY, node);
  7028. return -1;
  7029. }
  7030. if( ctx->property_get || ctx->property_set )
  7031. {
  7032. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  7033. return -1;
  7034. }
  7035. if( !ctx->type.isLValue )
  7036. {
  7037. Error(TXT_NOT_LVALUE, node);
  7038. return -1;
  7039. }
  7040. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  7041. ConvertToReference(ctx);
  7042. else if( !ctx->type.dataType.IsReference() )
  7043. {
  7044. Error(TXT_NOT_VALID_REFERENCE, node);
  7045. return -1;
  7046. }
  7047. // Copy the value to a temp before changing it
  7048. ConvertToTempVariable(ctx);
  7049. asASSERT(!ctx->type.isLValue);
  7050. // Increment the value pointed to by the reference still in the register
  7051. asEBCInstr iInc = asBC_INCi, iDec = asBC_DECi;
  7052. if( ctx->type.dataType.IsDoubleType() )
  7053. {
  7054. iInc = asBC_INCd;
  7055. iDec = asBC_DECd;
  7056. }
  7057. else if( ctx->type.dataType.IsFloatType() )
  7058. {
  7059. iInc = asBC_INCf;
  7060. iDec = asBC_DECf;
  7061. }
  7062. else if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() )
  7063. {
  7064. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  7065. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  7066. {
  7067. iInc = asBC_INCi16;
  7068. iDec = asBC_DECi16;
  7069. }
  7070. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  7071. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  7072. {
  7073. iInc = asBC_INCi8;
  7074. iDec = asBC_DECi8;
  7075. }
  7076. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  7077. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  7078. {
  7079. iInc = asBC_INCi64;
  7080. iDec = asBC_DECi64;
  7081. }
  7082. }
  7083. else
  7084. {
  7085. Error(TXT_ILLEGAL_OPERATION, node);
  7086. return -1;
  7087. }
  7088. if( op == ttInc ) ctx->bc.Instr(iInc); else ctx->bc.Instr(iDec);
  7089. }
  7090. else if( op == ttDot )
  7091. {
  7092. if( node->firstChild->nodeType == snIdentifier )
  7093. {
  7094. ProcessPropertyGetAccessor(ctx, node);
  7095. // Get the property name
  7096. asCString name(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  7097. // We need to look for get/set property accessors.
  7098. // If found, the context stores information on the get/set accessors
  7099. // until it is known which is to be used.
  7100. int r = 0;
  7101. if( node->next && node->next->tokenType == ttOpenBracket )
  7102. {
  7103. // The property accessor should take an index arg
  7104. asSExprContext dummyArg(engine);
  7105. r = FindPropertyAccessor(name, ctx, &dummyArg, node);
  7106. }
  7107. if( r == 0 )
  7108. r = FindPropertyAccessor(name, ctx, node);
  7109. if( r != 0 )
  7110. return r;
  7111. if( !ctx->type.dataType.IsPrimitive() )
  7112. Dereference(ctx, true);
  7113. if( ctx->type.dataType.IsObjectHandle() )
  7114. {
  7115. // Convert the handle to a normal object
  7116. asCDataType dt = ctx->type.dataType;
  7117. dt.MakeHandle(false);
  7118. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  7119. // The handle may not have been an lvalue, but the dereferenced object is
  7120. ctx->type.isLValue = true;
  7121. }
  7122. // Find the property offset and type
  7123. if( ctx->type.dataType.IsObject() )
  7124. {
  7125. bool isConst = ctx->type.dataType.IsReadOnly();
  7126. asCObjectProperty *prop = builder->GetObjectProperty(ctx->type.dataType, name.AddressOf());
  7127. if( prop )
  7128. {
  7129. // Is the property access allowed?
  7130. if( prop->isPrivate && (!outFunc || outFunc->objectType != ctx->type.dataType.GetObjectType()) )
  7131. {
  7132. asCString msg;
  7133. msg.Format(TXT_PRIVATE_PROP_ACCESS_s, name.AddressOf());
  7134. Error(msg.AddressOf(), node);
  7135. }
  7136. // Put the offset on the stack
  7137. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(ctx->type.dataType.GetObjectType(), false)));
  7138. if( prop->type.IsReference() )
  7139. ctx->bc.Instr(asBC_RDSPTR);
  7140. // Reference to primitive must be stored in the temp register
  7141. if( prop->type.IsPrimitive() )
  7142. {
  7143. ctx->bc.Instr(asBC_PopRPtr);
  7144. }
  7145. // Set the new type (keeping info about temp variable)
  7146. ctx->type.dataType = prop->type;
  7147. ctx->type.dataType.MakeReference(true);
  7148. ctx->type.isVariable = false;
  7149. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  7150. {
  7151. // Objects that are members are not references
  7152. ctx->type.dataType.MakeReference(false);
  7153. }
  7154. ctx->type.dataType.MakeReadOnly(isConst ? true : prop->type.IsReadOnly());
  7155. }
  7156. else
  7157. {
  7158. asCString str;
  7159. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  7160. Error(str.AddressOf(), node);
  7161. return -1;
  7162. }
  7163. }
  7164. else
  7165. {
  7166. asCString str;
  7167. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  7168. Error(str.AddressOf(), node);
  7169. return -1;
  7170. }
  7171. }
  7172. else
  7173. {
  7174. // Make sure it is an object we are accessing
  7175. if( !ctx->type.dataType.IsObject() )
  7176. {
  7177. asCString str;
  7178. str.Format(TXT_ILLEGAL_OPERATION_ON_s, ctx->type.dataType.Format().AddressOf());
  7179. Error(str.AddressOf(), node);
  7180. return -1;
  7181. }
  7182. // Process the get property accessor
  7183. ProcessPropertyGetAccessor(ctx, node);
  7184. bool isConst = false;
  7185. if( ctx->type.dataType.IsObjectHandle() )
  7186. isConst = ctx->type.dataType.IsHandleToConst();
  7187. else
  7188. isConst = ctx->type.dataType.IsReadOnly();
  7189. asCObjectType *trueObj = ctx->type.dataType.GetObjectType();
  7190. asCTypeInfo objType = ctx->type;
  7191. // Compile function call
  7192. CompileFunctionCall(node->firstChild, ctx, trueObj, isConst);
  7193. // If the method returned a reference, then we can't release the original
  7194. // object yet, because the reference may be to a member of it
  7195. if( objType.isTemporary &&
  7196. (ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) &&
  7197. !ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7198. {
  7199. // Remember the original object's variable, so that it can be released
  7200. // later on when the reference to its member goes out of scope
  7201. ctx->type.isTemporary = true;
  7202. ctx->type.stackOffset = objType.stackOffset;
  7203. }
  7204. else
  7205. {
  7206. // As the method didn't return a reference to a member
  7207. // we can safely release the original object now
  7208. ReleaseTemporaryVariable(objType, &ctx->bc);
  7209. }
  7210. }
  7211. }
  7212. else if( op == ttOpenBracket )
  7213. {
  7214. // If the property access takes an index arg, then we should use that instead of processing it now
  7215. asCString propertyName;
  7216. if( (ctx->property_get && engine->scriptFunctions[ctx->property_get]->GetParamCount() == 1) ||
  7217. (ctx->property_set && engine->scriptFunctions[ctx->property_set]->GetParamCount() == 2) )
  7218. {
  7219. // Determine the name of the property accessor
  7220. asCScriptFunction *func = 0;
  7221. if( ctx->property_get )
  7222. func = engine->scriptFunctions[ctx->property_get];
  7223. else
  7224. func = engine->scriptFunctions[ctx->property_get];
  7225. propertyName = func->GetName();
  7226. propertyName = propertyName.SubString(4);
  7227. // Set the original type of the expression so we can re-evaluate the property accessor
  7228. if( func->objectType )
  7229. {
  7230. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7231. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7232. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7233. }
  7234. ctx->property_get = ctx->property_set = 0;
  7235. if( ctx->property_arg )
  7236. {
  7237. asDELETE(ctx->property_arg, asSExprContext);
  7238. ctx->property_arg = 0;
  7239. }
  7240. }
  7241. else
  7242. {
  7243. if( !ctx->type.dataType.IsObject() )
  7244. {
  7245. asCString str;
  7246. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  7247. Error(str.AddressOf(), node);
  7248. return -1;
  7249. }
  7250. ProcessPropertyGetAccessor(ctx, node);
  7251. }
  7252. Dereference(ctx, true);
  7253. // Compile the expression
  7254. asSExprContext expr(engine);
  7255. CompileAssignment(node->firstChild, &expr);
  7256. // Check for the existence of the opIndex method
  7257. asSExprContext lctx(engine);
  7258. MergeExprBytecodeAndType(&lctx, ctx);
  7259. int r = 0;
  7260. if( propertyName == "" )
  7261. r = CompileOverloadedDualOperator2(node, "opIndex", &lctx, &expr, ctx);
  7262. if( r == 0 )
  7263. {
  7264. // Check for accessors methods for the opIndex
  7265. r = FindPropertyAccessor(propertyName == "" ? "opIndex" : propertyName.AddressOf(), &lctx, &expr, node);
  7266. if( r == 0 )
  7267. {
  7268. asCString str;
  7269. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  7270. Error(str.AddressOf(), node);
  7271. return -1;
  7272. }
  7273. else if( r < 0 )
  7274. return -1;
  7275. MergeExprBytecodeAndType(ctx, &lctx);
  7276. }
  7277. }
  7278. return 0;
  7279. }
  7280. int asCCompiler::GetPrecedence(asCScriptNode *op)
  7281. {
  7282. // x * y, x / y, x % y
  7283. // x + y, x - y
  7284. // x <= y, x < y, x >= y, x > y
  7285. // x = =y, x != y, x xor y, x is y, x !is y
  7286. // x and y
  7287. // x or y
  7288. // The following are not used in this function,
  7289. // but should have lower precedence than the above
  7290. // x ? y : z
  7291. // x = y
  7292. // The expression term have the highest precedence
  7293. if( op->nodeType == snExprTerm )
  7294. return 1;
  7295. // Evaluate operators by token
  7296. int tokenType = op->tokenType;
  7297. if( tokenType == ttStar || tokenType == ttSlash || tokenType == ttPercent )
  7298. return 0;
  7299. if( tokenType == ttPlus || tokenType == ttMinus )
  7300. return -1;
  7301. if( tokenType == ttBitShiftLeft ||
  7302. tokenType == ttBitShiftRight ||
  7303. tokenType == ttBitShiftRightArith )
  7304. return -2;
  7305. if( tokenType == ttAmp )
  7306. return -3;
  7307. if( tokenType == ttBitXor )
  7308. return -4;
  7309. if( tokenType == ttBitOr )
  7310. return -5;
  7311. if( tokenType == ttLessThanOrEqual ||
  7312. tokenType == ttLessThan ||
  7313. tokenType == ttGreaterThanOrEqual ||
  7314. tokenType == ttGreaterThan )
  7315. return -6;
  7316. if( tokenType == ttEqual || tokenType == ttNotEqual || tokenType == ttXor || tokenType == ttIs || tokenType == ttNotIs )
  7317. return -7;
  7318. if( tokenType == ttAnd )
  7319. return -8;
  7320. if( tokenType == ttOr )
  7321. return -9;
  7322. // Unknown operator
  7323. asASSERT(false);
  7324. return 0;
  7325. }
  7326. int asCCompiler::MatchArgument(asCArray<int> &funcs, asCArray<int> &matches, const asCTypeInfo *argType, int paramNum, bool allowObjectConstruct)
  7327. {
  7328. bool isExactMatch = false;
  7329. bool isMatchExceptConst = false;
  7330. bool isMatchWithBaseType = false;
  7331. bool isMatchExceptSign = false;
  7332. bool isMatchNotVarType = false;
  7333. asUINT n;
  7334. matches.SetLength(0);
  7335. for( n = 0; n < funcs.GetLength(); n++ )
  7336. {
  7337. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  7338. // Does the function have arguments enough?
  7339. if( (int)desc->parameterTypes.GetLength() <= paramNum )
  7340. continue;
  7341. // Can we make the match by implicit conversion?
  7342. asSExprContext ti(engine);
  7343. ti.type = *argType;
  7344. if( argType->dataType.IsPrimitive() ) ti.type.dataType.MakeReference(false);
  7345. ImplicitConversion(&ti, desc->parameterTypes[paramNum], 0, asIC_IMPLICIT_CONV, false, 0, allowObjectConstruct);
  7346. // If the function parameter is an inout-reference then it must not be possible to call the
  7347. // function with an incorrect argument type, even though the type can normally be converted.
  7348. if( desc->parameterTypes[paramNum].IsReference() &&
  7349. desc->inOutFlags[paramNum] == asTM_INOUTREF &&
  7350. desc->parameterTypes[paramNum].GetTokenType() != ttQuestion )
  7351. {
  7352. if( desc->parameterTypes[paramNum].IsPrimitive() &&
  7353. desc->parameterTypes[paramNum].GetTokenType() != argType->dataType.GetTokenType() )
  7354. continue;
  7355. if( desc->parameterTypes[paramNum].IsEnumType() &&
  7356. desc->parameterTypes[paramNum].GetObjectType() != argType->dataType.GetObjectType() )
  7357. continue;
  7358. }
  7359. // How well does the argument match the function parameter?
  7360. if( desc->parameterTypes[paramNum].IsEqualExceptRef(ti.type.dataType) )
  7361. {
  7362. // Is it an exact match?
  7363. if( argType->dataType.IsEqualExceptRef(ti.type.dataType) )
  7364. {
  7365. if( !isExactMatch ) matches.SetLength(0);
  7366. isExactMatch = true;
  7367. matches.PushLast(funcs[n]);
  7368. continue;
  7369. }
  7370. if( !isExactMatch )
  7371. {
  7372. // Is it a match except const?
  7373. if( argType->dataType.IsEqualExceptRefAndConst(ti.type.dataType) )
  7374. {
  7375. if( !isMatchExceptConst ) matches.SetLength(0);
  7376. isMatchExceptConst = true;
  7377. matches.PushLast(funcs[n]);
  7378. continue;
  7379. }
  7380. if( !isMatchExceptConst )
  7381. {
  7382. // Is it a size promotion, e.g. int8 -> int?
  7383. if( argType->dataType.IsSamePrimitiveBaseType(ti.type.dataType) ||
  7384. (argType->dataType.IsEnumType() && ti.type.dataType.IsIntegerType()) )
  7385. {
  7386. if( !isMatchWithBaseType ) matches.SetLength(0);
  7387. isMatchWithBaseType = true;
  7388. matches.PushLast(funcs[n]);
  7389. continue;
  7390. }
  7391. if( !isMatchWithBaseType )
  7392. {
  7393. // Conversion between signed and unsigned integer is better than between integer and float
  7394. // Is it a match except for sign?
  7395. if( (argType->dataType.IsIntegerType() && ti.type.dataType.IsUnsignedType()) ||
  7396. (argType->dataType.IsUnsignedType() && ti.type.dataType.IsIntegerType()) ||
  7397. (argType->dataType.IsEnumType() && ti.type.dataType.IsUnsignedType()) )
  7398. {
  7399. if( !isMatchExceptSign ) matches.SetLength(0);
  7400. isMatchExceptSign = true;
  7401. matches.PushLast(funcs[n]);
  7402. continue;
  7403. }
  7404. if( !isMatchExceptSign )
  7405. {
  7406. // If there was any match without a var type it has higher priority
  7407. if( desc->parameterTypes[paramNum].GetTokenType() != ttQuestion )
  7408. {
  7409. if( !isMatchNotVarType ) matches.SetLength(0);
  7410. isMatchNotVarType = true;
  7411. matches.PushLast(funcs[n]);
  7412. continue;
  7413. }
  7414. // Implicit conversion to ?& has the smallest priority
  7415. if( !isMatchNotVarType )
  7416. matches.PushLast(funcs[n]);
  7417. }
  7418. }
  7419. }
  7420. }
  7421. }
  7422. }
  7423. return (int)matches.GetLength();
  7424. }
  7425. void asCCompiler::PrepareArgument2(asSExprContext *ctx, asSExprContext *arg, asCDataType *paramType, bool isFunction, int refType, asCArray<int> *reservedVars)
  7426. {
  7427. // Reference parameters whose value won't be used don't evaluate the expression
  7428. if( paramType->IsReference() && !(refType & asTM_INREF) )
  7429. {
  7430. // Store the original bytecode so that it can be reused when processing the deferred output parameter
  7431. asSExprContext *orig = asNEW(asSExprContext)(engine);
  7432. MergeExprBytecodeAndType(orig, arg);
  7433. arg->origExpr = orig;
  7434. }
  7435. PrepareArgument(paramType, arg, arg->exprNode, isFunction, refType, reservedVars);
  7436. // arg still holds the original expression for output parameters
  7437. ctx->bc.AddCode(&arg->bc);
  7438. }
  7439. bool asCCompiler::CompileOverloadedDualOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  7440. {
  7441. ctx->exprNode = node;
  7442. // What type of operator is it?
  7443. int token = node->tokenType;
  7444. if( token == ttUnrecognizedToken )
  7445. {
  7446. // This happens when the compiler is inferring an assignment
  7447. // operation from another action, for example in preparing a value
  7448. // as a function argument
  7449. token = ttAssignment;
  7450. }
  7451. // boolean operators are not overloadable
  7452. if( token == ttAnd ||
  7453. token == ttOr ||
  7454. token == ttXor )
  7455. return false;
  7456. // Dual operators can also be implemented as class methods
  7457. if( token == ttEqual ||
  7458. token == ttNotEqual )
  7459. {
  7460. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7461. // Find the matching opEquals method
  7462. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  7463. if( r == 0 )
  7464. {
  7465. // Try again by switching the order of the operands
  7466. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  7467. }
  7468. if( r == 1 )
  7469. {
  7470. if( token == ttNotEqual )
  7471. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  7472. // Success, don't continue
  7473. return true;
  7474. }
  7475. else if( r < 0 )
  7476. {
  7477. // Compiler error, don't continue
  7478. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  7479. return true;
  7480. }
  7481. }
  7482. if( token == ttEqual ||
  7483. token == ttNotEqual ||
  7484. token == ttLessThan ||
  7485. token == ttLessThanOrEqual ||
  7486. token == ttGreaterThan ||
  7487. token == ttGreaterThanOrEqual )
  7488. {
  7489. bool swappedOrder = false;
  7490. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7491. // Find the matching opCmp method
  7492. int r = CompileOverloadedDualOperator2(node, "opCmp", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  7493. if( r == 0 )
  7494. {
  7495. // Try again by switching the order of the operands
  7496. swappedOrder = true;
  7497. r = CompileOverloadedDualOperator2(node, "opCmp", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  7498. }
  7499. if( r == 1 )
  7500. {
  7501. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  7502. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  7503. ctx->bc.InstrW_DW(asBC_CMPIi, ctx->type.stackOffset, 0);
  7504. if( token == ttEqual )
  7505. ctx->bc.Instr(asBC_TZ);
  7506. else if( token == ttNotEqual )
  7507. ctx->bc.Instr(asBC_TNZ);
  7508. else if( (token == ttLessThan && !swappedOrder) ||
  7509. (token == ttGreaterThan && swappedOrder) )
  7510. ctx->bc.Instr(asBC_TS);
  7511. else if( (token == ttLessThanOrEqual && !swappedOrder) ||
  7512. (token == ttGreaterThanOrEqual && swappedOrder) )
  7513. ctx->bc.Instr(asBC_TNP);
  7514. else if( (token == ttGreaterThan && !swappedOrder) ||
  7515. (token == ttLessThan && swappedOrder) )
  7516. ctx->bc.Instr(asBC_TP);
  7517. else if( (token == ttGreaterThanOrEqual && !swappedOrder) ||
  7518. (token == ttLessThanOrEqual && swappedOrder) )
  7519. ctx->bc.Instr(asBC_TNS);
  7520. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  7521. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), a, true);
  7522. // Success, don't continue
  7523. return true;
  7524. }
  7525. else if( r < 0 )
  7526. {
  7527. // Compiler error, don't continue
  7528. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  7529. return true;
  7530. }
  7531. }
  7532. // The rest of the operators are not commutative, and doesn't require specific return type
  7533. const char *op = 0, *op_r = 0;
  7534. switch( token )
  7535. {
  7536. case ttPlus: op = "opAdd"; op_r = "opAdd_r"; break;
  7537. case ttMinus: op = "opSub"; op_r = "opSub_r"; break;
  7538. case ttStar: op = "opMul"; op_r = "opMul_r"; break;
  7539. case ttSlash: op = "opDiv"; op_r = "opDiv_r"; break;
  7540. case ttPercent: op = "opMod"; op_r = "opMod_r"; break;
  7541. case ttBitOr: op = "opOr"; op_r = "opOr_r"; break;
  7542. case ttAmp: op = "opAnd"; op_r = "opAnd_r"; break;
  7543. case ttBitXor: op = "opXor"; op_r = "opXor_r"; break;
  7544. case ttBitShiftLeft: op = "opShl"; op_r = "opShl_r"; break;
  7545. case ttBitShiftRight: op = "opShr"; op_r = "opShr_r"; break;
  7546. case ttBitShiftRightArith: op = "opUShr"; op_r = "opUShr_r"; break;
  7547. }
  7548. // TODO: Might be interesting to support a concatenation operator, e.g. ~
  7549. if( op && op_r )
  7550. {
  7551. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7552. // Find the matching operator method
  7553. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  7554. if( r == 0 )
  7555. {
  7556. // Try again by switching the order of the operands, and using the reversed operator
  7557. r = CompileOverloadedDualOperator2(node, op_r, rctx, lctx, ctx);
  7558. }
  7559. if( r == 1 )
  7560. {
  7561. // Success, don't continue
  7562. return true;
  7563. }
  7564. else if( r < 0 )
  7565. {
  7566. // Compiler error, don't continue
  7567. ctx->type.SetDummy();
  7568. return true;
  7569. }
  7570. }
  7571. // Assignment operators
  7572. op = 0;
  7573. switch( token )
  7574. {
  7575. case ttAssignment: op = "opAssign"; break;
  7576. case ttAddAssign: op = "opAddAssign"; break;
  7577. case ttSubAssign: op = "opSubAssign"; break;
  7578. case ttMulAssign: op = "opMulAssign"; break;
  7579. case ttDivAssign: op = "opDivAssign"; break;
  7580. case ttModAssign: op = "opModAssign"; break;
  7581. case ttOrAssign: op = "opOrAssign"; break;
  7582. case ttAndAssign: op = "opAndAssign"; break;
  7583. case ttXorAssign: op = "opXorAssign"; break;
  7584. case ttShiftLeftAssign: op = "opShlAssign"; break;
  7585. case ttShiftRightLAssign: op = "opShrAssign"; break;
  7586. case ttShiftRightAAssign: op = "opUShrAssign"; break;
  7587. }
  7588. if( op )
  7589. {
  7590. // TODO: Shouldn't accept const lvalue with the assignment operators
  7591. // Find the matching operator method
  7592. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  7593. if( r == 1 )
  7594. {
  7595. // Success, don't continue
  7596. return true;
  7597. }
  7598. else if( r < 0 )
  7599. {
  7600. // Compiler error, don't continue
  7601. ctx->type.SetDummy();
  7602. return true;
  7603. }
  7604. }
  7605. // No suitable operator was found
  7606. return false;
  7607. }
  7608. // Returns negative on compile error
  7609. // zero on no matching operator
  7610. // one on matching operator
  7611. int asCCompiler::CompileOverloadedDualOperator2(asCScriptNode *node, const char *methodName, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx, bool specificReturn, const asCDataType &returnType)
  7612. {
  7613. // Find the matching method
  7614. if( lctx->type.dataType.IsObject() &&
  7615. (!lctx->type.isExplicitHandle ||
  7616. lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  7617. {
  7618. // Is the left value a const?
  7619. bool isConst = false;
  7620. if( lctx->type.dataType.IsObjectHandle() )
  7621. isConst = lctx->type.dataType.IsHandleToConst();
  7622. else
  7623. isConst = lctx->type.dataType.IsReadOnly();
  7624. asCArray<int> funcs;
  7625. asCObjectType *ot = lctx->type.dataType.GetObjectType();
  7626. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7627. {
  7628. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  7629. if( func->name == methodName &&
  7630. (!specificReturn || func->returnType == returnType) &&
  7631. func->parameterTypes.GetLength() == 1 &&
  7632. (!isConst || func->isReadOnly) )
  7633. {
  7634. // Make sure the method is accessible by the module
  7635. asCConfigGroup *group = engine->FindConfigGroupForFunction(func->id);
  7636. if( !group || group->HasModuleAccess(builder->module->name.AddressOf()) )
  7637. funcs.PushLast(func->id);
  7638. }
  7639. }
  7640. // Which is the best matching function?
  7641. asCArray<int> ops;
  7642. MatchArgument(funcs, ops, &rctx->type, 0);
  7643. // If the object is not const, then we need to prioritize non-const methods
  7644. if( !isConst )
  7645. FilterConst(ops);
  7646. // Did we find an operator?
  7647. if( ops.GetLength() == 1 )
  7648. {
  7649. // Process the lctx expression as get accessor
  7650. ProcessPropertyGetAccessor(lctx, node);
  7651. // Merge the bytecode so that it forms lvalue.methodName(rvalue)
  7652. asCTypeInfo objType = lctx->type;
  7653. asCArray<asSExprContext *> args;
  7654. args.PushLast(rctx);
  7655. MergeExprBytecode(ctx, lctx);
  7656. ctx->type = lctx->type;
  7657. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  7658. // If the method returned a reference, then we can't release the original
  7659. // object yet, because the reference may be to a member of it
  7660. if( objType.isTemporary &&
  7661. (ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) &&
  7662. !ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not to a member
  7663. {
  7664. // Remember the object's variable, so that it can be released
  7665. // later on when the reference to its member goes out of scope
  7666. ctx->type.isTemporary = true;
  7667. ctx->type.stackOffset = objType.stackOffset;
  7668. }
  7669. else
  7670. {
  7671. // As the index operator didn't return a reference to a
  7672. // member we can release the original object now
  7673. ReleaseTemporaryVariable(objType, &ctx->bc);
  7674. }
  7675. // Found matching operator
  7676. return 1;
  7677. }
  7678. else if( ops.GetLength() > 1 )
  7679. {
  7680. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  7681. PrintMatchingFuncs(ops, node);
  7682. ctx->type.SetDummy();
  7683. // Compiler error
  7684. return -1;
  7685. }
  7686. }
  7687. // No matching operator
  7688. return 0;
  7689. }
  7690. void asCCompiler::MakeFunctionCall(asSExprContext *ctx, int funcId, asCObjectType *objectType, asCArray<asSExprContext*> &args, asCScriptNode * /*node*/, bool useVariable, int stackOffset, int funcPtrVar)
  7691. {
  7692. if( objectType )
  7693. {
  7694. // The ASHANDLE type is really a value type, so if it is a
  7695. // local variable on the stack it must not be dereferenced
  7696. if( !(objectType->flags & asOBJ_ASHANDLE) ||
  7697. !(ctx->type.isVariable && !IsVariableOnHeap(ctx->type.stackOffset)) )
  7698. Dereference(ctx, true);
  7699. // This following warning was removed as there may be valid reasons
  7700. // for calling non-const methods on temporary objects, and we shouldn't
  7701. // warn when there is no way of removing the warning.
  7702. /*
  7703. // Warn if the method is non-const and the object is temporary
  7704. // since the changes will be lost when the object is destroyed.
  7705. // If the object is accessed through a handle, then it is assumed
  7706. // the object is not temporary, even though the handle is.
  7707. if( ctx->type.isTemporary &&
  7708. !ctx->type.dataType.IsObjectHandle() &&
  7709. !engine->scriptFunctions[funcId]->isReadOnly )
  7710. {
  7711. Warning("A non-const method is called on temporary object. Changes to the object may be lost.", node);
  7712. Information(engine->scriptFunctions[funcId]->GetDeclaration(), node);
  7713. }
  7714. */ }
  7715. asCByteCode objBC(engine);
  7716. objBC.AddCode(&ctx->bc);
  7717. PrepareFunctionCall(funcId, &ctx->bc, args);
  7718. // Verify if any of the args variable offsets are used in the other code.
  7719. // If they are exchange the offset for a new one
  7720. asUINT n;
  7721. for( n = 0; n < args.GetLength(); n++ )
  7722. {
  7723. if( args[n]->type.isTemporary && objBC.IsVarUsed(args[n]->type.stackOffset) )
  7724. {
  7725. // Release the current temporary variable
  7726. ReleaseTemporaryVariable(args[n]->type, 0);
  7727. asCArray<int> usedVars;
  7728. objBC.GetVarsUsed(usedVars);
  7729. ctx->bc.GetVarsUsed(usedVars);
  7730. asCDataType dt = args[n]->type.dataType;
  7731. dt.MakeReference(false);
  7732. int newOffset = AllocateVariableNotIn(dt, true, &usedVars, IsVariableOnHeap(args[n]->type.stackOffset));
  7733. asASSERT( IsVariableOnHeap(args[n]->type.stackOffset) == IsVariableOnHeap(newOffset) );
  7734. ctx->bc.ExchangeVar(args[n]->type.stackOffset, newOffset);
  7735. args[n]->type.stackOffset = (short)newOffset;
  7736. args[n]->type.isTemporary = true;
  7737. args[n]->type.isVariable = true;
  7738. }
  7739. }
  7740. ctx->bc.AddCode(&objBC);
  7741. MoveArgsToStack(funcId, &ctx->bc, args, objectType ? true : false);
  7742. PerformFunctionCall(funcId, ctx, false, &args, 0, useVariable, stackOffset, funcPtrVar);
  7743. }
  7744. int asCCompiler::CompileOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  7745. {
  7746. IsVariableInitialized(&lctx->type, node);
  7747. IsVariableInitialized(&rctx->type, node);
  7748. if( lctx->type.isExplicitHandle || rctx->type.isExplicitHandle ||
  7749. node->tokenType == ttIs || node->tokenType == ttNotIs )
  7750. {
  7751. CompileOperatorOnHandles(node, lctx, rctx, ctx);
  7752. return 0;
  7753. }
  7754. else
  7755. {
  7756. // Compile an overloaded operator for the two operands
  7757. if( CompileOverloadedDualOperator(node, lctx, rctx, ctx) )
  7758. return 0;
  7759. // If both operands are objects, then we shouldn't continue
  7760. if( lctx->type.dataType.IsObject() && rctx->type.dataType.IsObject() )
  7761. {
  7762. asCString str;
  7763. str.Format(TXT_NO_MATCHING_OP_FOUND_FOR_TYPES_s_AND_s, lctx->type.dataType.Format().AddressOf(), rctx->type.dataType.Format().AddressOf());
  7764. Error(str.AddressOf(), node);
  7765. ctx->type.SetDummy();
  7766. return -1;
  7767. }
  7768. // Process the property get accessors (if any)
  7769. ProcessPropertyGetAccessor(lctx, node);
  7770. ProcessPropertyGetAccessor(rctx, node);
  7771. // Make sure we have two variables or constants
  7772. if( lctx->type.dataType.IsReference() ) ConvertToVariableNotIn(lctx, rctx);
  7773. if( rctx->type.dataType.IsReference() ) ConvertToVariableNotIn(rctx, lctx);
  7774. // Make sure lctx doesn't end up with a variable used in rctx
  7775. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  7776. {
  7777. asCArray<int> vars;
  7778. rctx->bc.GetVarsUsed(vars);
  7779. int offset = AllocateVariableNotIn(lctx->type.dataType, true, &vars);
  7780. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  7781. ReleaseTemporaryVariable(offset, 0);
  7782. }
  7783. // Math operators
  7784. // + - * / % += -= *= /= %=
  7785. int op = node->tokenType;
  7786. if( op == ttPlus || op == ttAddAssign ||
  7787. op == ttMinus || op == ttSubAssign ||
  7788. op == ttStar || op == ttMulAssign ||
  7789. op == ttSlash || op == ttDivAssign ||
  7790. op == ttPercent || op == ttModAssign )
  7791. {
  7792. CompileMathOperator(node, lctx, rctx, ctx);
  7793. return 0;
  7794. }
  7795. // Bitwise operators
  7796. // << >> >>> & | ^ <<= >>= >>>= &= |= ^=
  7797. if( op == ttAmp || op == ttAndAssign ||
  7798. op == ttBitOr || op == ttOrAssign ||
  7799. op == ttBitXor || op == ttXorAssign ||
  7800. op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  7801. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  7802. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  7803. {
  7804. CompileBitwiseOperator(node, lctx, rctx, ctx);
  7805. return 0;
  7806. }
  7807. // Comparison operators
  7808. // == != < > <= >=
  7809. if( op == ttEqual || op == ttNotEqual ||
  7810. op == ttLessThan || op == ttLessThanOrEqual ||
  7811. op == ttGreaterThan || op == ttGreaterThanOrEqual )
  7812. {
  7813. CompileComparisonOperator(node, lctx, rctx, ctx);
  7814. return 0;
  7815. }
  7816. // Boolean operators
  7817. // && || ^^
  7818. if( op == ttAnd || op == ttOr || op == ttXor )
  7819. {
  7820. CompileBooleanOperator(node, lctx, rctx, ctx);
  7821. return 0;
  7822. }
  7823. }
  7824. asASSERT(false);
  7825. return -1;
  7826. }
  7827. void asCCompiler::ConvertToTempVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  7828. {
  7829. asCArray<int> excludeVars;
  7830. if( exclude ) exclude->bc.GetVarsUsed(excludeVars);
  7831. ConvertToTempVariableNotIn(ctx, &excludeVars);
  7832. }
  7833. void asCCompiler::ConvertToTempVariableNotIn(asSExprContext *ctx, asCArray<int> *reservedVars)
  7834. {
  7835. // This is only used for primitive types and null handles
  7836. asASSERT( ctx->type.dataType.IsPrimitive() || ctx->type.dataType.IsNullHandle() );
  7837. ConvertToVariableNotIn(ctx, reservedVars);
  7838. if( !ctx->type.isTemporary )
  7839. {
  7840. if( ctx->type.dataType.IsPrimitive() )
  7841. {
  7842. // Copy the variable to a temporary variable
  7843. int offset = AllocateVariableNotIn(ctx->type.dataType, true, reservedVars);
  7844. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  7845. ctx->bc.InstrW_W(asBC_CpyVtoV4, offset, ctx->type.stackOffset);
  7846. else
  7847. ctx->bc.InstrW_W(asBC_CpyVtoV8, offset, ctx->type.stackOffset);
  7848. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  7849. }
  7850. else
  7851. {
  7852. // We should never get here
  7853. asASSERT(false);
  7854. }
  7855. }
  7856. }
  7857. void asCCompiler::ConvertToTempVariable(asSExprContext *ctx)
  7858. {
  7859. ConvertToTempVariableNotIn(ctx, (asCArray<int>*)0);
  7860. }
  7861. void asCCompiler::ConvertToVariable(asSExprContext *ctx)
  7862. {
  7863. ConvertToVariableNotIn(ctx, (asCArray<int>*)0);
  7864. }
  7865. void asCCompiler::ConvertToVariableNotIn(asSExprContext *ctx, asCArray<int> *reservedVars)
  7866. {
  7867. // We should never get here while the context is still an unprocessed property accessor
  7868. asASSERT(ctx->property_get == 0 && ctx->property_set == 0);
  7869. asCArray<int> excludeVars;
  7870. if( reservedVars ) excludeVars.Concatenate(*reservedVars);
  7871. int offset;
  7872. if( !ctx->type.isVariable &&
  7873. (ctx->type.dataType.IsObjectHandle() ||
  7874. (ctx->type.dataType.IsObject() && ctx->type.dataType.SupportHandles())) )
  7875. {
  7876. offset = AllocateVariableNotIn(ctx->type.dataType, true, &excludeVars);
  7877. if( ctx->type.IsNullConstant() )
  7878. {
  7879. if( ctx->bc.GetLastInstr() == asBC_PshC4 || ctx->bc.GetLastInstr() == asBC_PshC8 )
  7880. ctx->bc.Pop(AS_PTR_SIZE); // Pop the null constant pushed onto the stack
  7881. #ifdef AS_64BIT_PTR
  7882. ctx->bc.InstrSHORT_QW(asBC_SetV8, (short)offset, 0);
  7883. #else
  7884. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, 0);
  7885. #endif
  7886. }
  7887. else
  7888. {
  7889. // Copy the object handle to a variable
  7890. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  7891. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  7892. ctx->bc.Pop(AS_PTR_SIZE);
  7893. }
  7894. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  7895. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  7896. ctx->type.dataType.MakeHandle(true);
  7897. }
  7898. else if( (!ctx->type.isVariable || ctx->type.dataType.IsReference()) &&
  7899. ctx->type.dataType.IsPrimitive() )
  7900. {
  7901. if( ctx->type.isConstant )
  7902. {
  7903. offset = AllocateVariableNotIn(ctx->type.dataType, true, &excludeVars);
  7904. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  7905. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, ctx->type.byteValue);
  7906. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  7907. ctx->bc.InstrSHORT_W(asBC_SetV2, (short)offset, ctx->type.wordValue);
  7908. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  7909. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, ctx->type.dwordValue);
  7910. else
  7911. ctx->bc.InstrSHORT_QW(asBC_SetV8, (short)offset, ctx->type.qwordValue);
  7912. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  7913. return;
  7914. }
  7915. else
  7916. {
  7917. asASSERT(ctx->type.dataType.IsPrimitive());
  7918. asASSERT(ctx->type.dataType.IsReference());
  7919. ctx->type.dataType.MakeReference(false);
  7920. offset = AllocateVariableNotIn(ctx->type.dataType, true, &excludeVars);
  7921. // Read the value from the address in the register directly into the variable
  7922. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  7923. ctx->bc.InstrSHORT(asBC_RDR1, (short)offset);
  7924. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  7925. ctx->bc.InstrSHORT(asBC_RDR2, (short)offset);
  7926. else if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  7927. ctx->bc.InstrSHORT(asBC_RDR4, (short)offset);
  7928. else
  7929. ctx->bc.InstrSHORT(asBC_RDR8, (short)offset);
  7930. }
  7931. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  7932. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  7933. }
  7934. }
  7935. void asCCompiler::ConvertToVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  7936. {
  7937. asCArray<int> excludeVars;
  7938. if( exclude ) exclude->bc.GetVarsUsed(excludeVars);
  7939. ConvertToVariableNotIn(ctx, &excludeVars);
  7940. }
  7941. void asCCompiler::CompileMathOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  7942. {
  7943. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  7944. // Implicitly convert the operands to a number type
  7945. asCDataType to;
  7946. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  7947. to.SetTokenType(ttDouble);
  7948. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  7949. to.SetTokenType(ttFloat);
  7950. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  7951. {
  7952. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() )
  7953. to.SetTokenType(ttInt64);
  7954. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  7955. to.SetTokenType(ttUInt64);
  7956. }
  7957. else
  7958. {
  7959. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() ||
  7960. lctx->type.dataType.IsEnumType() || rctx->type.dataType.IsEnumType() )
  7961. to.SetTokenType(ttInt);
  7962. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  7963. to.SetTokenType(ttUInt);
  7964. }
  7965. // If doing an operation with double constant and float variable, the constant should be converted to float
  7966. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  7967. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  7968. to.SetTokenType(ttFloat);
  7969. // Do the actual conversion
  7970. asCArray<int> reservedVars;
  7971. rctx->bc.GetVarsUsed(reservedVars);
  7972. lctx->bc.GetVarsUsed(reservedVars);
  7973. if( lctx->type.dataType.IsReference() )
  7974. ConvertToVariableNotIn(lctx, &reservedVars);
  7975. if( rctx->type.dataType.IsReference() )
  7976. ConvertToVariableNotIn(rctx, &reservedVars);
  7977. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  7978. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  7979. // Verify that the conversion was successful
  7980. if( !lctx->type.dataType.IsIntegerType() &&
  7981. !lctx->type.dataType.IsUnsignedType() &&
  7982. !lctx->type.dataType.IsFloatType() &&
  7983. !lctx->type.dataType.IsDoubleType() )
  7984. {
  7985. asCString str;
  7986. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, lctx->type.dataType.Format().AddressOf());
  7987. Error(str.AddressOf(), node);
  7988. ctx->type.SetDummy();
  7989. return;
  7990. }
  7991. if( !rctx->type.dataType.IsIntegerType() &&
  7992. !rctx->type.dataType.IsUnsignedType() &&
  7993. !rctx->type.dataType.IsFloatType() &&
  7994. !rctx->type.dataType.IsDoubleType() )
  7995. {
  7996. asCString str;
  7997. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, rctx->type.dataType.Format().AddressOf());
  7998. Error(str.AddressOf(), node);
  7999. ctx->type.SetDummy();
  8000. return;
  8001. }
  8002. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8003. // Verify if we are dividing with a constant zero
  8004. int op = node->tokenType;
  8005. if( rctx->type.isConstant && rctx->type.qwordValue == 0 &&
  8006. (op == ttSlash || op == ttDivAssign ||
  8007. op == ttPercent || op == ttModAssign) )
  8008. {
  8009. Error(TXT_DIVIDE_BY_ZERO, node);
  8010. }
  8011. if( !isConstant )
  8012. {
  8013. ConvertToVariableNotIn(lctx, rctx);
  8014. ConvertToVariableNotIn(rctx, lctx);
  8015. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8016. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8017. if( op == ttAddAssign || op == ttSubAssign ||
  8018. op == ttMulAssign || op == ttDivAssign ||
  8019. op == ttModAssign )
  8020. {
  8021. // Merge the operands in the different order so that they are evaluated correctly
  8022. MergeExprBytecode(ctx, rctx);
  8023. MergeExprBytecode(ctx, lctx);
  8024. }
  8025. else
  8026. {
  8027. MergeExprBytecode(ctx, lctx);
  8028. MergeExprBytecode(ctx, rctx);
  8029. }
  8030. ProcessDeferredParams(ctx);
  8031. asEBCInstr instruction = asBC_ADDi;
  8032. if( lctx->type.dataType.IsIntegerType() ||
  8033. lctx->type.dataType.IsUnsignedType() )
  8034. {
  8035. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8036. {
  8037. if( op == ttPlus || op == ttAddAssign )
  8038. instruction = asBC_ADDi;
  8039. else if( op == ttMinus || op == ttSubAssign )
  8040. instruction = asBC_SUBi;
  8041. else if( op == ttStar || op == ttMulAssign )
  8042. instruction = asBC_MULi;
  8043. else if( op == ttSlash || op == ttDivAssign )
  8044. {
  8045. if( lctx->type.dataType.IsIntegerType() )
  8046. instruction = asBC_DIVi;
  8047. else
  8048. instruction = asBC_DIVu;
  8049. }
  8050. else if( op == ttPercent || op == ttModAssign )
  8051. {
  8052. if( lctx->type.dataType.IsIntegerType() )
  8053. instruction = asBC_MODi;
  8054. else
  8055. instruction = asBC_MODu;
  8056. }
  8057. }
  8058. else
  8059. {
  8060. if( op == ttPlus || op == ttAddAssign )
  8061. instruction = asBC_ADDi64;
  8062. else if( op == ttMinus || op == ttSubAssign )
  8063. instruction = asBC_SUBi64;
  8064. else if( op == ttStar || op == ttMulAssign )
  8065. instruction = asBC_MULi64;
  8066. else if( op == ttSlash || op == ttDivAssign )
  8067. {
  8068. if( lctx->type.dataType.IsIntegerType() )
  8069. instruction = asBC_DIVi64;
  8070. else
  8071. instruction = asBC_DIVu64;
  8072. }
  8073. else if( op == ttPercent || op == ttModAssign )
  8074. {
  8075. if( lctx->type.dataType.IsIntegerType() )
  8076. instruction = asBC_MODi64;
  8077. else
  8078. instruction = asBC_MODu64;
  8079. }
  8080. }
  8081. }
  8082. else if( lctx->type.dataType.IsFloatType() )
  8083. {
  8084. if( op == ttPlus || op == ttAddAssign )
  8085. instruction = asBC_ADDf;
  8086. else if( op == ttMinus || op == ttSubAssign )
  8087. instruction = asBC_SUBf;
  8088. else if( op == ttStar || op == ttMulAssign )
  8089. instruction = asBC_MULf;
  8090. else if( op == ttSlash || op == ttDivAssign )
  8091. instruction = asBC_DIVf;
  8092. else if( op == ttPercent || op == ttModAssign )
  8093. instruction = asBC_MODf;
  8094. }
  8095. else if( lctx->type.dataType.IsDoubleType() )
  8096. {
  8097. if( op == ttPlus || op == ttAddAssign )
  8098. instruction = asBC_ADDd;
  8099. else if( op == ttMinus || op == ttSubAssign )
  8100. instruction = asBC_SUBd;
  8101. else if( op == ttStar || op == ttMulAssign )
  8102. instruction = asBC_MULd;
  8103. else if( op == ttSlash || op == ttDivAssign )
  8104. instruction = asBC_DIVd;
  8105. else if( op == ttPercent || op == ttModAssign )
  8106. instruction = asBC_MODd;
  8107. }
  8108. else
  8109. {
  8110. // Shouldn't be possible
  8111. asASSERT(false);
  8112. }
  8113. // Do the operation
  8114. int a = AllocateVariable(lctx->type.dataType, true);
  8115. int b = lctx->type.stackOffset;
  8116. int c = rctx->type.stackOffset;
  8117. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8118. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8119. }
  8120. else
  8121. {
  8122. // Both values are constants
  8123. if( lctx->type.dataType.IsIntegerType() ||
  8124. lctx->type.dataType.IsUnsignedType() )
  8125. {
  8126. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8127. {
  8128. int v = 0;
  8129. if( op == ttPlus )
  8130. v = lctx->type.intValue + rctx->type.intValue;
  8131. else if( op == ttMinus )
  8132. v = lctx->type.intValue - rctx->type.intValue;
  8133. else if( op == ttStar )
  8134. v = lctx->type.intValue * rctx->type.intValue;
  8135. else if( op == ttSlash )
  8136. {
  8137. if( rctx->type.intValue == 0 )
  8138. v = 0;
  8139. else
  8140. if( lctx->type.dataType.IsIntegerType() )
  8141. v = lctx->type.intValue / rctx->type.intValue;
  8142. else
  8143. v = lctx->type.dwordValue / rctx->type.dwordValue;
  8144. }
  8145. else if( op == ttPercent )
  8146. {
  8147. if( rctx->type.intValue == 0 )
  8148. v = 0;
  8149. else
  8150. if( lctx->type.dataType.IsIntegerType() )
  8151. v = lctx->type.intValue % rctx->type.intValue;
  8152. else
  8153. v = lctx->type.dwordValue % rctx->type.dwordValue;
  8154. }
  8155. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8156. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  8157. if( lctx->type.dataType.GetTokenType() == ttUInt && op == ttMinus && lctx->type.intValue < rctx->type.intValue )
  8158. ctx->type.dataType.SetTokenType(ttInt);
  8159. }
  8160. else
  8161. {
  8162. asQWORD v = 0;
  8163. if( op == ttPlus )
  8164. v = lctx->type.qwordValue + rctx->type.qwordValue;
  8165. else if( op == ttMinus )
  8166. v = lctx->type.qwordValue - rctx->type.qwordValue;
  8167. else if( op == ttStar )
  8168. v = lctx->type.qwordValue * rctx->type.qwordValue;
  8169. else if( op == ttSlash )
  8170. {
  8171. if( rctx->type.qwordValue == 0 )
  8172. v = 0;
  8173. else
  8174. if( lctx->type.dataType.IsIntegerType() )
  8175. v = asINT64(lctx->type.qwordValue) / asINT64(rctx->type.qwordValue);
  8176. else
  8177. v = lctx->type.qwordValue / rctx->type.qwordValue;
  8178. }
  8179. else if( op == ttPercent )
  8180. {
  8181. if( rctx->type.qwordValue == 0 )
  8182. v = 0;
  8183. else
  8184. if( lctx->type.dataType.IsIntegerType() )
  8185. v = asINT64(lctx->type.qwordValue) % asINT64(rctx->type.qwordValue);
  8186. else
  8187. v = lctx->type.qwordValue % rctx->type.qwordValue;
  8188. }
  8189. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8190. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  8191. if( lctx->type.dataType.GetTokenType() == ttUInt64 && op == ttMinus && lctx->type.qwordValue < rctx->type.qwordValue )
  8192. ctx->type.dataType.SetTokenType(ttInt64);
  8193. }
  8194. }
  8195. else if( lctx->type.dataType.IsFloatType() )
  8196. {
  8197. float v = 0.0f;
  8198. if( op == ttPlus )
  8199. v = lctx->type.floatValue + rctx->type.floatValue;
  8200. else if( op == ttMinus )
  8201. v = lctx->type.floatValue - rctx->type.floatValue;
  8202. else if( op == ttStar )
  8203. v = lctx->type.floatValue * rctx->type.floatValue;
  8204. else if( op == ttSlash )
  8205. {
  8206. if( rctx->type.floatValue == 0 )
  8207. v = 0;
  8208. else
  8209. v = lctx->type.floatValue / rctx->type.floatValue;
  8210. }
  8211. else if( op == ttPercent )
  8212. {
  8213. if( rctx->type.floatValue == 0 )
  8214. v = 0;
  8215. else
  8216. v = fmodf(lctx->type.floatValue, rctx->type.floatValue);
  8217. }
  8218. ctx->type.SetConstantF(lctx->type.dataType, v);
  8219. }
  8220. else if( lctx->type.dataType.IsDoubleType() )
  8221. {
  8222. double v = 0.0;
  8223. if( op == ttPlus )
  8224. v = lctx->type.doubleValue + rctx->type.doubleValue;
  8225. else if( op == ttMinus )
  8226. v = lctx->type.doubleValue - rctx->type.doubleValue;
  8227. else if( op == ttStar )
  8228. v = lctx->type.doubleValue * rctx->type.doubleValue;
  8229. else if( op == ttSlash )
  8230. {
  8231. if( rctx->type.doubleValue == 0 )
  8232. v = 0;
  8233. else
  8234. v = lctx->type.doubleValue / rctx->type.doubleValue;
  8235. }
  8236. else if( op == ttPercent )
  8237. {
  8238. if( rctx->type.doubleValue == 0 )
  8239. v = 0;
  8240. else
  8241. v = fmod(lctx->type.doubleValue, rctx->type.doubleValue);
  8242. }
  8243. ctx->type.SetConstantD(lctx->type.dataType, v);
  8244. }
  8245. else
  8246. {
  8247. // Shouldn't be possible
  8248. asASSERT(false);
  8249. }
  8250. }
  8251. }
  8252. void asCCompiler::CompileBitwiseOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8253. {
  8254. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  8255. int op = node->tokenType;
  8256. if( op == ttAmp || op == ttAndAssign ||
  8257. op == ttBitOr || op == ttOrAssign ||
  8258. op == ttBitXor || op == ttXorAssign )
  8259. {
  8260. // Convert left hand operand to integer if it's not already one
  8261. asCDataType to;
  8262. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 ||
  8263. rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8264. to.SetTokenType(ttUInt64);
  8265. else
  8266. to.SetTokenType(ttUInt);
  8267. // Do the actual conversion
  8268. asCArray<int> reservedVars;
  8269. rctx->bc.GetVarsUsed(reservedVars);
  8270. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8271. // Verify that the conversion was successful
  8272. if( !lctx->type.dataType.IsUnsignedType() )
  8273. {
  8274. asCString str;
  8275. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8276. Error(str.AddressOf(), node);
  8277. }
  8278. // Convert right hand operand to same type as left hand operand
  8279. asCArray<int> vars;
  8280. lctx->bc.GetVarsUsed(vars);
  8281. ImplicitConversion(rctx, lctx->type.dataType, node, asIC_IMPLICIT_CONV, true, &vars);
  8282. if( !rctx->type.dataType.IsEqualExceptRef(lctx->type.dataType) )
  8283. {
  8284. asCString str;
  8285. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  8286. Error(str.AddressOf(), node);
  8287. }
  8288. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8289. if( !isConstant )
  8290. {
  8291. ConvertToVariableNotIn(lctx, rctx);
  8292. ConvertToVariableNotIn(rctx, lctx);
  8293. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8294. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8295. if( op == ttAndAssign || op == ttOrAssign || op == ttXorAssign )
  8296. {
  8297. // Compound assignments execute the right hand value first
  8298. MergeExprBytecode(ctx, rctx);
  8299. MergeExprBytecode(ctx, lctx);
  8300. }
  8301. else
  8302. {
  8303. MergeExprBytecode(ctx, lctx);
  8304. MergeExprBytecode(ctx, rctx);
  8305. }
  8306. ProcessDeferredParams(ctx);
  8307. asEBCInstr instruction = asBC_BAND;
  8308. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8309. {
  8310. if( op == ttAmp || op == ttAndAssign )
  8311. instruction = asBC_BAND;
  8312. else if( op == ttBitOr || op == ttOrAssign )
  8313. instruction = asBC_BOR;
  8314. else if( op == ttBitXor || op == ttXorAssign )
  8315. instruction = asBC_BXOR;
  8316. }
  8317. else
  8318. {
  8319. if( op == ttAmp || op == ttAndAssign )
  8320. instruction = asBC_BAND64;
  8321. else if( op == ttBitOr || op == ttOrAssign )
  8322. instruction = asBC_BOR64;
  8323. else if( op == ttBitXor || op == ttXorAssign )
  8324. instruction = asBC_BXOR64;
  8325. }
  8326. // Do the operation
  8327. int a = AllocateVariable(lctx->type.dataType, true);
  8328. int b = lctx->type.stackOffset;
  8329. int c = rctx->type.stackOffset;
  8330. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8331. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8332. }
  8333. else
  8334. {
  8335. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8336. {
  8337. asQWORD v = 0;
  8338. if( op == ttAmp )
  8339. v = lctx->type.qwordValue & rctx->type.qwordValue;
  8340. else if( op == ttBitOr )
  8341. v = lctx->type.qwordValue | rctx->type.qwordValue;
  8342. else if( op == ttBitXor )
  8343. v = lctx->type.qwordValue ^ rctx->type.qwordValue;
  8344. // Remember the result
  8345. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8346. }
  8347. else
  8348. {
  8349. asDWORD v = 0;
  8350. if( op == ttAmp )
  8351. v = lctx->type.dwordValue & rctx->type.dwordValue;
  8352. else if( op == ttBitOr )
  8353. v = lctx->type.dwordValue | rctx->type.dwordValue;
  8354. else if( op == ttBitXor )
  8355. v = lctx->type.dwordValue ^ rctx->type.dwordValue;
  8356. // Remember the result
  8357. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8358. }
  8359. }
  8360. }
  8361. else if( op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  8362. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  8363. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8364. {
  8365. // Don't permit object to primitive conversion, since we don't know which integer type is the correct one
  8366. if( lctx->type.dataType.IsObject() )
  8367. {
  8368. asCString str;
  8369. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  8370. Error(str.AddressOf(), node);
  8371. // Set an integer value and allow the compiler to continue
  8372. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttInt, true), 0);
  8373. return;
  8374. }
  8375. // Convert left hand operand to integer if it's not already one
  8376. asCDataType to = lctx->type.dataType;
  8377. if( lctx->type.dataType.IsUnsignedType() &&
  8378. lctx->type.dataType.GetSizeInMemoryBytes() < 4 )
  8379. {
  8380. to = asCDataType::CreatePrimitive(ttUInt, false);
  8381. }
  8382. else if( !lctx->type.dataType.IsUnsignedType() )
  8383. {
  8384. asCDataType to;
  8385. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8386. to.SetTokenType(ttInt64);
  8387. else
  8388. to.SetTokenType(ttInt);
  8389. }
  8390. // Do the actual conversion
  8391. asCArray<int> reservedVars;
  8392. rctx->bc.GetVarsUsed(reservedVars);
  8393. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8394. // Verify that the conversion was successful
  8395. if( lctx->type.dataType != to )
  8396. {
  8397. asCString str;
  8398. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8399. Error(str.AddressOf(), node);
  8400. }
  8401. // Right operand must be 32bit uint
  8402. asCArray<int> vars;
  8403. lctx->bc.GetVarsUsed(vars);
  8404. ImplicitConversion(rctx, asCDataType::CreatePrimitive(ttUInt, true), node, asIC_IMPLICIT_CONV, true, &vars);
  8405. if( !rctx->type.dataType.IsUnsignedType() )
  8406. {
  8407. asCString str;
  8408. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "uint");
  8409. Error(str.AddressOf(), node);
  8410. }
  8411. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8412. if( !isConstant )
  8413. {
  8414. ConvertToVariableNotIn(lctx, rctx);
  8415. ConvertToVariableNotIn(rctx, lctx);
  8416. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8417. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8418. if( op == ttShiftLeftAssign || op == ttShiftRightLAssign || op == ttShiftRightAAssign )
  8419. {
  8420. // Compound assignments execute the right hand value first
  8421. MergeExprBytecode(ctx, rctx);
  8422. MergeExprBytecode(ctx, lctx);
  8423. }
  8424. else
  8425. {
  8426. MergeExprBytecode(ctx, lctx);
  8427. MergeExprBytecode(ctx, rctx);
  8428. }
  8429. ProcessDeferredParams(ctx);
  8430. asEBCInstr instruction = asBC_BSLL;
  8431. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8432. {
  8433. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  8434. instruction = asBC_BSLL;
  8435. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  8436. instruction = asBC_BSRL;
  8437. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8438. instruction = asBC_BSRA;
  8439. }
  8440. else
  8441. {
  8442. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  8443. instruction = asBC_BSLL64;
  8444. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  8445. instruction = asBC_BSRL64;
  8446. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8447. instruction = asBC_BSRA64;
  8448. }
  8449. // Do the operation
  8450. int a = AllocateVariable(lctx->type.dataType, true);
  8451. int b = lctx->type.stackOffset;
  8452. int c = rctx->type.stackOffset;
  8453. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8454. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8455. }
  8456. else
  8457. {
  8458. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8459. {
  8460. asDWORD v = 0;
  8461. if( op == ttBitShiftLeft )
  8462. v = lctx->type.dwordValue << rctx->type.dwordValue;
  8463. else if( op == ttBitShiftRight )
  8464. v = lctx->type.dwordValue >> rctx->type.dwordValue;
  8465. else if( op == ttBitShiftRightArith )
  8466. v = lctx->type.intValue >> rctx->type.dwordValue;
  8467. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8468. }
  8469. else
  8470. {
  8471. asQWORD v = 0;
  8472. if( op == ttBitShiftLeft )
  8473. v = lctx->type.qwordValue << rctx->type.dwordValue;
  8474. else if( op == ttBitShiftRight )
  8475. v = lctx->type.qwordValue >> rctx->type.dwordValue;
  8476. else if( op == ttBitShiftRightArith )
  8477. v = asINT64(lctx->type.qwordValue) >> rctx->type.dwordValue;
  8478. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8479. }
  8480. }
  8481. }
  8482. }
  8483. void asCCompiler::CompileComparisonOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8484. {
  8485. // Both operands must be of the same type
  8486. // Implicitly convert the operands to a number type
  8487. asCDataType to;
  8488. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  8489. to.SetTokenType(ttDouble);
  8490. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  8491. to.SetTokenType(ttFloat);
  8492. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8493. {
  8494. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() )
  8495. to.SetTokenType(ttInt64);
  8496. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8497. to.SetTokenType(ttUInt64);
  8498. }
  8499. else
  8500. {
  8501. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() ||
  8502. lctx->type.dataType.IsEnumType() || rctx->type.dataType.IsEnumType() )
  8503. to.SetTokenType(ttInt);
  8504. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8505. to.SetTokenType(ttUInt);
  8506. else if( lctx->type.dataType.IsBooleanType() || rctx->type.dataType.IsBooleanType() )
  8507. to.SetTokenType(ttBool);
  8508. }
  8509. // If doing an operation with double constant and float variable, the constant should be converted to float
  8510. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  8511. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  8512. to.SetTokenType(ttFloat);
  8513. // Is it an operation on signed values?
  8514. bool signMismatch = false;
  8515. if( !lctx->type.dataType.IsUnsignedType() || !rctx->type.dataType.IsUnsignedType() )
  8516. {
  8517. if( lctx->type.dataType.GetTokenType() == ttUInt64 )
  8518. {
  8519. if( !lctx->type.isConstant )
  8520. signMismatch = true;
  8521. else if( lctx->type.qwordValue & (I64(1)<<63) )
  8522. signMismatch = true;
  8523. }
  8524. if( lctx->type.dataType.GetTokenType() == ttUInt )
  8525. {
  8526. if( !lctx->type.isConstant )
  8527. signMismatch = true;
  8528. else if( lctx->type.dwordValue & (1<<31) )
  8529. signMismatch = true;
  8530. }
  8531. if( rctx->type.dataType.GetTokenType() == ttUInt64 )
  8532. {
  8533. if( !rctx->type.isConstant )
  8534. signMismatch = true;
  8535. else if( rctx->type.qwordValue & (I64(1)<<63) )
  8536. signMismatch = true;
  8537. }
  8538. if( rctx->type.dataType.GetTokenType() == ttUInt )
  8539. {
  8540. if( !rctx->type.isConstant )
  8541. signMismatch = true;
  8542. else if( rctx->type.dwordValue & (1<<31) )
  8543. signMismatch = true;
  8544. }
  8545. }
  8546. // Check for signed/unsigned mismatch
  8547. if( signMismatch )
  8548. Warning(TXT_SIGNED_UNSIGNED_MISMATCH, node);
  8549. // Do the actual conversion
  8550. asCArray<int> reservedVars;
  8551. rctx->bc.GetVarsUsed(reservedVars);
  8552. if( lctx->type.dataType.IsReference() )
  8553. ConvertToVariableNotIn(lctx, &reservedVars);
  8554. if( rctx->type.dataType.IsReference() )
  8555. ConvertToVariableNotIn(rctx, &reservedVars);
  8556. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8557. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  8558. // Verify that the conversion was successful
  8559. bool ok = true;
  8560. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  8561. {
  8562. asCString str;
  8563. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8564. Error(str.AddressOf(), node);
  8565. ok = false;
  8566. }
  8567. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  8568. {
  8569. asCString str;
  8570. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8571. Error(str.AddressOf(), node);
  8572. ok = false;
  8573. }
  8574. if( !ok )
  8575. {
  8576. // It wasn't possible to get two valid operands, so we just return
  8577. // a boolean result and let the compiler continue.
  8578. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  8579. return;
  8580. }
  8581. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8582. int op = node->tokenType;
  8583. if( !isConstant )
  8584. {
  8585. if( to.IsBooleanType() )
  8586. {
  8587. int op = node->tokenType;
  8588. if( op == ttEqual || op == ttNotEqual )
  8589. {
  8590. // Must convert to temporary variable, because we are changing the value before comparison
  8591. ConvertToTempVariableNotIn(lctx, rctx);
  8592. ConvertToTempVariableNotIn(rctx, lctx);
  8593. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8594. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8595. // Make sure they are equal if not false
  8596. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  8597. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  8598. MergeExprBytecode(ctx, lctx);
  8599. MergeExprBytecode(ctx, rctx);
  8600. ProcessDeferredParams(ctx);
  8601. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  8602. int b = lctx->type.stackOffset;
  8603. int c = rctx->type.stackOffset;
  8604. if( op == ttEqual )
  8605. {
  8606. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  8607. ctx->bc.Instr(asBC_TZ);
  8608. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8609. }
  8610. else if( op == ttNotEqual )
  8611. {
  8612. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  8613. ctx->bc.Instr(asBC_TNZ);
  8614. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8615. }
  8616. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  8617. }
  8618. else
  8619. {
  8620. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  8621. Error(TXT_ILLEGAL_OPERATION, node);
  8622. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 0);
  8623. }
  8624. }
  8625. else
  8626. {
  8627. ConvertToVariableNotIn(lctx, rctx);
  8628. ConvertToVariableNotIn(rctx, lctx);
  8629. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8630. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8631. MergeExprBytecode(ctx, lctx);
  8632. MergeExprBytecode(ctx, rctx);
  8633. ProcessDeferredParams(ctx);
  8634. asEBCInstr iCmp = asBC_CMPi, iT = asBC_TZ;
  8635. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8636. iCmp = asBC_CMPi;
  8637. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8638. iCmp = asBC_CMPu;
  8639. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8640. iCmp = asBC_CMPi64;
  8641. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8642. iCmp = asBC_CMPu64;
  8643. else if( lctx->type.dataType.IsFloatType() )
  8644. iCmp = asBC_CMPf;
  8645. else if( lctx->type.dataType.IsDoubleType() )
  8646. iCmp = asBC_CMPd;
  8647. else
  8648. asASSERT(false);
  8649. if( op == ttEqual )
  8650. iT = asBC_TZ;
  8651. else if( op == ttNotEqual )
  8652. iT = asBC_TNZ;
  8653. else if( op == ttLessThan )
  8654. iT = asBC_TS;
  8655. else if( op == ttLessThanOrEqual )
  8656. iT = asBC_TNP;
  8657. else if( op == ttGreaterThan )
  8658. iT = asBC_TP;
  8659. else if( op == ttGreaterThanOrEqual )
  8660. iT = asBC_TNS;
  8661. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  8662. int b = lctx->type.stackOffset;
  8663. int c = rctx->type.stackOffset;
  8664. ctx->bc.InstrW_W(iCmp, b, c);
  8665. ctx->bc.Instr(iT);
  8666. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8667. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  8668. }
  8669. }
  8670. else
  8671. {
  8672. if( to.IsBooleanType() )
  8673. {
  8674. int op = node->tokenType;
  8675. if( op == ttEqual || op == ttNotEqual )
  8676. {
  8677. // Make sure they are equal if not false
  8678. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  8679. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  8680. asDWORD v = 0;
  8681. if( op == ttEqual )
  8682. {
  8683. v = lctx->type.intValue - rctx->type.intValue;
  8684. if( v == 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  8685. }
  8686. else if( op == ttNotEqual )
  8687. {
  8688. v = lctx->type.intValue - rctx->type.intValue;
  8689. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  8690. }
  8691. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), v);
  8692. }
  8693. else
  8694. {
  8695. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  8696. Error(TXT_ILLEGAL_OPERATION, node);
  8697. }
  8698. }
  8699. else
  8700. {
  8701. int i = 0;
  8702. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8703. {
  8704. int v = lctx->type.intValue - rctx->type.intValue;
  8705. if( v < 0 ) i = -1;
  8706. if( v > 0 ) i = 1;
  8707. }
  8708. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8709. {
  8710. asDWORD v1 = lctx->type.dwordValue;
  8711. asDWORD v2 = rctx->type.dwordValue;
  8712. if( v1 < v2 ) i = -1;
  8713. if( v1 > v2 ) i = 1;
  8714. }
  8715. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8716. {
  8717. asINT64 v = asINT64(lctx->type.qwordValue) - asINT64(rctx->type.qwordValue);
  8718. if( v < 0 ) i = -1;
  8719. if( v > 0 ) i = 1;
  8720. }
  8721. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8722. {
  8723. asQWORD v1 = lctx->type.qwordValue;
  8724. asQWORD v2 = rctx->type.qwordValue;
  8725. if( v1 < v2 ) i = -1;
  8726. if( v1 > v2 ) i = 1;
  8727. }
  8728. else if( lctx->type.dataType.IsFloatType() )
  8729. {
  8730. float v = lctx->type.floatValue - rctx->type.floatValue;
  8731. if( v < 0 ) i = -1;
  8732. if( v > 0 ) i = 1;
  8733. }
  8734. else if( lctx->type.dataType.IsDoubleType() )
  8735. {
  8736. double v = lctx->type.doubleValue - rctx->type.doubleValue;
  8737. if( v < 0 ) i = -1;
  8738. if( v > 0 ) i = 1;
  8739. }
  8740. if( op == ttEqual )
  8741. i = (i == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8742. else if( op == ttNotEqual )
  8743. i = (i != 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8744. else if( op == ttLessThan )
  8745. i = (i < 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8746. else if( op == ttLessThanOrEqual )
  8747. i = (i <= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8748. else if( op == ttGreaterThan )
  8749. i = (i > 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8750. else if( op == ttGreaterThanOrEqual )
  8751. i = (i >= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8752. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), i);
  8753. }
  8754. }
  8755. }
  8756. void asCCompiler::PushVariableOnStack(asSExprContext *ctx, bool asReference)
  8757. {
  8758. // Put the result on the stack
  8759. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  8760. if( asReference )
  8761. ctx->type.dataType.MakeReference(true);
  8762. else
  8763. {
  8764. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8765. ctx->bc.Instr(asBC_RDS4);
  8766. else
  8767. ctx->bc.Instr(asBC_RDS8);
  8768. }
  8769. }
  8770. void asCCompiler::CompileBooleanOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8771. {
  8772. // Both operands must be booleans
  8773. asCDataType to;
  8774. to.SetTokenType(ttBool);
  8775. // Do the actual conversion
  8776. asCArray<int> reservedVars;
  8777. rctx->bc.GetVarsUsed(reservedVars);
  8778. lctx->bc.GetVarsUsed(reservedVars);
  8779. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8780. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, &reservedVars);
  8781. // Verify that the conversion was successful
  8782. if( !lctx->type.dataType.IsBooleanType() )
  8783. {
  8784. asCString str;
  8785. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), "bool");
  8786. Error(str.AddressOf(), node);
  8787. // Force the conversion to allow compilation to proceed
  8788. lctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  8789. }
  8790. if( !rctx->type.dataType.IsBooleanType() )
  8791. {
  8792. asCString str;
  8793. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "bool");
  8794. Error(str.AddressOf(), node);
  8795. // Force the conversion to allow compilation to proceed
  8796. rctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  8797. }
  8798. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8799. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  8800. // What kind of operator is it?
  8801. int op = node->tokenType;
  8802. if( op == ttXor )
  8803. {
  8804. if( !isConstant )
  8805. {
  8806. // Must convert to temporary variable, because we are changing the value before comparison
  8807. ConvertToTempVariableNotIn(lctx, rctx);
  8808. ConvertToTempVariableNotIn(rctx, lctx);
  8809. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8810. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8811. // Make sure they are equal if not false
  8812. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  8813. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  8814. MergeExprBytecode(ctx, lctx);
  8815. MergeExprBytecode(ctx, rctx);
  8816. ProcessDeferredParams(ctx);
  8817. int a = AllocateVariable(ctx->type.dataType, true);
  8818. int b = lctx->type.stackOffset;
  8819. int c = rctx->type.stackOffset;
  8820. ctx->bc.InstrW_W_W(asBC_BXOR,a,b,c);
  8821. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  8822. }
  8823. else
  8824. {
  8825. // Make sure they are equal if not false
  8826. #if AS_SIZEOF_BOOL == 1
  8827. if( lctx->type.byteValue != 0 ) lctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  8828. if( rctx->type.byteValue != 0 ) rctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  8829. asBYTE v = 0;
  8830. v = lctx->type.byteValue - rctx->type.byteValue;
  8831. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  8832. ctx->type.isConstant = true;
  8833. ctx->type.byteValue = v;
  8834. #else
  8835. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  8836. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  8837. asDWORD v = 0;
  8838. v = lctx->type.intValue - rctx->type.intValue;
  8839. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  8840. ctx->type.isConstant = true;
  8841. ctx->type.dwordValue = v;
  8842. #endif
  8843. }
  8844. }
  8845. else if( op == ttAnd ||
  8846. op == ttOr )
  8847. {
  8848. if( !isConstant )
  8849. {
  8850. // If or-operator and first value is 1 the second value shouldn't be calculated
  8851. // if and-operator and first value is 0 the second value shouldn't be calculated
  8852. ConvertToVariable(lctx);
  8853. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8854. MergeExprBytecode(ctx, lctx);
  8855. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  8856. int label1 = nextLabel++;
  8857. int label2 = nextLabel++;
  8858. if( op == ttAnd )
  8859. {
  8860. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  8861. ctx->bc.Instr(asBC_ClrHi);
  8862. ctx->bc.InstrDWORD(asBC_JNZ, label1);
  8863. ctx->bc.InstrW_DW(asBC_SetV4, (asWORD)offset, 0);
  8864. ctx->bc.InstrINT(asBC_JMP, label2);
  8865. }
  8866. else if( op == ttOr )
  8867. {
  8868. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  8869. ctx->bc.Instr(asBC_ClrHi);
  8870. ctx->bc.InstrDWORD(asBC_JZ, label1);
  8871. #if AS_SIZEOF_BOOL == 1
  8872. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  8873. #else
  8874. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  8875. #endif
  8876. ctx->bc.InstrINT(asBC_JMP, label2);
  8877. }
  8878. ctx->bc.Label((short)label1);
  8879. ConvertToVariable(rctx);
  8880. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8881. rctx->bc.InstrW_W(asBC_CpyVtoV4, offset, rctx->type.stackOffset);
  8882. MergeExprBytecode(ctx, rctx);
  8883. ctx->bc.Label((short)label2);
  8884. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), offset, true);
  8885. }
  8886. else
  8887. {
  8888. #if AS_SIZEOF_BOOL == 1
  8889. asBYTE v = 0;
  8890. if( op == ttAnd )
  8891. v = lctx->type.byteValue && rctx->type.byteValue;
  8892. else if( op == ttOr )
  8893. v = lctx->type.byteValue || rctx->type.byteValue;
  8894. // Remember the result
  8895. ctx->type.isConstant = true;
  8896. ctx->type.byteValue = v;
  8897. #else
  8898. asDWORD v = 0;
  8899. if( op == ttAnd )
  8900. v = lctx->type.dwordValue && rctx->type.dwordValue;
  8901. else if( op == ttOr )
  8902. v = lctx->type.dwordValue || rctx->type.dwordValue;
  8903. // Remember the result
  8904. ctx->type.isConstant = true;
  8905. ctx->type.dwordValue = v;
  8906. #endif
  8907. }
  8908. }
  8909. }
  8910. void asCCompiler::CompileOperatorOnHandles(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8911. {
  8912. // Process the property accessor as get
  8913. ProcessPropertyGetAccessor(lctx, node);
  8914. ProcessPropertyGetAccessor(rctx, node);
  8915. // Make sure lctx doesn't end up with a variable used in rctx
  8916. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  8917. {
  8918. asCArray<int> vars;
  8919. rctx->bc.GetVarsUsed(vars);
  8920. int offset = AllocateVariable(lctx->type.dataType, true);
  8921. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  8922. ReleaseTemporaryVariable(offset, 0);
  8923. }
  8924. // Warn if not both operands are explicit handles
  8925. if( (node->tokenType == ttEqual || node->tokenType == ttNotEqual) &&
  8926. ((!lctx->type.isExplicitHandle && !(lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE))) ||
  8927. (!rctx->type.isExplicitHandle && !(rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE)))) )
  8928. {
  8929. Warning(TXT_HANDLE_COMPARISON, node);
  8930. }
  8931. // If one of the operands is a value type used as handle, we should look for the opEquals method
  8932. if( ((lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) ||
  8933. (rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE))) &&
  8934. (node->tokenType == ttEqual || node->tokenType == ttIs ||
  8935. node->tokenType == ttNotEqual || node->tokenType == ttNotIs) )
  8936. {
  8937. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  8938. // Find the matching opEquals method
  8939. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  8940. if( r == 0 )
  8941. {
  8942. // Try again by switching the order of the operands
  8943. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  8944. }
  8945. if( r == 1 )
  8946. {
  8947. if( node->tokenType == ttNotEqual || node->tokenType == ttNotIs )
  8948. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  8949. // Success, don't continue
  8950. return;
  8951. }
  8952. else if( r == 0 )
  8953. {
  8954. // Couldn't find opEquals method
  8955. Error(TXT_NO_APPROPRIATE_OPEQUALS, node);
  8956. }
  8957. // Compiler error, don't continue
  8958. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  8959. return;
  8960. }
  8961. // Implicitly convert null to the other type
  8962. asCDataType to;
  8963. if( lctx->type.IsNullConstant() )
  8964. to = rctx->type.dataType;
  8965. else if( rctx->type.IsNullConstant() )
  8966. to = lctx->type.dataType;
  8967. else
  8968. {
  8969. // TODO: Use the common base type
  8970. to = lctx->type.dataType;
  8971. }
  8972. // Need to pop the value if it is a null constant
  8973. if( lctx->type.IsNullConstant() )
  8974. lctx->bc.Pop(AS_PTR_SIZE);
  8975. if( rctx->type.IsNullConstant() )
  8976. rctx->bc.Pop(AS_PTR_SIZE);
  8977. // Convert both sides to explicit handles
  8978. to.MakeHandle(true);
  8979. to.MakeReference(false);
  8980. // Do the conversion
  8981. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  8982. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  8983. // Both operands must be of the same type
  8984. // Verify that the conversion was successful
  8985. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  8986. {
  8987. asCString str;
  8988. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8989. Error(str.AddressOf(), node);
  8990. }
  8991. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  8992. {
  8993. asCString str;
  8994. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8995. Error(str.AddressOf(), node);
  8996. }
  8997. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  8998. int op = node->tokenType;
  8999. if( op == ttEqual || op == ttNotEqual || op == ttIs || op == ttNotIs )
  9000. {
  9001. // If the object handle already is in a variable we must manually pop it from the stack
  9002. if( lctx->type.isVariable )
  9003. lctx->bc.Pop(AS_PTR_SIZE);
  9004. if( rctx->type.isVariable )
  9005. rctx->bc.Pop(AS_PTR_SIZE);
  9006. // TODO: optimize: Treat the object handles as two integers, i.e. don't do REFCPY
  9007. ConvertToVariableNotIn(lctx, rctx);
  9008. ConvertToVariable(rctx);
  9009. MergeExprBytecode(ctx, lctx);
  9010. MergeExprBytecode(ctx, rctx);
  9011. int a = AllocateVariable(ctx->type.dataType, true);
  9012. int b = lctx->type.stackOffset;
  9013. int c = rctx->type.stackOffset;
  9014. // TODO: When saving the bytecode we must be able to determine that this is
  9015. // a comparison with a pointer, so that the instruction can be adapted
  9016. // to the pointer size on the platform that will execute it.
  9017. #ifdef AS_64BIT_PTR
  9018. ctx->bc.InstrW_W(asBC_CMPi64, b, c);
  9019. #else
  9020. ctx->bc.InstrW_W(asBC_CMPi, b, c);
  9021. #endif
  9022. if( op == ttEqual || op == ttIs )
  9023. ctx->bc.Instr(asBC_TZ);
  9024. else if( op == ttNotEqual || op == ttNotIs )
  9025. ctx->bc.Instr(asBC_TNZ);
  9026. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9027. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9028. ReleaseTemporaryVariable(lctx->type, &ctx->bc);
  9029. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  9030. ProcessDeferredParams(ctx);
  9031. }
  9032. else
  9033. {
  9034. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  9035. Error(TXT_ILLEGAL_OPERATION, node);
  9036. }
  9037. }
  9038. void asCCompiler::PerformFunctionCall(int funcId, asSExprContext *ctx, bool isConstructor, asCArray<asSExprContext*> *args, asCObjectType *objType, bool useVariable, int varOffset, int funcPtrVar)
  9039. {
  9040. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  9041. // Check if the function is private
  9042. if( descr->isPrivate && descr->GetObjectType() != outFunc->GetObjectType() )
  9043. {
  9044. asCString msg;
  9045. msg.Format(TXT_PRIVATE_METHOD_CALL_s, descr->GetDeclarationStr().AddressOf());
  9046. Error(msg.AddressOf(), ctx->exprNode);
  9047. }
  9048. int argSize = descr->GetSpaceNeededForArguments();
  9049. if( descr->objectType && descr->returnType.IsReference() &&
  9050. !ctx->type.isVariable && (ctx->type.dataType.IsObjectHandle() || ctx->type.dataType.SupportHandles()) &&
  9051. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_SCOPED) &&
  9052. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_ASHANDLE) )
  9053. {
  9054. // The class method we're calling is returning a reference, which may be to a member of the object.
  9055. // In order to guarantee the lifetime of the reference, we must hold a local reference to the object.
  9056. // TODO: optimize: This can be avoided for local variables (non-handles) as they have a well defined life time
  9057. int tempRef = AllocateVariable(ctx->type.dataType, true);
  9058. ctx->bc.InstrSHORT(asBC_PSF, (short)tempRef);
  9059. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  9060. // Add the release of this reference, as a deferred expression
  9061. asSDeferredParam deferred;
  9062. deferred.origExpr = 0;
  9063. deferred.argInOutFlags = asTM_INREF;
  9064. deferred.argNode = 0;
  9065. deferred.argType.SetVariable(ctx->type.dataType, tempRef, true);
  9066. ctx->deferredParams.PushLast(deferred);
  9067. }
  9068. ctx->type.Set(descr->returnType);
  9069. if( isConstructor )
  9070. {
  9071. // Sometimes the value types are allocated on the heap,
  9072. // which is when this way of constructing them is used.
  9073. asASSERT(useVariable == false);
  9074. ctx->bc.Alloc(asBC_ALLOC, objType, descr->id, argSize+AS_PTR_SIZE);
  9075. // The instruction has already moved the returned object to the variable
  9076. ctx->type.Set(asCDataType::CreatePrimitive(ttVoid, false));
  9077. ctx->type.isLValue = false;
  9078. // Clean up arguments
  9079. if( args )
  9080. AfterFunctionCall(funcId, *args, ctx, false);
  9081. ProcessDeferredParams(ctx);
  9082. return;
  9083. }
  9084. else if( descr->funcType == asFUNC_IMPORTED )
  9085. ctx->bc.Call(asBC_CALLBND , descr->id, argSize + (descr->objectType ? AS_PTR_SIZE : 0));
  9086. // TODO: Maybe we need two different byte codes
  9087. else if( descr->funcType == asFUNC_INTERFACE || descr->funcType == asFUNC_VIRTUAL )
  9088. ctx->bc.Call(asBC_CALLINTF, descr->id, argSize + (descr->objectType ? AS_PTR_SIZE : 0));
  9089. else if( descr->funcType == asFUNC_SCRIPT )
  9090. ctx->bc.Call(asBC_CALL , descr->id, argSize + (descr->objectType ? AS_PTR_SIZE : 0));
  9091. else if( descr->funcType == asFUNC_SYSTEM )
  9092. ctx->bc.Call(asBC_CALLSYS , descr->id, argSize + (descr->objectType ? AS_PTR_SIZE : 0));
  9093. else if( descr->funcType == asFUNC_FUNCDEF )
  9094. ctx->bc.CallPtr(asBC_CallPtr, funcPtrVar, argSize);
  9095. if( ctx->type.dataType.IsObject() && !descr->returnType.IsReference() )
  9096. {
  9097. int returnOffset = 0;
  9098. if( useVariable )
  9099. {
  9100. // Use the given variable
  9101. returnOffset = varOffset;
  9102. ctx->type.SetVariable(descr->returnType, returnOffset, false);
  9103. }
  9104. else
  9105. {
  9106. // Allocate a temporary variable for the returned object
  9107. // The returned object will actually be allocated on the heap, so
  9108. // we must force the allocation of the variable to do the same
  9109. returnOffset = AllocateVariable(descr->returnType, true, true);
  9110. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  9111. }
  9112. ctx->type.dataType.MakeReference(true);
  9113. ctx->type.isLValue = false; // It is a reference, but not an lvalue
  9114. // Move the pointer from the object register to the temporary variable
  9115. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  9116. // Clean up arguments
  9117. if( args )
  9118. AfterFunctionCall(funcId, *args, ctx, false);
  9119. ProcessDeferredParams(ctx);
  9120. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  9121. }
  9122. else if( descr->returnType.IsReference() )
  9123. {
  9124. asASSERT(useVariable == false);
  9125. // We cannot clean up the arguments yet, because the
  9126. // reference might be pointing to one of them.
  9127. // Clean up arguments
  9128. if( args )
  9129. AfterFunctionCall(funcId, *args, ctx, true);
  9130. // Do not process the output parameters yet, because it
  9131. // might invalidate the returned reference
  9132. if( descr->returnType.IsPrimitive() )
  9133. ctx->type.Set(descr->returnType);
  9134. else
  9135. {
  9136. ctx->bc.Instr(asBC_PshRPtr);
  9137. if( descr->returnType.IsObject() &&
  9138. (!descr->returnType.IsObjectHandle() || (descr->returnType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  9139. {
  9140. // We are getting the pointer to the object
  9141. // not a pointer to a object variable
  9142. ctx->type.dataType.MakeReference(false);
  9143. }
  9144. }
  9145. // A returned reference can be used as lvalue
  9146. ctx->type.isLValue = true;
  9147. }
  9148. else
  9149. {
  9150. asASSERT(useVariable == false);
  9151. if( descr->returnType.GetSizeInMemoryBytes() )
  9152. {
  9153. // Allocate a temporary variable to hold the value, but make sure
  9154. // the temporary variable isn't used in any of the deferred arguments
  9155. asCArray<int> vars;
  9156. for( asUINT n = 0; args && n < args->GetLength(); n++ )
  9157. {
  9158. asSExprContext *expr = (*args)[n]->origExpr;
  9159. if( expr )
  9160. expr->bc.GetVarsUsed(vars);
  9161. }
  9162. int offset = AllocateVariableNotIn(descr->returnType, true, &vars);
  9163. ctx->type.SetVariable(descr->returnType, offset, true);
  9164. // Move the value from the return register to the variable
  9165. if( descr->returnType.GetSizeOnStackDWords() == 1 )
  9166. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)offset);
  9167. else if( descr->returnType.GetSizeOnStackDWords() == 2 )
  9168. ctx->bc.InstrSHORT(asBC_CpyRtoV8, (short)offset);
  9169. }
  9170. else
  9171. ctx->type.Set(descr->returnType);
  9172. ctx->type.isLValue = false;
  9173. // Clean up arguments
  9174. if( args )
  9175. AfterFunctionCall(funcId, *args, ctx, false);
  9176. ProcessDeferredParams(ctx);
  9177. }
  9178. }
  9179. // This only merges the bytecode, but doesn't modify the type of the final context
  9180. void asCCompiler::MergeExprBytecode(asSExprContext *before, asSExprContext *after)
  9181. {
  9182. before->bc.AddCode(&after->bc);
  9183. for( asUINT n = 0; n < after->deferredParams.GetLength(); n++ )
  9184. {
  9185. before->deferredParams.PushLast(after->deferredParams[n]);
  9186. after->deferredParams[n].origExpr = 0;
  9187. }
  9188. after->deferredParams.SetLength(0);
  9189. }
  9190. // This merges both bytecode and the type of the final context
  9191. void asCCompiler::MergeExprBytecodeAndType(asSExprContext *before, asSExprContext *after)
  9192. {
  9193. MergeExprBytecode(before, after);
  9194. before->type = after->type;
  9195. before->property_get = after->property_get;
  9196. before->property_set = after->property_set;
  9197. before->property_const = after->property_const;
  9198. before->property_handle = after->property_handle;
  9199. before->property_ref = after->property_ref;
  9200. before->property_arg = after->property_arg;
  9201. before->exprNode = after->exprNode;
  9202. after->property_arg = 0;
  9203. // Do not copy the origExpr member
  9204. }
  9205. void asCCompiler::FilterConst(asCArray<int> &funcs)
  9206. {
  9207. if( funcs.GetLength() == 0 ) return;
  9208. // This is only done for object methods
  9209. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[0]);
  9210. if( desc->objectType == 0 ) return;
  9211. // Check if there are any non-const matches
  9212. asUINT n;
  9213. bool foundNonConst = false;
  9214. for( n = 0; n < funcs.GetLength(); n++ )
  9215. {
  9216. desc = builder->GetFunctionDescription(funcs[n]);
  9217. if( !desc->isReadOnly )
  9218. {
  9219. foundNonConst = true;
  9220. break;
  9221. }
  9222. }
  9223. if( foundNonConst )
  9224. {
  9225. // Remove all const methods
  9226. for( n = 0; n < funcs.GetLength(); n++ )
  9227. {
  9228. desc = builder->GetFunctionDescription(funcs[n]);
  9229. if( desc->isReadOnly )
  9230. {
  9231. if( n == funcs.GetLength() - 1 )
  9232. funcs.PopLast();
  9233. else
  9234. funcs[n] = funcs.PopLast();
  9235. n--;
  9236. }
  9237. }
  9238. }
  9239. }
  9240. END_AS_NAMESPACE