as_compiler.cpp 388 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2013 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. // Modified by Lasse Oorni for Urho3D
  24. //
  25. // as_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. #ifndef AS_NO_COMPILER
  32. #include "as_compiler.h"
  33. #include "as_tokendef.h"
  34. #include "as_tokenizer.h"
  35. #include "as_string_util.h"
  36. #include "as_texts.h"
  37. #include "as_parser.h"
  38. #include "as_debug.h"
  39. BEGIN_AS_NAMESPACE
  40. //
  41. // The calling convention rules for script functions:
  42. // - If a class method returns a reference, the caller must guarantee the object pointer stays alive until the function returns, and the reference is no longer going to be used
  43. // - If a class method doesn't return a reference, it must guarantee by itself that the this pointer stays alive during the function call. If no outside access is made, then the function is guaranteed to stay alive and nothing needs to be done
  44. // - The object pointer is always passed as the first argument, position 0
  45. // - If the function returns a value type the caller must reserve the memory for this and pass the pointer as the first argument after the object pointer
  46. //
  47. // TODO: I must correct the interpretation of a references to objects in the compiler.
  48. // A reference should mean that a pointer to the object is on the stack.
  49. // No expression should end up as non-references to objects, as the actual object is
  50. // never put on the stack.
  51. // Local variables are declared as non-references, but the expression should be a reference to the variable.
  52. // Function parameters of called functions can also be non-references, but in that case it means the
  53. // object will be passed by value (currently on the heap, which will be moved to the application stack).
  54. //
  55. // The compiler shouldn't use the asCDataType::IsReference. The datatype should always be stored as non-references.
  56. // Instead the compiler should keep track of references in TypeInfo, where it should also state how the reference
  57. // is currently stored, i.e. in variable, in register, on stack, etc.
  58. asCCompiler::asCCompiler(asCScriptEngine *engine) : byteCode(engine)
  59. {
  60. builder = 0;
  61. script = 0;
  62. variables = 0;
  63. isProcessingDeferredParams = false;
  64. isCompilingDefaultArg = false;
  65. noCodeOutput = 0;
  66. }
  67. asCCompiler::~asCCompiler()
  68. {
  69. while( variables )
  70. {
  71. asCVariableScope *var = variables;
  72. variables = variables->parent;
  73. asDELETE(var,asCVariableScope);
  74. }
  75. }
  76. void asCCompiler::Reset(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  77. {
  78. this->builder = builder;
  79. this->engine = builder->engine;
  80. this->script = script;
  81. this->outFunc = outFunc;
  82. hasCompileErrors = false;
  83. m_isConstructor = false;
  84. m_isConstructorCalled = false;
  85. m_classDecl = 0;
  86. nextLabel = 0;
  87. breakLabels.SetLength(0);
  88. continueLabels.SetLength(0);
  89. byteCode.ClearAll();
  90. }
  91. int asCCompiler::CompileDefaultConstructor(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, asCScriptFunction *outFunc, sClassDeclaration *classDecl)
  92. {
  93. Reset(builder, script, outFunc);
  94. m_classDecl = classDecl;
  95. // Insert a JitEntry at the start of the function for JIT compilers
  96. byteCode.InstrPTR(asBC_JitEntry, 0);
  97. // Add a variable scope that might be needed to declare dummy variables
  98. // in case the member initialization refers to undefined symbols.
  99. AddVariableScope();
  100. // Initialize the class members that have no explicit expression first. This will allow the
  101. // base class' constructor to access these members without worry they will be uninitialized.
  102. // This can happen if the base class' constructor calls a method that is overridden by the derived class
  103. CompileMemberInitialization(&byteCode, true);
  104. // If the class is derived from another, then the base class' default constructor must be called
  105. if( outFunc->objectType->derivedFrom )
  106. {
  107. // Make sure the base class really has a default constructor
  108. if( outFunc->objectType->derivedFrom->beh.construct == 0 )
  109. Error(TEXT_BASE_DOESNT_HAVE_DEF_CONSTR, node);
  110. // Call the base class' default constructor
  111. byteCode.InstrSHORT(asBC_PSF, 0);
  112. byteCode.Instr(asBC_RDSPtr);
  113. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  114. }
  115. // Initialize the class members that explicit expressions afterwards. This allow the expressions
  116. // to access the base class members without worry they will be uninitialized
  117. CompileMemberInitialization(&byteCode, false);
  118. byteCode.OptimizeLocally(tempVariableOffsets);
  119. // If there are compile errors, there is no reason to build the final code
  120. if( hasCompileErrors )
  121. return -1;
  122. // Pop the object pointer from the stack
  123. byteCode.Ret(AS_PTR_SIZE);
  124. // Count total variable size
  125. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  126. outFunc->variableSpace = varSize;
  127. FinalizeFunction();
  128. #ifdef AS_DEBUG
  129. // DEBUG: output byte code
  130. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + "__defconstr.txt").AddressOf(), engine, outFunc);
  131. #endif
  132. return 0;
  133. }
  134. int asCCompiler::CompileFactory(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  135. {
  136. Reset(builder, script, outFunc);
  137. // Insert a JitEntry at the start of the function for JIT compilers
  138. byteCode.InstrPTR(asBC_JitEntry, 0);
  139. // Find the corresponding constructor
  140. asCDataType dt = asCDataType::CreateObject(outFunc->returnType.GetObjectType(), false);
  141. int constructor = 0;
  142. for( unsigned int n = 0; n < dt.GetBehaviour()->factories.GetLength(); n++ )
  143. {
  144. if( dt.GetBehaviour()->factories[n] == outFunc->id )
  145. {
  146. constructor = dt.GetBehaviour()->constructors[n];
  147. break;
  148. }
  149. }
  150. // Allocate the class and instanciate it with the constructor
  151. int varOffset = AllocateVariable(dt, true);
  152. outFunc->variableSpace = AS_PTR_SIZE;
  153. byteCode.InstrSHORT(asBC_PSF, (short)varOffset);
  154. // Copy all arguments to the top of the stack
  155. // TODO: runtime optimize: Might be interesting to have a specific instruction for copying all arguments
  156. int offset = (int)outFunc->GetSpaceNeededForArguments();
  157. for( int a = int(outFunc->parameterTypes.GetLength()) - 1; a >= 0; a-- )
  158. {
  159. if( !outFunc->parameterTypes[a].IsPrimitive() ||
  160. outFunc->parameterTypes[a].IsReference() )
  161. {
  162. offset -= AS_PTR_SIZE;
  163. byteCode.InstrSHORT(asBC_PshVPtr, short(-offset));
  164. }
  165. else
  166. {
  167. if( outFunc->parameterTypes[a].GetSizeOnStackDWords() == 2 )
  168. {
  169. offset -= 2;
  170. byteCode.InstrSHORT(asBC_PshV8, short(-offset));
  171. }
  172. else
  173. {
  174. offset -= 1;
  175. byteCode.InstrSHORT(asBC_PshV4, short(-offset));
  176. }
  177. }
  178. }
  179. int argDwords = (int)outFunc->GetSpaceNeededForArguments();
  180. byteCode.Alloc(asBC_ALLOC, dt.GetObjectType(), constructor, argDwords + AS_PTR_SIZE);
  181. // Return a handle to the newly created object
  182. byteCode.InstrSHORT(asBC_LOADOBJ, (short)varOffset);
  183. byteCode.Ret(argDwords);
  184. FinalizeFunction();
  185. // Tell the virtual machine not to clean up parameters on exception
  186. outFunc->dontCleanUpOnException = true;
  187. /*
  188. #ifdef AS_DEBUG
  189. // DEBUG: output byte code
  190. asCString args;
  191. args.Format("%d", outFunc->parameterTypes.GetLength());
  192. byteCode.DebugOutput(("__" + outFunc->name + "__factory" + args + ".txt").AddressOf(), engine);
  193. #endif
  194. */
  195. return 0;
  196. }
  197. void asCCompiler::FinalizeFunction()
  198. {
  199. TimeIt("asCCompiler::FinalizeFunction");
  200. asUINT n;
  201. // Finalize the bytecode
  202. byteCode.Finalize(tempVariableOffsets);
  203. byteCode.ExtractObjectVariableInfo(outFunc);
  204. // Compile the list of object variables for the exception handler
  205. // Start with the variables allocated on the heap, and then the ones allocated on the stack
  206. for( n = 0; n < variableAllocations.GetLength(); n++ )
  207. {
  208. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  209. {
  210. if( variableIsOnHeap[n] )
  211. {
  212. outFunc->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  213. outFunc->funcVariableTypes.PushLast(variableAllocations[n].GetFuncDef());
  214. outFunc->objVariablePos.PushLast(GetVariableOffset(n));
  215. }
  216. }
  217. }
  218. outFunc->objVariablesOnHeap = asUINT(outFunc->objVariablePos.GetLength());
  219. for( n = 0; n < variableAllocations.GetLength(); n++ )
  220. {
  221. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  222. {
  223. if( !variableIsOnHeap[n] )
  224. {
  225. outFunc->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  226. outFunc->funcVariableTypes.PushLast(variableAllocations[n].GetFuncDef());
  227. outFunc->objVariablePos.PushLast(GetVariableOffset(n));
  228. }
  229. }
  230. }
  231. // Copy byte code to the function
  232. asASSERT( outFunc->byteCode.GetLength() == 0 );
  233. outFunc->byteCode.SetLength(byteCode.GetSize());
  234. byteCode.Output(outFunc->byteCode.AddressOf());
  235. outFunc->AddReferences();
  236. outFunc->stackNeeded = byteCode.largestStackUsed + outFunc->variableSpace;
  237. outFunc->lineNumbers = byteCode.lineNumbers;
  238. // Extract the script section indexes too if there are any entries that are different from the function's script section
  239. int lastIdx = outFunc->scriptSectionIdx;
  240. for( n = 0; n < byteCode.sectionIdxs.GetLength(); n++ )
  241. {
  242. if( byteCode.sectionIdxs[n] != lastIdx )
  243. {
  244. lastIdx = byteCode.sectionIdxs[n];
  245. outFunc->sectionIdxs.PushLast(byteCode.lineNumbers[n*2]);
  246. outFunc->sectionIdxs.PushLast(lastIdx);
  247. }
  248. }
  249. }
  250. // internal
  251. int asCCompiler::SetupParametersAndReturnVariable(asCArray<asCString> &parameterNames, asCScriptNode *func)
  252. {
  253. int stackPos = 0;
  254. if( outFunc->objectType )
  255. stackPos = -AS_PTR_SIZE; // The first parameter is the pointer to the object
  256. // Add the first variable scope, which the parameters and
  257. // variables declared in the outermost statement block is
  258. // part of.
  259. AddVariableScope();
  260. bool isDestructor = false;
  261. asCDataType returnType;
  262. // Examine return type
  263. returnType = outFunc->returnType;
  264. // Check if this is a constructor or destructor
  265. if( returnType.GetTokenType() == ttVoid && outFunc->objectType )
  266. {
  267. if( outFunc->name[0] == '~' )
  268. isDestructor = true;
  269. else if( outFunc->objectType->name == outFunc->name )
  270. m_isConstructor = true;
  271. }
  272. // Is the return type allowed?
  273. if( (!returnType.CanBeInstanciated() && returnType != asCDataType::CreatePrimitive(ttVoid, false)) ||
  274. (returnType.IsReference() && !returnType.CanBeInstanciated()) )
  275. {
  276. // TODO: Hasn't this been validated by the builder already?
  277. asCString str;
  278. str.Format(TXT_RETURN_CANT_BE_s, returnType.Format().AddressOf());
  279. Error(str, func);
  280. }
  281. // If the return type is a value type returned by value the address of the
  282. // location where the value will be stored is pushed on the stack before
  283. // the arguments
  284. if( !(isDestructor || m_isConstructor) && outFunc->DoesReturnOnStack() )
  285. stackPos -= AS_PTR_SIZE;
  286. asCVariableScope vs(0);
  287. // Declare parameters
  288. asUINT n;
  289. for( n = 0; n < parameterNames.GetLength(); n++ )
  290. {
  291. // Get the parameter type
  292. asCDataType &type = outFunc->parameterTypes[n];
  293. asETypeModifiers inoutFlag = outFunc->inOutFlags[n];
  294. // Is the data type allowed?
  295. // TODO: Hasn't this been validated by the builder already?
  296. if( (type.IsReference() && inoutFlag != asTM_INOUTREF && !type.CanBeInstanciated()) ||
  297. (!type.IsReference() && !type.CanBeInstanciated()) )
  298. {
  299. asCString parm = type.Format();
  300. if( inoutFlag == asTM_INREF )
  301. parm += "in";
  302. else if( inoutFlag == asTM_OUTREF )
  303. parm += "out";
  304. asCString str;
  305. str.Format(TXT_PARAMETER_CANT_BE_s, parm.AddressOf());
  306. Error(str, func);
  307. }
  308. // If the parameter has a name then declare it as variable
  309. if( parameterNames[n] != "" )
  310. {
  311. asCString &name = parameterNames[n];
  312. if( vs.DeclareVariable(name.AddressOf(), type, stackPos, true) < 0 )
  313. {
  314. // TODO: It might be an out-of-memory too
  315. Error(TXT_PARAMETER_ALREADY_DECLARED, func);
  316. }
  317. // Add marker for variable declaration
  318. byteCode.VarDecl((int)outFunc->variables.GetLength());
  319. outFunc->AddVariable(name, type, stackPos);
  320. }
  321. else
  322. vs.DeclareVariable("", type, stackPos, true);
  323. // Move to next parameter
  324. stackPos -= type.GetSizeOnStackDWords();
  325. }
  326. for( n = asUINT(vs.variables.GetLength()); n-- > 0; )
  327. variables->DeclareVariable(vs.variables[n]->name.AddressOf(), vs.variables[n]->type, vs.variables[n]->stackOffset, vs.variables[n]->onHeap);
  328. variables->DeclareVariable("return", returnType, stackPos, true);
  329. return stackPos;
  330. }
  331. void asCCompiler::CompileMemberInitialization(asCByteCode *byteCode, bool onlyDefaults)
  332. {
  333. asASSERT( m_classDecl );
  334. // Initialize each member in the order they were declared
  335. for( asUINT n = 0; n < outFunc->objectType->properties.GetLength(); n++ )
  336. {
  337. asCObjectProperty *prop = outFunc->objectType->properties[n];
  338. // Check if the property has an initialization expression
  339. asCScriptNode *declNode = 0;
  340. asCScriptNode *initNode = 0;
  341. asCScriptCode *initScript = 0;
  342. for( asUINT m = 0; m < m_classDecl->propInits.GetLength(); m++ )
  343. {
  344. if( m_classDecl->propInits[m].name == prop->name )
  345. {
  346. declNode = m_classDecl->propInits[m].declNode;
  347. initNode = m_classDecl->propInits[m].initNode;
  348. initScript = m_classDecl->propInits[m].file;
  349. break;
  350. }
  351. }
  352. // If declNode is null, the property was inherited in which case
  353. // it was already initialized by the base class' constructor
  354. if( declNode )
  355. {
  356. if( initNode )
  357. {
  358. if( onlyDefaults )
  359. continue;
  360. #ifdef AS_NO_MEMBER_INIT
  361. // Give an error as the initialization in the declaration has been disabled
  362. asCScriptCode *origScript = script;
  363. script = initScript;
  364. Error("Initialization of members in declaration is not supported", initNode);
  365. script = origScript;
  366. // Clear the initialization node
  367. initNode = 0;
  368. initScript = script;
  369. #else
  370. // Re-parse the initialization expression as the parser now knows the types, which it didn't earlier
  371. asCParser parser(builder);
  372. int r = parser.ParseVarInit(initScript, initNode);
  373. if( r < 0 )
  374. continue;
  375. initNode = parser.GetScriptNode();
  376. #endif
  377. }
  378. else
  379. {
  380. if( !onlyDefaults )
  381. continue;
  382. }
  383. #ifdef AS_NO_MEMBER_INIT
  384. // The initialization will be done in the asCScriptObject constructor, so
  385. // here we should just validate that the member has a default constructor
  386. if( prop->type.IsObject() &&
  387. !prop->type.IsObjectHandle() &&
  388. (((prop->type.GetObjectType()->flags & asOBJ_REF) &&
  389. prop->type.GetBehaviour()->factory == 0) ||
  390. ((prop->type.GetObjectType()->flags & asOBJ_VALUE) &&
  391. prop->type.GetBehaviour()->construct == 0 &&
  392. !(prop->type.GetObjectType()->flags & asOBJ_POD))) )
  393. {
  394. // Class has no default factory/constructor.
  395. asCString str;
  396. // TODO: funcdef: asCDataType should have a GetTypeName()
  397. if( prop->type.GetFuncDef() )
  398. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, prop->type.GetFuncDef()->GetName());
  399. else
  400. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, prop->type.GetObjectType()->GetName());
  401. Error(str, declNode);
  402. }
  403. #else
  404. // Temporarily set the script that is being compiled to where the member initialization is declared.
  405. // The script can be different when including mixin classes from a different script section
  406. asCScriptCode *origScript = script;
  407. script = initScript;
  408. // Add a line instruction with the position of the declaration
  409. LineInstr(byteCode, declNode->tokenPos);
  410. // Compile the initialization
  411. asQWORD constantValue;
  412. asCByteCode bc(engine);
  413. CompileInitialization(initNode, &bc, prop->type, declNode, prop->byteOffset, &constantValue, 2);
  414. byteCode->AddCode(&bc);
  415. script = origScript;
  416. #endif
  417. }
  418. }
  419. }
  420. // Entry
  421. int asCCompiler::CompileFunction(asCBuilder *builder, asCScriptCode *script, asCArray<asCString> &parameterNames, asCScriptNode *func, asCScriptFunction *outFunc, sClassDeclaration *classDecl)
  422. {
  423. TimeIt("asCCompiler::CompileFunction");
  424. Reset(builder, script, outFunc);
  425. int buildErrors = builder->numErrors;
  426. int stackPos = SetupParametersAndReturnVariable(parameterNames, func);
  427. //--------------------------------------------
  428. // Compile the statement block
  429. if( m_isConstructor )
  430. m_classDecl = classDecl;
  431. // We need to parse the statement block now
  432. asCScriptNode *blockBegin;
  433. // If the function signature was implicit, e.g. virtual property
  434. // accessor, then the received node already is the statement block
  435. if( func->nodeType != snStatementBlock )
  436. blockBegin = func->lastChild;
  437. else
  438. blockBegin = func;
  439. // TODO: memory: We can parse the statement block one statement at a time, thus save even more memory
  440. // TODO: optimize: For large functions, the parsing of the statement block can take a long time. Presumably because a lot of memory needs to be allocated
  441. asCParser parser(builder);
  442. int r = parser.ParseStatementBlock(script, blockBegin);
  443. if( r < 0 ) return -1;
  444. asCScriptNode *block = parser.GetScriptNode();
  445. // Reserve a label for the cleanup code
  446. nextLabel++;
  447. bool hasReturn;
  448. asCByteCode bc(engine);
  449. LineInstr(&bc, blockBegin->tokenPos);
  450. CompileStatementBlock(block, false, &hasReturn, &bc);
  451. LineInstr(&bc, blockBegin->tokenPos + blockBegin->tokenLength);
  452. // Make sure there is a return in all paths (if not return type is void)
  453. // Don't bother with this check if there are compiler errors, e.g. Unreachable code
  454. if( !hasCompileErrors && outFunc->returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  455. {
  456. if( hasReturn == false )
  457. Error(TXT_NOT_ALL_PATHS_RETURN, blockBegin);
  458. }
  459. //------------------------------------------------
  460. // Concatenate the bytecode
  461. // Insert a JitEntry at the start of the function for JIT compilers
  462. byteCode.InstrPTR(asBC_JitEntry, 0);
  463. if( outFunc->objectType )
  464. {
  465. if( m_isConstructor )
  466. {
  467. if( outFunc->objectType->derivedFrom )
  468. {
  469. // Call the base class' default constructor unless called manually in the code
  470. if( !m_isConstructorCalled )
  471. {
  472. if( outFunc->objectType->derivedFrom->beh.construct )
  473. {
  474. // Initialize members without explicit expression first
  475. CompileMemberInitialization(&byteCode, true);
  476. // Call base class' constructor
  477. asCByteCode tmpBC(engine);
  478. tmpBC.InstrSHORT(asBC_PSF, 0);
  479. tmpBC.Instr(asBC_RDSPtr);
  480. tmpBC.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  481. tmpBC.OptimizeLocally(tempVariableOffsets);
  482. byteCode.AddCode(&tmpBC);
  483. // Add the initialization of the members with explicit expressions
  484. CompileMemberInitialization(&byteCode, false);
  485. }
  486. else
  487. Error(TEXT_BASE_DOESNT_HAVE_DEF_CONSTR, blockBegin);
  488. }
  489. else
  490. {
  491. // Only initialize members that don't have an explicit expression
  492. // The members that are explicitly initialized will be initialized after the call to base class' constructor
  493. CompileMemberInitialization(&byteCode, true);
  494. }
  495. }
  496. else
  497. {
  498. // Add the initialization of the members
  499. CompileMemberInitialization(&byteCode, true);
  500. CompileMemberInitialization(&byteCode, false);
  501. }
  502. }
  503. // Increase the reference for the object pointer, so that it is guaranteed to live during the entire call
  504. if( !m_isConstructor && !outFunc->returnType.IsReference() )
  505. {
  506. // TODO: runtime optimize: If the function is trivial, i.e. doesn't access any outside functions,
  507. // then this is not necessary. If I implement this, then the function needs
  508. // to set a flag so the exception handler doesn't try to release the handle.
  509. // It is not necessary to do this for constructors, as they have no outside references that can be released anyway
  510. // It is not necessary to do this for methods that return references, as the caller is guaranteed to hold a reference to the object
  511. asCByteCode tmpBC(engine);
  512. tmpBC.InstrSHORT(asBC_PSF, 0);
  513. tmpBC.Instr(asBC_RDSPtr);
  514. tmpBC.Call(asBC_CALLSYS, outFunc->objectType->beh.addref, AS_PTR_SIZE);
  515. tmpBC.OptimizeLocally(tempVariableOffsets);
  516. byteCode.AddCode(&tmpBC);
  517. }
  518. }
  519. // Add the code for the statement block
  520. byteCode.AddCode(&bc);
  521. // Count total variable size
  522. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  523. outFunc->variableSpace = varSize;
  524. // Deallocate all local variables
  525. int n;
  526. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  527. {
  528. sVariable *v = variables->variables[n];
  529. if( v->stackOffset > 0 )
  530. {
  531. // Call variables destructors
  532. if( v->name != "return" && v->name != "return address" )
  533. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  534. DeallocateVariable(v->stackOffset);
  535. }
  536. }
  537. // This is the label that return statements jump to
  538. // in order to exit the function
  539. byteCode.Label(0);
  540. // Call destructors for function parameters
  541. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  542. {
  543. sVariable *v = variables->variables[n];
  544. if( v->stackOffset <= 0 )
  545. {
  546. // Call variable destructors here, for variables not yet destroyed
  547. if( v->name != "return" && v->name != "return address" )
  548. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  549. }
  550. // Do not deallocate parameters
  551. }
  552. // Release the object pointer again
  553. if( outFunc->objectType && !m_isConstructor && !outFunc->returnType.IsReference() )
  554. byteCode.InstrW_PTR(asBC_FREE, 0, outFunc->objectType);
  555. // Check if the number of labels in the functions isn't too many to be handled
  556. if( nextLabel >= (1<<15) )
  557. Error(TXT_TOO_MANY_JUMP_LABELS, func);
  558. // If there are compile errors, there is no reason to build the final code
  559. if( hasCompileErrors || builder->numErrors != buildErrors )
  560. return -1;
  561. // At this point there should be no variables allocated
  562. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  563. // Remove the variable scope
  564. RemoveVariableScope();
  565. byteCode.Ret(-stackPos);
  566. FinalizeFunction();
  567. #ifdef AS_DEBUG
  568. // DEBUG: output byte code
  569. if( outFunc->objectType )
  570. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  571. else
  572. byteCode.DebugOutput(("__" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  573. #endif
  574. return 0;
  575. }
  576. int asCCompiler::CallCopyConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asSExprContext *arg, asCScriptNode *node, bool isGlobalVar, bool derefDest)
  577. {
  578. if( !type.IsObject() )
  579. return 0;
  580. // CallCopyConstructor should not be called for object handles.
  581. asASSERT( !type.IsObjectHandle() );
  582. asCArray<asSExprContext*> args;
  583. args.PushLast(arg);
  584. // The reference parameter must be pushed on the stack
  585. asASSERT( arg->type.dataType.GetObjectType() == type.GetObjectType() );
  586. // Since we're calling the copy constructor, we have to trust the function to not do
  587. // anything stupid otherwise we will just enter a loop, as we try to make temporary
  588. // copies of the argument in order to guarantee safety.
  589. if( type.GetObjectType()->flags & asOBJ_REF )
  590. {
  591. asSExprContext ctx(engine);
  592. int func = 0;
  593. asSTypeBehaviour *beh = type.GetBehaviour();
  594. if( beh ) func = beh->copyfactory;
  595. if( func > 0 )
  596. {
  597. if( !isGlobalVar )
  598. {
  599. // Call factory and store the handle in the given variable
  600. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType(), true, offset);
  601. // Pop the reference left by the function call
  602. ctx.bc.Instr(asBC_PopPtr);
  603. }
  604. else
  605. {
  606. // Call factory
  607. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType());
  608. // Store the returned handle in the global variable
  609. ctx.bc.Instr(asBC_RDSPtr);
  610. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  611. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  612. ctx.bc.Instr(asBC_PopPtr);
  613. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  614. }
  615. bc->AddCode(&ctx.bc);
  616. return 0;
  617. }
  618. }
  619. else
  620. {
  621. asSTypeBehaviour *beh = type.GetBehaviour();
  622. int func = beh ? beh->copyconstruct : 0;
  623. if( func > 0 )
  624. {
  625. // Push the address where the object will be stored on the stack, before the argument
  626. // TODO: When the context is serializable this probably has to be changed, since this
  627. // pointer can remain on the stack while the context is suspended. There is no
  628. // risk the pointer becomes invalid though, there is just no easy way to serialize it.
  629. asCByteCode tmp(engine);
  630. if( isGlobalVar )
  631. tmp.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  632. else if( isObjectOnHeap )
  633. tmp.InstrSHORT(asBC_PSF, (short)offset);
  634. tmp.AddCode(bc);
  635. bc->AddCode(&tmp);
  636. // When the object is allocated on the stack the object pointer
  637. // must be pushed on the stack after the arguments
  638. if( !isObjectOnHeap )
  639. {
  640. asASSERT( !isGlobalVar );
  641. bc->InstrSHORT(asBC_PSF, (short)offset);
  642. if( derefDest )
  643. {
  644. // The variable is a reference to the real location, so we need to dereference it
  645. bc->Instr(asBC_RDSPtr);
  646. }
  647. }
  648. asSExprContext ctx(engine);
  649. PerformFunctionCall(func, &ctx, isObjectOnHeap, &args, type.GetObjectType());
  650. bc->AddCode(&ctx.bc);
  651. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  652. // Mark the object as initialized
  653. if( !isObjectOnHeap )
  654. bc->ObjInfo(offset, asOBJ_INIT);
  655. return 0;
  656. }
  657. }
  658. // Class has no copy constructor/factory.
  659. asCString str;
  660. str.Format(TXT_NO_COPY_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  661. Error(str, node);
  662. return -1;
  663. }
  664. int asCCompiler::CallDefaultConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asCScriptNode *node, int isVarGlobOrMem, bool deferDest)
  665. {
  666. if( !type.IsObject() || type.IsObjectHandle() )
  667. return 0;
  668. if( type.GetObjectType()->flags & asOBJ_REF )
  669. {
  670. asSExprContext ctx(engine);
  671. ctx.exprNode = node;
  672. int func = 0;
  673. asSTypeBehaviour *beh = type.GetBehaviour();
  674. if( beh ) func = beh->factory;
  675. if( func > 0 )
  676. {
  677. if( isVarGlobOrMem == 0 )
  678. {
  679. // Call factory and store the handle in the given variable
  680. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType(), true, offset);
  681. // Pop the reference left by the function call
  682. ctx.bc.Instr(asBC_PopPtr);
  683. }
  684. else
  685. {
  686. // Call factory
  687. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  688. // TODO: runtime optimize: Should have a way of storing the object pointer directly to the destination
  689. // instead of first storing it in a local variable and then copying it to the
  690. // destination.
  691. if( !(type.GetObjectType()->flags & asOBJ_SCOPED) )
  692. {
  693. // Only dereference the variable if not a scoped type
  694. ctx.bc.Instr(asBC_RDSPtr);
  695. }
  696. if( isVarGlobOrMem == 1 )
  697. {
  698. // Store the returned handle in the global variable
  699. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  700. }
  701. else
  702. {
  703. // Store the returned handle in the class member
  704. ctx.bc.InstrSHORT(asBC_PSF, 0);
  705. ctx.bc.Instr(asBC_RDSPtr);
  706. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  707. }
  708. if( type.GetObjectType()->flags & asOBJ_SCOPED )
  709. {
  710. // For scoped typed we must move the reference from the local
  711. // variable rather than copy it as there is no AddRef behaviour
  712. ctx.bc.InstrSHORT_DW(asBC_COPY, AS_PTR_SIZE, asTYPEID_OBJHANDLE | engine->GetTypeIdFromDataType(type));
  713. // Clear the local variable so the reference isn't released
  714. ctx.bc.InstrSHORT(asBC_ClrVPtr, ctx.type.stackOffset);
  715. }
  716. else
  717. {
  718. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  719. }
  720. ctx.bc.Instr(asBC_PopPtr);
  721. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  722. }
  723. bc->AddCode(&ctx.bc);
  724. return 0;
  725. }
  726. }
  727. else
  728. {
  729. asSTypeBehaviour *beh = type.GetBehaviour();
  730. int func = 0;
  731. if( beh ) func = beh->construct;
  732. // Allocate and initialize with the default constructor
  733. if( func != 0 || (type.GetObjectType()->flags & asOBJ_POD) )
  734. {
  735. if( !isObjectOnHeap )
  736. {
  737. asASSERT( isVarGlobOrMem == 0 );
  738. // There is nothing to do if there is no function,
  739. // as the memory is already allocated on the stack
  740. if( func )
  741. {
  742. // Call the constructor as a normal function
  743. bc->InstrSHORT(asBC_PSF, (short)offset);
  744. if( deferDest )
  745. bc->Instr(asBC_RDSPtr);
  746. asSExprContext ctx(engine);
  747. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  748. bc->AddCode(&ctx.bc);
  749. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  750. // Mark the object as initialized
  751. bc->ObjInfo(offset, asOBJ_INIT);
  752. }
  753. }
  754. else
  755. {
  756. if( isVarGlobOrMem == 0 )
  757. bc->InstrSHORT(asBC_PSF, (short)offset);
  758. else if( isVarGlobOrMem == 1 )
  759. bc->InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  760. else
  761. {
  762. bc->InstrSHORT(asBC_PSF, 0);
  763. bc->Instr(asBC_RDSPtr);
  764. bc->InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  765. }
  766. bc->Alloc(asBC_ALLOC, type.GetObjectType(), func, AS_PTR_SIZE);
  767. }
  768. return 0;
  769. }
  770. }
  771. // Class has no default factory/constructor.
  772. asCString str;
  773. // TODO: funcdef: asCDataType should have a GetTypeName()
  774. if( type.GetFuncDef() )
  775. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetFuncDef()->GetName());
  776. else
  777. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  778. Error(str, node);
  779. return -1;
  780. }
  781. void asCCompiler::CallDestructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc)
  782. {
  783. if( !type.IsReference() )
  784. {
  785. // Call destructor for the data type
  786. if( type.IsObject() )
  787. {
  788. if( isObjectOnHeap || type.IsObjectHandle() )
  789. {
  790. // Free the memory
  791. bc->InstrW_PTR(asBC_FREE, (short)offset, type.GetObjectType());
  792. }
  793. else
  794. {
  795. asASSERT( type.GetObjectType()->GetFlags() & asOBJ_VALUE );
  796. if( type.GetBehaviour()->destruct )
  797. {
  798. // Call the destructor as a regular function
  799. asSExprContext ctx(engine);
  800. ctx.bc.InstrSHORT(asBC_PSF, (short)offset);
  801. PerformFunctionCall(type.GetBehaviour()->destruct, &ctx);
  802. ctx.bc.OptimizeLocally(tempVariableOffsets);
  803. bc->AddCode(&ctx.bc);
  804. }
  805. // TODO: Value on stack: This probably needs to be done in PerformFunctionCall
  806. // Mark the object as destroyed
  807. bc->ObjInfo(offset, asOBJ_UNINIT);
  808. }
  809. }
  810. }
  811. }
  812. void asCCompiler::LineInstr(asCByteCode *bc, size_t pos)
  813. {
  814. int r, c;
  815. script->ConvertPosToRowCol(pos, &r, &c);
  816. bc->Line(r, c, script->idx);
  817. }
  818. void asCCompiler::CompileStatementBlock(asCScriptNode *block, bool ownVariableScope, bool *hasReturn, asCByteCode *bc)
  819. {
  820. *hasReturn = false;
  821. bool isFinished = false;
  822. bool hasUnreachableCode = false;
  823. bool hasReturnBefore = false;
  824. if( ownVariableScope )
  825. {
  826. bc->Block(true);
  827. AddVariableScope();
  828. }
  829. asCScriptNode *node = block->firstChild;
  830. while( node )
  831. {
  832. if( !hasUnreachableCode && (*hasReturn || isFinished) )
  833. {
  834. // Empty statements don't count
  835. if( node->nodeType != snExpressionStatement || node->firstChild )
  836. {
  837. hasUnreachableCode = true;
  838. Warning(TXT_UNREACHABLE_CODE, node);
  839. }
  840. if( *hasReturn )
  841. hasReturnBefore = true;
  842. }
  843. if( node->nodeType == snBreak || node->nodeType == snContinue )
  844. isFinished = true;
  845. asCByteCode statement(engine);
  846. if( node->nodeType == snDeclaration )
  847. CompileDeclaration(node, &statement);
  848. else
  849. CompileStatement(node, hasReturn, &statement);
  850. // Ignore missing returns in unreachable code paths
  851. if( !(*hasReturn) && hasReturnBefore )
  852. *hasReturn = true;
  853. LineInstr(bc, node->tokenPos);
  854. bc->AddCode(&statement);
  855. if( !hasCompileErrors )
  856. {
  857. asASSERT( tempVariables.GetLength() == 0 );
  858. asASSERT( reservedVariables.GetLength() == 0 );
  859. }
  860. node = node->next;
  861. }
  862. if( ownVariableScope )
  863. {
  864. // Deallocate variables in this block, in reverse order
  865. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  866. {
  867. sVariable *v = variables->variables[n];
  868. // Call variable destructors here, for variables not yet destroyed
  869. // If the block is terminated with a break, continue, or
  870. // return the variables are already destroyed
  871. if( !isFinished && !*hasReturn )
  872. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  873. // Don't deallocate function parameters
  874. if( v->stackOffset > 0 )
  875. DeallocateVariable(v->stackOffset);
  876. }
  877. RemoveVariableScope();
  878. bc->Block(false);
  879. }
  880. }
  881. // Entry
  882. int asCCompiler::CompileGlobalVariable(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, sGlobalVariableDescription *gvar, asCScriptFunction *outFunc)
  883. {
  884. Reset(builder, script, outFunc);
  885. // Add a variable scope (even though variables can't be declared)
  886. AddVariableScope();
  887. gvar->isPureConstant = false;
  888. // Parse the initialization nodes
  889. asCParser parser(builder);
  890. if( node )
  891. {
  892. int r = parser.ParseVarInit(script, node);
  893. if( r < 0 )
  894. return r;
  895. node = parser.GetScriptNode();
  896. }
  897. // Compile the expression
  898. asSExprContext ctx(engine);
  899. asQWORD constantValue;
  900. if( CompileInitialization(node, &ctx.bc, gvar->datatype, gvar->idNode, gvar->index, &constantValue, 1) )
  901. {
  902. // Should the variable be marked as pure constant?
  903. if( gvar->datatype.IsPrimitive() && gvar->datatype.IsReadOnly() )
  904. {
  905. gvar->isPureConstant = true;
  906. gvar->constantValue = constantValue;
  907. }
  908. }
  909. // Concatenate the bytecode
  910. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  911. // Add information on the line number for the global variable
  912. size_t pos = 0;
  913. if( gvar->idNode )
  914. pos = gvar->idNode->tokenPos;
  915. else if( gvar->nextNode )
  916. pos = gvar->nextNode->tokenPos;
  917. LineInstr(&byteCode, pos);
  918. // Reserve space for all local variables
  919. outFunc->variableSpace = varSize;
  920. ctx.bc.OptimizeLocally(tempVariableOffsets);
  921. byteCode.AddCode(&ctx.bc);
  922. // Deallocate variables in this block, in reverse order
  923. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; --n )
  924. {
  925. sVariable *v = variables->variables[n];
  926. // Call variable destructors here, for variables not yet destroyed
  927. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  928. DeallocateVariable(v->stackOffset);
  929. }
  930. if( hasCompileErrors ) return -1;
  931. // At this point there should be no variables allocated
  932. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  933. // Remove the variable scope again
  934. RemoveVariableScope();
  935. byteCode.Ret(0);
  936. FinalizeFunction();
  937. #ifdef AS_DEBUG
  938. // DEBUG: output byte code
  939. byteCode.DebugOutput(("___init_" + gvar->name + ".txt").AddressOf(), engine, outFunc);
  940. #endif
  941. return 0;
  942. }
  943. void asCCompiler::DetermineSingleFunc(asSExprContext *ctx, asCScriptNode *node)
  944. {
  945. // Don't do anything if this is not a deferred global function
  946. if( ctx->methodName == "" || ctx->type.dataType.GetObjectType() != 0 )
  947. return;
  948. // Determine the namespace
  949. asSNameSpace *ns = 0;
  950. asCString name = "";
  951. int pos = ctx->methodName.FindLast("::");
  952. if( pos >= 0 )
  953. {
  954. asCString nsName = ctx->methodName.SubString(0, pos+2);
  955. ns = DetermineNameSpace(nsName);
  956. name = ctx->methodName.SubString(pos+2);
  957. }
  958. else
  959. {
  960. DetermineNameSpace("");
  961. name = ctx->methodName;
  962. }
  963. asCArray<int> funcs;
  964. if( ns )
  965. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  966. // CompileVariableAccess should guarantee that at least one function is exists
  967. asASSERT( funcs.GetLength() > 0 );
  968. if( funcs.GetLength() > 1 )
  969. {
  970. asCString str;
  971. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, ctx->methodName.AddressOf());
  972. Error(str, node);
  973. // Fall through so the compiler can continue as if only one function was matching
  974. }
  975. // A shared object may not access global functions unless they too are shared (e.g. registered functions)
  976. if( !builder->GetFunctionDescription(funcs[0])->IsShared() &&
  977. outFunc->IsShared() )
  978. {
  979. asCString msg;
  980. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, builder->GetFunctionDescription(funcs[0])->GetDeclaration());
  981. Error(msg, node);
  982. // Fall through so the compiler can continue anyway
  983. }
  984. // Push the function pointer on the stack
  985. ctx->bc.InstrPTR(asBC_FuncPtr, builder->GetFunctionDescription(funcs[0]));
  986. ctx->type.Set(asCDataType::CreateFuncDef(builder->GetFunctionDescription(funcs[0])));
  987. ctx->type.dataType.MakeHandle(true);
  988. ctx->type.isExplicitHandle = true;
  989. ctx->methodName = "";
  990. }
  991. void asCCompiler::PrepareArgument(asCDataType *paramType, asSExprContext *ctx, asCScriptNode *node, bool isFunction, int refType, bool isMakingCopy)
  992. {
  993. asCDataType param = *paramType;
  994. if( paramType->GetTokenType() == ttQuestion )
  995. {
  996. // The function is expecting a var type. If the argument is a function name, we must now decide which function it is
  997. DetermineSingleFunc(ctx, node);
  998. // Since the function is expecting a var type ?, then we don't want to convert the argument to anything else
  999. param = ctx->type.dataType;
  1000. param.MakeHandle(ctx->type.isExplicitHandle);
  1001. // Reference types will always be passed as handles to ? parameters
  1002. if( builder->engine->ep.disallowValueAssignForRefType &&
  1003. ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_REF) && !(ctx->type.dataType.GetObjectType()->flags & asOBJ_SCOPED) )
  1004. {
  1005. param.MakeHandle(true);
  1006. }
  1007. param.MakeReference(paramType->IsReference());
  1008. param.MakeReadOnly(paramType->IsReadOnly());
  1009. }
  1010. else
  1011. param = *paramType;
  1012. asCDataType dt = param;
  1013. // Need to protect arguments by reference
  1014. if( isFunction && dt.IsReference() )
  1015. {
  1016. // Allocate a temporary variable of the same type as the argument
  1017. dt.MakeReference(false);
  1018. dt.MakeReadOnly(false);
  1019. int offset;
  1020. if( refType == 1 ) // &in
  1021. {
  1022. ProcessPropertyGetAccessor(ctx, node);
  1023. // Add the type id as hidden arg if the parameter is a ? type
  1024. if( paramType->GetTokenType() == ttQuestion )
  1025. {
  1026. asCByteCode tmpBC(engine);
  1027. // Place the type id on the stack as a hidden parameter
  1028. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  1029. // Insert the code before the expression code
  1030. tmpBC.AddCode(&ctx->bc);
  1031. ctx->bc.AddCode(&tmpBC);
  1032. }
  1033. // If the reference is const, then it is not necessary to make a copy if the value already is a variable
  1034. // Even if the same variable is passed in another argument as non-const then there is no problem
  1035. if( dt.IsPrimitive() || dt.IsNullHandle() )
  1036. {
  1037. IsVariableInitialized(&ctx->type, node);
  1038. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  1039. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true);
  1040. if( !(param.IsReadOnly() && ctx->type.isVariable) )
  1041. ConvertToTempVariable(ctx);
  1042. PushVariableOnStack(ctx, true);
  1043. ctx->type.dataType.MakeReadOnly(param.IsReadOnly());
  1044. }
  1045. else
  1046. {
  1047. IsVariableInitialized(&ctx->type, node);
  1048. if( !isMakingCopy )
  1049. {
  1050. ImplicitConversion(ctx, param, node, asIC_IMPLICIT_CONV, true);
  1051. if( !ctx->type.dataType.IsEqualExceptRef(param) )
  1052. {
  1053. asCString str;
  1054. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), param.Format().AddressOf());
  1055. Error(str, node);
  1056. ctx->type.Set(param);
  1057. }
  1058. }
  1059. // If the argument already is a temporary
  1060. // variable we don't need to allocate another
  1061. // If the parameter is read-only and the object already is a local
  1062. // variable then it is not necessary to make a copy either
  1063. if( !ctx->type.isTemporary && !(param.IsReadOnly() && ctx->type.isVariable) && !isMakingCopy )
  1064. {
  1065. // Make sure the variable is not used in the expression
  1066. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1067. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  1068. // Allocate and construct the temporary object
  1069. asCByteCode tmpBC(engine);
  1070. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  1071. // Insert the code before the expression code
  1072. tmpBC.AddCode(&ctx->bc);
  1073. ctx->bc.AddCode(&tmpBC);
  1074. // Assign the evaluated expression to the temporary variable
  1075. PrepareForAssignment(&dt, ctx, node, true);
  1076. dt.MakeReference(IsVariableOnHeap(offset));
  1077. asCTypeInfo type;
  1078. type.Set(dt);
  1079. type.isTemporary = true;
  1080. type.stackOffset = (short)offset;
  1081. if( dt.IsObjectHandle() )
  1082. type.isExplicitHandle = true;
  1083. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1084. PerformAssignment(&type, &ctx->type, &ctx->bc, node);
  1085. ctx->bc.Instr(asBC_PopPtr);
  1086. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  1087. ctx->type = type;
  1088. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1089. if( dt.IsObject() && !dt.IsObjectHandle() )
  1090. ctx->bc.Instr(asBC_RDSPtr);
  1091. if( paramType->IsReadOnly() )
  1092. ctx->type.dataType.MakeReadOnly(true);
  1093. }
  1094. else if( isMakingCopy )
  1095. {
  1096. // We must guarantee that the address to the value is on the stack
  1097. if( ctx->type.dataType.IsObject() &&
  1098. !ctx->type.dataType.IsObjectHandle() &&
  1099. ctx->type.dataType.IsReference() )
  1100. Dereference(ctx, true);
  1101. }
  1102. }
  1103. }
  1104. else if( refType == 2 ) // &out
  1105. {
  1106. // Add the type id as hidden arg if the parameter is a ? type
  1107. if( paramType->GetTokenType() == ttQuestion )
  1108. {
  1109. asCByteCode tmpBC(engine);
  1110. // Place the type id on the stack as a hidden parameter
  1111. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  1112. // Insert the code before the expression code
  1113. tmpBC.AddCode(&ctx->bc);
  1114. ctx->bc.AddCode(&tmpBC);
  1115. }
  1116. // Make sure the variable is not used in the expression
  1117. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1118. if( dt.IsPrimitive() )
  1119. {
  1120. ctx->type.SetVariable(dt, offset, true);
  1121. PushVariableOnStack(ctx, true);
  1122. }
  1123. else
  1124. {
  1125. // Allocate and construct the temporary object
  1126. asCByteCode tmpBC(engine);
  1127. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  1128. // Insert the code before the expression code
  1129. tmpBC.AddCode(&ctx->bc);
  1130. ctx->bc.AddCode(&tmpBC);
  1131. dt.MakeReference((!dt.IsObject() || dt.IsObjectHandle()));
  1132. asCTypeInfo type;
  1133. type.Set(dt);
  1134. type.isTemporary = true;
  1135. type.stackOffset = (short)offset;
  1136. ctx->type = type;
  1137. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1138. if( dt.IsObject() && !dt.IsObjectHandle() )
  1139. ctx->bc.Instr(asBC_RDSPtr);
  1140. }
  1141. // After the function returns the temporary variable will
  1142. // be assigned to the expression, if it is a valid lvalue
  1143. }
  1144. else if( refType == asTM_INOUTREF )
  1145. {
  1146. ProcessPropertyGetAccessor(ctx, node);
  1147. // Add the type id as hidden arg if the parameter is a ? type
  1148. if( paramType->GetTokenType() == ttQuestion )
  1149. {
  1150. asCByteCode tmpBC(engine);
  1151. // Place the type id on the stack as a hidden parameter
  1152. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  1153. // Insert the code before the expression code
  1154. tmpBC.AddCode(&ctx->bc);
  1155. ctx->bc.AddCode(&tmpBC);
  1156. }
  1157. // Literal constants cannot be passed to inout ref arguments
  1158. if( !ctx->type.isVariable && ctx->type.isConstant )
  1159. {
  1160. Error(TXT_NOT_VALID_REFERENCE, node);
  1161. }
  1162. // Only objects that support object handles
  1163. // can be guaranteed to be safe. Local variables are
  1164. // already safe, so there is no need to add an extra
  1165. // references
  1166. if( !engine->ep.allowUnsafeReferences &&
  1167. !ctx->type.isVariable &&
  1168. ctx->type.dataType.IsObject() &&
  1169. !ctx->type.dataType.IsObjectHandle() &&
  1170. ((ctx->type.dataType.GetBehaviour()->addref &&
  1171. ctx->type.dataType.GetBehaviour()->release) ||
  1172. (ctx->type.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) )
  1173. {
  1174. // Store a handle to the object as local variable
  1175. asSExprContext tmp(engine);
  1176. asCDataType dt = ctx->type.dataType;
  1177. dt.MakeHandle(true);
  1178. dt.MakeReference(false);
  1179. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1180. // Copy the handle
  1181. if( !ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReference() )
  1182. ctx->bc.Instr(asBC_RDSPtr);
  1183. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1184. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  1185. ctx->bc.Instr(asBC_PopPtr);
  1186. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1187. dt.MakeHandle(false);
  1188. dt.MakeReference(true);
  1189. // Release previous temporary variable stored in the context (if any)
  1190. if( ctx->type.isTemporary )
  1191. {
  1192. ReleaseTemporaryVariable(ctx->type.stackOffset, &ctx->bc);
  1193. }
  1194. ctx->type.SetVariable(dt, offset, true);
  1195. }
  1196. // Make sure the reference to the value is on the stack
  1197. // For objects, the reference needs to be dereferenced so the pointer on the stack is to the actual object
  1198. // For handles, the reference shouldn't be changed because the pointer on the stack should be to the handle
  1199. if( ctx->type.dataType.IsObject() && ctx->type.dataType.IsReference() && !paramType->IsObjectHandle() )
  1200. Dereference(ctx, true);
  1201. else if( ctx->type.isVariable && !ctx->type.dataType.IsObject() )
  1202. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  1203. else if( ctx->type.dataType.IsPrimitive() )
  1204. ctx->bc.Instr(asBC_PshRPtr);
  1205. else if( ctx->type.dataType.IsObjectHandle() && !ctx->type.dataType.IsReference() )
  1206. ImplicitConversion(ctx, param, node, asIC_IMPLICIT_CONV, true, false);
  1207. }
  1208. }
  1209. else
  1210. {
  1211. ProcessPropertyGetAccessor(ctx, node);
  1212. if( dt.IsPrimitive() )
  1213. {
  1214. IsVariableInitialized(&ctx->type, node);
  1215. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  1216. // Implicitly convert primitives to the parameter type
  1217. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  1218. if( ctx->type.isVariable )
  1219. {
  1220. PushVariableOnStack(ctx, dt.IsReference());
  1221. }
  1222. else if( ctx->type.isConstant )
  1223. {
  1224. ConvertToVariable(ctx);
  1225. PushVariableOnStack(ctx, dt.IsReference());
  1226. }
  1227. }
  1228. else
  1229. {
  1230. IsVariableInitialized(&ctx->type, node);
  1231. // Implicitly convert primitives to the parameter type
  1232. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  1233. // Was the conversion successful?
  1234. if( !ctx->type.dataType.IsEqualExceptRef(dt) )
  1235. {
  1236. asCString str;
  1237. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), dt.Format().AddressOf());
  1238. Error(str, node);
  1239. ctx->type.Set(dt);
  1240. }
  1241. if( dt.IsObjectHandle() )
  1242. ctx->type.isExplicitHandle = true;
  1243. if( dt.IsObject() )
  1244. {
  1245. if( !dt.IsReference() )
  1246. {
  1247. // Objects passed by value must be placed in temporary variables
  1248. // so that they are guaranteed to not be referenced anywhere else.
  1249. // The object must also be allocated on the heap, as the memory will
  1250. // be deleted by in as_callfunc_xxx.
  1251. // TODO: value on stack: How can we avoid this unnecessary allocation?
  1252. // Local variables doesn't need to be copied into
  1253. // a temp if we're already compiling an assignment
  1254. if( !isMakingCopy || !ctx->type.dataType.IsObjectHandle() || !ctx->type.isVariable )
  1255. PrepareTemporaryObject(node, ctx, true);
  1256. // The implicit conversion shouldn't convert the object to
  1257. // non-reference yet. It will be dereferenced just before the call.
  1258. // Otherwise the object might be missed by the exception handler.
  1259. dt.MakeReference(true);
  1260. }
  1261. else
  1262. {
  1263. // An object passed by reference should place the pointer to
  1264. // the object on the stack.
  1265. dt.MakeReference(false);
  1266. }
  1267. }
  1268. }
  1269. }
  1270. // Don't put any pointer on the stack yet
  1271. if( param.IsReference() || param.IsObject() )
  1272. {
  1273. // &inout parameter may leave the reference on the stack already
  1274. if( refType != 3 )
  1275. {
  1276. asASSERT( ctx->type.isVariable || ctx->type.isTemporary || isMakingCopy );
  1277. if( ctx->type.isVariable || ctx->type.isTemporary )
  1278. {
  1279. ctx->bc.Instr(asBC_PopPtr);
  1280. ctx->bc.InstrSHORT(asBC_VAR, ctx->type.stackOffset);
  1281. ProcessDeferredParams(ctx);
  1282. }
  1283. }
  1284. }
  1285. }
  1286. void asCCompiler::PrepareFunctionCall(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args)
  1287. {
  1288. // When a match has been found, compile the final byte code using correct parameter types
  1289. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1290. // If the function being called is the opAssign or copy constructor for the same type
  1291. // as the argument, then we should avoid making temporary copy of the argument
  1292. bool makingCopy = false;
  1293. if( descr->parameterTypes.GetLength() == 1 &&
  1294. descr->parameterTypes[0].IsEqualExceptRefAndConst(args[0]->type.dataType) &&
  1295. ((descr->name == "opAssign" && descr->objectType && descr->objectType == args[0]->type.dataType.GetObjectType()) ||
  1296. (args[0]->type.dataType.GetObjectType() && descr->name == args[0]->type.dataType.GetObjectType()->name)) )
  1297. makingCopy = true;
  1298. // Add code for arguments
  1299. asSExprContext e(engine);
  1300. for( int n = (int)args.GetLength()-1; n >= 0; n-- )
  1301. {
  1302. // Make sure PrepareArgument doesn't use any variable that is already
  1303. // being used by any of the following argument expressions
  1304. int l = int(reservedVariables.GetLength());
  1305. for( int m = n-1; m >= 0; m-- )
  1306. args[m]->bc.GetVarsUsed(reservedVariables);
  1307. PrepareArgument2(&e, args[n], &descr->parameterTypes[n], true, descr->inOutFlags[n], makingCopy);
  1308. reservedVariables.SetLength(l);
  1309. }
  1310. bc->AddCode(&e.bc);
  1311. }
  1312. void asCCompiler::MoveArgsToStack(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args, bool addOneToOffset)
  1313. {
  1314. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1315. int offset = 0;
  1316. if( addOneToOffset )
  1317. offset += AS_PTR_SIZE;
  1318. // The address of where the return value should be stored is push on top of the arguments
  1319. if( descr->DoesReturnOnStack() )
  1320. offset += AS_PTR_SIZE;
  1321. #ifdef AS_DEBUG
  1322. // If the function being called is the opAssign or copy constructor for the same type
  1323. // as the argument, then we should avoid making temporary copy of the argument
  1324. bool makingCopy = false;
  1325. if( descr->parameterTypes.GetLength() == 1 &&
  1326. descr->parameterTypes[0].IsEqualExceptRefAndConst(args[0]->type.dataType) &&
  1327. ((descr->name == "opAssign" && descr->objectType && descr->objectType == args[0]->type.dataType.GetObjectType()) ||
  1328. (args[0]->type.dataType.GetObjectType() && descr->name == args[0]->type.dataType.GetObjectType()->name)) )
  1329. makingCopy = true;
  1330. #endif
  1331. // Move the objects that are sent by value to the stack just before the call
  1332. for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
  1333. {
  1334. if( descr->parameterTypes[n].IsReference() )
  1335. {
  1336. if( descr->parameterTypes[n].IsObject() && !descr->parameterTypes[n].IsObjectHandle() )
  1337. {
  1338. if( descr->inOutFlags[n] != asTM_INOUTREF )
  1339. {
  1340. #ifdef AS_DEBUG
  1341. asASSERT( args[n]->type.isVariable || args[n]->type.isTemporary || makingCopy );
  1342. #endif
  1343. if( (args[n]->type.isVariable || args[n]->type.isTemporary) )
  1344. {
  1345. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1346. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  1347. // as the value allocated on the stack is guaranteed to be safe
  1348. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1349. else
  1350. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1351. }
  1352. }
  1353. if( args[n]->type.dataType.IsObjectHandle() )
  1354. bc->InstrWORD(asBC_ChkNullS, (asWORD)offset);
  1355. }
  1356. else if( descr->inOutFlags[n] != asTM_INOUTREF )
  1357. {
  1358. if( descr->parameterTypes[n].GetTokenType() == ttQuestion &&
  1359. args[n]->type.dataType.IsObject() && !args[n]->type.dataType.IsObjectHandle() )
  1360. {
  1361. // Send the object as a reference to the object,
  1362. // and not to the variable holding the object
  1363. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1364. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  1365. // as the value allocated on the stack is guaranteed to be safe
  1366. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1367. else
  1368. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1369. }
  1370. else
  1371. {
  1372. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1373. }
  1374. }
  1375. }
  1376. else if( descr->parameterTypes[n].IsObject() )
  1377. {
  1378. // TODO: value on stack: What can we do to avoid this unnecessary allocation?
  1379. // The object must be allocated on the heap, because this memory will be deleted in as_callfunc_xxx
  1380. asASSERT(IsVariableOnHeap(args[n]->type.stackOffset));
  1381. bc->InstrWORD(asBC_GETOBJ, (asWORD)offset);
  1382. // The temporary variable must not be freed as it will no longer hold an object
  1383. DeallocateVariable(args[n]->type.stackOffset);
  1384. args[n]->type.isTemporary = false;
  1385. }
  1386. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  1387. }
  1388. }
  1389. int asCCompiler::CompileArgumentList(asCScriptNode *node, asCArray<asSExprContext*> &args)
  1390. {
  1391. asASSERT(node->nodeType == snArgList);
  1392. // Count arguments
  1393. asCScriptNode *arg = node->firstChild;
  1394. int argCount = 0;
  1395. while( arg )
  1396. {
  1397. argCount++;
  1398. arg = arg->next;
  1399. }
  1400. // Prepare the arrays
  1401. args.SetLength(argCount);
  1402. int n;
  1403. for( n = 0; n < argCount; n++ )
  1404. args[n] = 0;
  1405. n = argCount-1;
  1406. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1407. bool anyErrors = false;
  1408. arg = node->lastChild;
  1409. while( arg )
  1410. {
  1411. asSExprContext expr(engine);
  1412. int r = CompileAssignment(arg, &expr);
  1413. if( r < 0 ) anyErrors = true;
  1414. args[n] = asNEW(asSExprContext)(engine);
  1415. if( args[n] == 0 )
  1416. {
  1417. // Out of memory
  1418. return -1;
  1419. }
  1420. MergeExprBytecodeAndType(args[n], &expr);
  1421. n--;
  1422. arg = arg->prev;
  1423. }
  1424. return anyErrors ? -1 : 0;
  1425. }
  1426. int asCCompiler::CompileDefaultArgs(asCScriptNode *node, asCArray<asSExprContext*> &args, asCScriptFunction *func)
  1427. {
  1428. bool anyErrors = false;
  1429. asCArray<int> varsUsed;
  1430. int explicitArgs = (int)args.GetLength();
  1431. for( int p = 0; p < explicitArgs; p++ )
  1432. args[p]->bc.GetVarsUsed(varsUsed);
  1433. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1434. args.SetLength(func->parameterTypes.GetLength());
  1435. for( asUINT c = explicitArgs; c < args.GetLength(); c++ )
  1436. args[c] = 0;
  1437. for( int n = (int)func->parameterTypes.GetLength() - 1; n >= explicitArgs; n-- )
  1438. {
  1439. if( func->defaultArgs[n] == 0 ) { anyErrors = true; continue; }
  1440. // Parse the default arg string
  1441. asCParser parser(builder);
  1442. asCScriptCode code;
  1443. code.SetCode("default arg", func->defaultArgs[n]->AddressOf(), false);
  1444. int r = parser.ParseExpression(&code);
  1445. if( r < 0 )
  1446. {
  1447. asCString msg;
  1448. msg.Format(TXT_FAILED_TO_COMPILE_DEF_ARG_d_IN_FUNC_s, n, func->GetDeclaration());
  1449. Error(msg, node);
  1450. anyErrors = true;
  1451. continue;
  1452. }
  1453. asCScriptNode *arg = parser.GetScriptNode();
  1454. // Temporarily set the script code to the default arg expression
  1455. asCScriptCode *origScript = script;
  1456. script = &code;
  1457. // Don't allow the expression to access local variables
  1458. // TODO: namespace: The default arg should see the symbols declared in the same scope as the function that is called
  1459. isCompilingDefaultArg = true;
  1460. asSExprContext expr(engine);
  1461. r = CompileExpression(arg, &expr);
  1462. // Don't allow address of class method
  1463. if( expr.methodName != "" )
  1464. {
  1465. // TODO: Improve error message
  1466. Error(TXT_DEF_ARG_TYPE_DOESNT_MATCH, arg);
  1467. r = -1;
  1468. }
  1469. // Make sure the expression can be implicitly converted to the parameter type
  1470. if( r >= 0 )
  1471. {
  1472. asCArray<int> funcs;
  1473. funcs.PushLast(func->id);
  1474. asCArray<asSOverloadCandidate> matches;
  1475. if( MatchArgument(funcs, matches, &expr, n) == 0 )
  1476. {
  1477. Error(TXT_DEF_ARG_TYPE_DOESNT_MATCH, arg);
  1478. r = -1;
  1479. }
  1480. }
  1481. isCompilingDefaultArg = false;
  1482. script = origScript;
  1483. if( r < 0 )
  1484. {
  1485. asCString msg;
  1486. msg.Format(TXT_FAILED_TO_COMPILE_DEF_ARG_d_IN_FUNC_s, n, func->GetDeclaration());
  1487. Error(msg, node);
  1488. anyErrors = true;
  1489. continue;
  1490. }
  1491. args[n] = asNEW(asSExprContext)(engine);
  1492. if( args[n] == 0 )
  1493. {
  1494. // Out of memory
  1495. return -1;
  1496. }
  1497. MergeExprBytecodeAndType(args[n], &expr);
  1498. // Make sure the default arg expression doesn't end up
  1499. // with a variable that is used in a previous expression
  1500. if( args[n]->type.isVariable )
  1501. {
  1502. int offset = args[n]->type.stackOffset;
  1503. if( varsUsed.Exists(offset) )
  1504. {
  1505. // Release the current temporary variable
  1506. ReleaseTemporaryVariable(args[n]->type, 0);
  1507. asCDataType dt = args[n]->type.dataType;
  1508. dt.MakeReference(false);
  1509. // Reserve all variables already used in the expression so none of them will be used
  1510. asCArray<int> used;
  1511. args[n]->bc.GetVarsUsed(used);
  1512. size_t prevReserved = reservedVariables.GetLength();
  1513. reservedVariables.Concatenate(used);
  1514. int newOffset = AllocateVariable(dt, true, IsVariableOnHeap(offset));
  1515. asASSERT( IsVariableOnHeap(offset) == IsVariableOnHeap(newOffset) );
  1516. reservedVariables.SetLength(prevReserved);
  1517. // Replace the variable in the expression
  1518. args[n]->bc.ExchangeVar(offset, newOffset);
  1519. args[n]->type.stackOffset = (short)newOffset;
  1520. args[n]->type.isTemporary = true;
  1521. args[n]->type.isVariable = true;
  1522. }
  1523. }
  1524. }
  1525. return anyErrors ? -1 : 0;
  1526. }
  1527. asUINT asCCompiler::MatchFunctions(asCArray<int> &funcs, asCArray<asSExprContext*> &args, asCScriptNode *node, const char *name, asCObjectType *objectType, bool isConstMethod, bool silent, bool allowObjectConstruct, const asCString &scope)
  1528. {
  1529. asCArray<int> origFuncs = funcs; // Keep the original list for error message
  1530. asUINT cost = 0;
  1531. asUINT n;
  1532. if( funcs.GetLength() > 0 )
  1533. {
  1534. // Check the number of parameters in the found functions
  1535. for( n = 0; n < funcs.GetLength(); ++n )
  1536. {
  1537. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  1538. if( desc->parameterTypes.GetLength() != args.GetLength() )
  1539. {
  1540. bool noMatch = true;
  1541. if( args.GetLength() < desc->parameterTypes.GetLength() )
  1542. {
  1543. // Count the number of default args
  1544. asUINT defaultArgs = 0;
  1545. for( asUINT d = 0; d < desc->defaultArgs.GetLength(); d++ )
  1546. if( desc->defaultArgs[d] )
  1547. defaultArgs++;
  1548. if( args.GetLength() >= desc->parameterTypes.GetLength() - defaultArgs )
  1549. noMatch = false;
  1550. }
  1551. if( noMatch )
  1552. {
  1553. // remove it from the list
  1554. if( n == funcs.GetLength()-1 )
  1555. funcs.PopLast();
  1556. else
  1557. funcs[n] = funcs.PopLast();
  1558. n--;
  1559. }
  1560. }
  1561. }
  1562. // Match functions with the parameters, and discard those that do not match
  1563. asCArray<asSOverloadCandidate> matchingFuncs;
  1564. matchingFuncs.SetLengthNoConstruct( funcs.GetLength() );
  1565. for ( n = 0; n < funcs.GetLength(); ++n )
  1566. {
  1567. matchingFuncs[n].funcId = funcs[n];
  1568. matchingFuncs[n].cost = 0;
  1569. }
  1570. for( n = 0; n < args.GetLength(); ++n )
  1571. {
  1572. asCArray<asSOverloadCandidate> tempFuncs;
  1573. MatchArgument(funcs, tempFuncs, args[n], n, allowObjectConstruct);
  1574. // Intersect the found functions with the list of matching functions
  1575. for( asUINT f = 0; f < matchingFuncs.GetLength(); f++ )
  1576. {
  1577. asUINT c;
  1578. for( c = 0; c < tempFuncs.GetLength(); c++ )
  1579. {
  1580. if( matchingFuncs[f].funcId == tempFuncs[c].funcId )
  1581. {
  1582. // Sum argument cost
  1583. matchingFuncs[f].cost += tempFuncs[c].cost;
  1584. break;
  1585. } // End if match
  1586. }
  1587. // Was the function a match?
  1588. if( c == tempFuncs.GetLength() )
  1589. {
  1590. // No, remove it from the list
  1591. if( f == matchingFuncs.GetLength()-1 )
  1592. matchingFuncs.PopLast();
  1593. else
  1594. matchingFuncs[f] = matchingFuncs.PopLast();
  1595. f--;
  1596. }
  1597. }
  1598. }
  1599. // Select the overload(s) with the lowest overall cost
  1600. funcs.SetLength(0);
  1601. asUINT bestCost = asUINT(-1);
  1602. for( n = 0; n < matchingFuncs.GetLength(); ++n )
  1603. {
  1604. cost = matchingFuncs[n].cost;
  1605. if( cost < bestCost )
  1606. {
  1607. funcs.SetLength(0);
  1608. bestCost = cost;
  1609. }
  1610. if( cost == bestCost )
  1611. funcs.PushLast( matchingFuncs[n].funcId );
  1612. }
  1613. // Cost returned is equivalent to the best cost discovered
  1614. cost = bestCost;
  1615. }
  1616. if( !isConstMethod )
  1617. FilterConst(funcs);
  1618. if( funcs.GetLength() != 1 && !silent )
  1619. {
  1620. // Build a readable string of the function with parameter types
  1621. asCString str;
  1622. if( scope != "" )
  1623. {
  1624. if( scope == "::" )
  1625. str = scope;
  1626. else
  1627. str = scope + "::";
  1628. }
  1629. str += name;
  1630. str += "(";
  1631. if( args.GetLength() )
  1632. {
  1633. if( args[0]->methodName != "" )
  1634. str += args[0]->methodName;
  1635. else
  1636. str += args[0]->type.dataType.Format();
  1637. }
  1638. for( n = 1; n < args.GetLength(); n++ )
  1639. {
  1640. str += ", ";
  1641. if( args[n]->methodName != "" )
  1642. str += args[n]->methodName;
  1643. else
  1644. str += args[n]->type.dataType.Format();
  1645. }
  1646. str += ")";
  1647. if( isConstMethod )
  1648. str += " const";
  1649. if( objectType && scope == "" )
  1650. str = objectType->name + "::" + str;
  1651. if( funcs.GetLength() == 0 )
  1652. {
  1653. str.Format(TXT_NO_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1654. Error(str, node);
  1655. // Print the list of candidates
  1656. if( origFuncs.GetLength() > 0 )
  1657. {
  1658. int r = 0, c = 0;
  1659. asASSERT( node );
  1660. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  1661. builder->WriteInfo(script->name.AddressOf(), TXT_CANDIDATES_ARE, r, c, false);
  1662. PrintMatchingFuncs(origFuncs, node);
  1663. }
  1664. }
  1665. else
  1666. {
  1667. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1668. Error(str, node);
  1669. PrintMatchingFuncs(funcs, node);
  1670. }
  1671. }
  1672. return cost;
  1673. }
  1674. void asCCompiler::CompileDeclaration(asCScriptNode *decl, asCByteCode *bc)
  1675. {
  1676. // Get the data type
  1677. asCDataType type = builder->CreateDataTypeFromNode(decl->firstChild, script, outFunc->nameSpace);
  1678. // Declare all variables in this declaration
  1679. asCScriptNode *node = decl->firstChild->next;
  1680. while( node )
  1681. {
  1682. // Is the type allowed?
  1683. if( !type.CanBeInstanciated() )
  1684. {
  1685. asCString str;
  1686. // TODO: Change to "'type' cannot be declared as variable"
  1687. str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format().AddressOf());
  1688. Error(str, node);
  1689. // Use int instead to avoid further problems
  1690. type = asCDataType::CreatePrimitive(ttInt, false);
  1691. }
  1692. // A shared object may not declare variables of non-shared types
  1693. if( outFunc->IsShared() )
  1694. {
  1695. asCObjectType *ot = type.GetObjectType();
  1696. if( ot && !ot->IsShared() )
  1697. {
  1698. asCString msg;
  1699. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  1700. Error(msg, decl);
  1701. }
  1702. }
  1703. // Get the name of the identifier
  1704. asCString name(&script->code[node->tokenPos], node->tokenLength);
  1705. // Verify that the name isn't used by a dynamic data type
  1706. if( engine->GetObjectType(name.AddressOf(), outFunc->nameSpace) != 0 )
  1707. {
  1708. asCString str;
  1709. str.Format(TXT_ILLEGAL_VARIABLE_NAME_s, name.AddressOf());
  1710. Error(str, node);
  1711. }
  1712. int offset = AllocateVariable(type, false);
  1713. if( variables->DeclareVariable(name.AddressOf(), type, offset, IsVariableOnHeap(offset)) < 0 )
  1714. {
  1715. // TODO: It might be an out-of-memory too
  1716. asCString str;
  1717. str.Format(TXT_s_ALREADY_DECLARED, name.AddressOf());
  1718. Error(str, node);
  1719. // Don't continue after this error, as it will just
  1720. // lead to more errors that are likely false
  1721. return;
  1722. }
  1723. // Add marker that the variable has been declared
  1724. bc->VarDecl((int)outFunc->variables.GetLength());
  1725. outFunc->AddVariable(name, type, offset);
  1726. // Keep the node for the variable decl
  1727. asCScriptNode *varNode = node;
  1728. node = node->next;
  1729. if( node == 0 || node->nodeType == snIdentifier )
  1730. {
  1731. // Initialize with default constructor
  1732. CompileInitialization(0, bc, type, varNode, offset, 0, 0);
  1733. }
  1734. else
  1735. {
  1736. // Compile the initialization expression
  1737. asQWORD constantValue = 0;
  1738. if( CompileInitialization(node, bc, type, varNode, offset, &constantValue, 0) )
  1739. {
  1740. // Check if the variable should be marked as pure constant
  1741. if( type.IsPrimitive() && type.IsReadOnly() )
  1742. {
  1743. sVariable *v = variables->GetVariable(name.AddressOf());
  1744. v->isPureConstant = true;
  1745. v->constantValue = constantValue;
  1746. }
  1747. }
  1748. node = node->next;
  1749. }
  1750. }
  1751. bc->OptimizeLocally(tempVariableOffsets);
  1752. }
  1753. bool asCCompiler::CompileInitialization(asCScriptNode *node, asCByteCode *bc, asCDataType &type, asCScriptNode *errNode, int offset, asQWORD *constantValue, int isVarGlobOrMem)
  1754. {
  1755. bool isConstantExpression = false;
  1756. if( node && node->nodeType == snArgList )
  1757. {
  1758. // Make sure it is an object and not a handle
  1759. if( type.GetObjectType() == 0 || type.IsObjectHandle() )
  1760. {
  1761. Error(TXT_MUST_BE_OBJECT, node);
  1762. }
  1763. else
  1764. {
  1765. // Compile the arguments
  1766. asCArray<asSExprContext *> args;
  1767. if( CompileArgumentList(node, args) >= 0 )
  1768. {
  1769. // Find all constructors
  1770. asCArray<int> funcs;
  1771. asSTypeBehaviour *beh = type.GetBehaviour();
  1772. if( beh )
  1773. {
  1774. if( type.GetObjectType()->flags & asOBJ_REF )
  1775. funcs = beh->factories;
  1776. else
  1777. funcs = beh->constructors;
  1778. }
  1779. asCString str = type.Format();
  1780. MatchFunctions(funcs, args, node, str.AddressOf());
  1781. if( funcs.GetLength() == 1 )
  1782. {
  1783. int r = asSUCCESS;
  1784. // Add the default values for arguments not explicitly supplied
  1785. asCScriptFunction *func = (funcs[0] & FUNC_IMPORTED) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  1786. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  1787. r = CompileDefaultArgs(node, args, func);
  1788. if( r == asSUCCESS )
  1789. {
  1790. asSExprContext ctx(engine);
  1791. if( type.GetObjectType() && (type.GetObjectType()->flags & asOBJ_REF) )
  1792. {
  1793. if( isVarGlobOrMem == 0 )
  1794. MakeFunctionCall(&ctx, funcs[0], 0, args, node, true, offset);
  1795. else
  1796. {
  1797. MakeFunctionCall(&ctx, funcs[0], 0, args, node);
  1798. ctx.bc.Instr(asBC_RDSPtr);
  1799. if( isVarGlobOrMem == 1 )
  1800. {
  1801. // Store the returned handle in the global variable
  1802. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  1803. }
  1804. else
  1805. {
  1806. // Store the returned handle in the member
  1807. ctx.bc.InstrSHORT(asBC_PSF, 0);
  1808. ctx.bc.Instr(asBC_RDSPtr);
  1809. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  1810. }
  1811. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  1812. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  1813. }
  1814. // Pop the reference left by the function call
  1815. ctx.bc.Instr(asBC_PopPtr);
  1816. }
  1817. else
  1818. {
  1819. bool onHeap = false;
  1820. if( isVarGlobOrMem == 0 )
  1821. {
  1822. // When the object is allocated on the heap, the address where the
  1823. // reference will be stored must be pushed on the stack before the
  1824. // arguments. This reference on the stack is safe, even if the script
  1825. // is suspended during the evaluation of the arguments.
  1826. onHeap = IsVariableOnHeap(offset);
  1827. if( onHeap )
  1828. ctx.bc.InstrSHORT(asBC_PSF, (short)offset);
  1829. }
  1830. else
  1831. {
  1832. // Push the address of the location where the variable will be stored on the stack.
  1833. // This reference is safe, because the addresses of the global variables cannot change.
  1834. // TODO: When serialization of the context is implemented this will probably have to change,
  1835. // because this pointer may be on the stack while the context is suspended, and may
  1836. // be difficult to serialize as the context doesn't know that the value represents a
  1837. // pointer.
  1838. onHeap = true;
  1839. if( isVarGlobOrMem == 1 )
  1840. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  1841. else
  1842. {
  1843. ctx.bc.InstrSHORT(asBC_PSF, 0);
  1844. ctx.bc.Instr(asBC_RDSPtr);
  1845. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  1846. }
  1847. }
  1848. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  1849. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  1850. // When the object is allocated on the stack, the address to the
  1851. // object is pushed on the stack after the arguments as the object pointer
  1852. if( !onHeap )
  1853. ctx.bc.InstrSHORT(asBC_PSF, (short)offset);
  1854. PerformFunctionCall(funcs[0], &ctx, onHeap, &args, type.GetObjectType());
  1855. if( isVarGlobOrMem == 0 )
  1856. {
  1857. // Mark the object in the local variable as initialized
  1858. ctx.bc.ObjInfo(offset, asOBJ_INIT);
  1859. }
  1860. }
  1861. bc->AddCode(&ctx.bc);
  1862. }
  1863. }
  1864. }
  1865. // Cleanup
  1866. for( asUINT n = 0; n < args.GetLength(); n++ )
  1867. if( args[n] )
  1868. {
  1869. asDELETE(args[n],asSExprContext);
  1870. }
  1871. }
  1872. }
  1873. else if( node && node->nodeType == snInitList )
  1874. {
  1875. asCTypeInfo ti;
  1876. ti.Set(type);
  1877. ti.isVariable = (isVarGlobOrMem == 0);
  1878. ti.isTemporary = false;
  1879. ti.stackOffset = (short)offset;
  1880. ti.isLValue = true;
  1881. CompileInitList(&ti, node, bc, isVarGlobOrMem);
  1882. }
  1883. else if( node && node->nodeType == snAssignment )
  1884. {
  1885. asSExprContext ctx(engine);
  1886. // TODO: copy: Here we should look for the best matching constructor, instead of
  1887. // just the copy constructor. Only if no appropriate constructor is
  1888. // available should the assignment operator be used.
  1889. // Call the default constructor here
  1890. if( isVarGlobOrMem == 0 )
  1891. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), &ctx.bc, errNode);
  1892. else
  1893. CallDefaultConstructor(type, offset, true, &ctx.bc, errNode, isVarGlobOrMem);
  1894. // Compile the expression
  1895. asSExprContext expr(engine);
  1896. int r = CompileAssignment(node, &expr);
  1897. if( r >= 0 )
  1898. {
  1899. if( type.IsPrimitive() )
  1900. {
  1901. if( type.IsReadOnly() && expr.type.isConstant )
  1902. {
  1903. ImplicitConversion(&expr, type, node, asIC_IMPLICIT_CONV);
  1904. // Tell caller that the expression is a constant so it can mark the variable as pure constant
  1905. isConstantExpression = true;
  1906. *constantValue = expr.type.qwordValue;
  1907. }
  1908. asSExprContext lctx(engine);
  1909. if( isVarGlobOrMem == 0 )
  1910. lctx.type.SetVariable(type, offset, false);
  1911. else if( isVarGlobOrMem == 1 )
  1912. {
  1913. lctx.type.Set(type);
  1914. lctx.type.dataType.MakeReference(true);
  1915. // If it is an enum value, i.e. offset is negative, that is being compiled then
  1916. // we skip this as the bytecode won't be used anyway, only the constant value
  1917. if( offset >= 0 )
  1918. lctx.bc.InstrPTR(asBC_LDG, engine->globalProperties[offset]->GetAddressOfValue());
  1919. }
  1920. else
  1921. {
  1922. asASSERT( isVarGlobOrMem == 2 );
  1923. lctx.type.Set(type);
  1924. lctx.type.dataType.MakeReference(true);
  1925. // Load the reference of the primitive member into the register
  1926. lctx.bc.InstrSHORT(asBC_PSF, 0);
  1927. lctx.bc.Instr(asBC_RDSPtr);
  1928. lctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  1929. lctx.bc.Instr(asBC_PopRPtr);
  1930. }
  1931. lctx.type.dataType.MakeReadOnly(false);
  1932. lctx.type.isLValue = true;
  1933. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  1934. ProcessDeferredParams(&ctx);
  1935. }
  1936. else
  1937. {
  1938. // TODO: runtime optimize: Here we should look for the best matching constructor, instead of
  1939. // just the copy constructor. Only if no appropriate constructor is
  1940. // available should the assignment operator be used.
  1941. asSExprContext lexpr(engine);
  1942. lexpr.type.Set(type);
  1943. if( isVarGlobOrMem == 0 )
  1944. lexpr.type.dataType.MakeReference(IsVariableOnHeap(offset));
  1945. else
  1946. lexpr.type.dataType.MakeReference(true);
  1947. // Allow initialization of constant variables
  1948. lexpr.type.dataType.MakeReadOnly(false);
  1949. if( type.IsObjectHandle() )
  1950. lexpr.type.isExplicitHandle = true;
  1951. if( isVarGlobOrMem == 0 )
  1952. {
  1953. lexpr.bc.InstrSHORT(asBC_PSF, (short)offset);
  1954. lexpr.type.stackOffset = (short)offset;
  1955. lexpr.type.isVariable = true;
  1956. }
  1957. else if( isVarGlobOrMem == 1 )
  1958. {
  1959. lexpr.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  1960. }
  1961. else
  1962. {
  1963. lexpr.bc.InstrSHORT(asBC_PSF, 0);
  1964. lexpr.bc.Instr(asBC_RDSPtr);
  1965. lexpr.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  1966. lexpr.type.stackOffset = -1;
  1967. }
  1968. lexpr.type.isLValue = true;
  1969. // If left expression resolves into a registered type
  1970. // check if the assignment operator is overloaded, and check
  1971. // the type of the right hand expression. If none is found
  1972. // the default action is a direct copy if it is the same type
  1973. // and a simple assignment.
  1974. bool assigned = false;
  1975. // Even though an ASHANDLE can be an explicit handle the overloaded operator needs to be called
  1976. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  1977. {
  1978. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  1979. if( assigned )
  1980. {
  1981. // Pop the resulting value
  1982. if( !ctx.type.dataType.IsPrimitive() )
  1983. ctx.bc.Instr(asBC_PopPtr);
  1984. // Release the argument
  1985. ProcessDeferredParams(&ctx);
  1986. // Release temporary variable that may be allocated by the overloaded operator
  1987. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1988. }
  1989. }
  1990. if( !assigned )
  1991. {
  1992. PrepareForAssignment(&lexpr.type.dataType, &expr, node, false);
  1993. // If the expression is constant and the variable also is constant
  1994. // then mark the variable as pure constant. This will allow the compiler
  1995. // to optimize expressions with this variable.
  1996. if( type.IsReadOnly() && expr.type.isConstant )
  1997. {
  1998. isConstantExpression = true;
  1999. *constantValue = expr.type.qwordValue;
  2000. }
  2001. // Add expression code to bytecode
  2002. MergeExprBytecode(&ctx, &expr);
  2003. // Add byte code for storing value of expression in variable
  2004. ctx.bc.AddCode(&lexpr.bc);
  2005. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, errNode);
  2006. // Release temporary variables used by expression
  2007. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  2008. ctx.bc.Instr(asBC_PopPtr);
  2009. ProcessDeferredParams(&ctx);
  2010. }
  2011. }
  2012. }
  2013. bc->AddCode(&ctx.bc);
  2014. }
  2015. else
  2016. {
  2017. asASSERT( node == 0 );
  2018. // Call the default constructor here, as no explicit initialization is done
  2019. if( isVarGlobOrMem == 0 )
  2020. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), bc, errNode);
  2021. else
  2022. CallDefaultConstructor(type, offset, true, bc, errNode, isVarGlobOrMem);
  2023. }
  2024. bc->OptimizeLocally(tempVariableOffsets);
  2025. return isConstantExpression;
  2026. }
  2027. void asCCompiler::CompileInitList(asCTypeInfo *var, asCScriptNode *node, asCByteCode *bc, int isVarGlobOrMem)
  2028. {
  2029. // Check if the type supports initialization lists
  2030. if( var->dataType.GetObjectType() == 0 ||
  2031. var->dataType.GetBehaviour()->listFactory == 0 ||
  2032. var->dataType.IsObjectHandle() )
  2033. {
  2034. asCString str;
  2035. str.Format(TXT_INIT_LIST_CANNOT_BE_USED_WITH_s, var->dataType.Format().AddressOf());
  2036. Error(str, node);
  2037. return;
  2038. }
  2039. // Count the number of elements and initialize the array with the correct size
  2040. int countElements = 0;
  2041. asCScriptNode *el = node->firstChild;
  2042. while( el )
  2043. {
  2044. countElements++;
  2045. el = el->next;
  2046. }
  2047. // Construct the array with the size elements
  2048. // TODO: value on stack: This needs to support value types on the stack as well
  2049. // Find the list factory
  2050. // TODO: initlist: Add support for value types as well
  2051. int funcId = var->dataType.GetBehaviour()->listFactory;
  2052. asCArray<asSExprContext *> args;
  2053. asSExprContext arg1(engine);
  2054. arg1.bc.InstrDWORD(asBC_PshC4, countElements);
  2055. arg1.type.Set(asCDataType::CreatePrimitive(ttUInt, false));
  2056. args.PushLast(&arg1);
  2057. asSExprContext ctx(engine);
  2058. PrepareFunctionCall(funcId, &ctx.bc, args);
  2059. MoveArgsToStack(funcId, &ctx.bc, args, false);
  2060. if( var->isVariable )
  2061. {
  2062. asASSERT( isVarGlobOrMem == 0 );
  2063. // Call factory and store the handle in the given variable
  2064. PerformFunctionCall(funcId, &ctx, false, &args, 0, true, var->stackOffset);
  2065. ctx.bc.Instr(asBC_PopPtr);
  2066. }
  2067. else
  2068. {
  2069. PerformFunctionCall(funcId, &ctx, false, &args);
  2070. ctx.bc.Instr(asBC_RDSPtr);
  2071. if( isVarGlobOrMem == 1 )
  2072. {
  2073. // Store the returned handle in the global variable
  2074. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  2075. }
  2076. else
  2077. {
  2078. // Store the returned handle in the member
  2079. ctx.bc.InstrSHORT(asBC_PSF, 0);
  2080. ctx.bc.Instr(asBC_RDSPtr);
  2081. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)var->stackOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2082. }
  2083. ctx.bc.InstrPTR(asBC_REFCPY, var->dataType.GetObjectType());
  2084. ctx.bc.Instr(asBC_PopPtr);
  2085. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  2086. }
  2087. bc->AddCode(&ctx.bc);
  2088. // TODO: initlist: Should we have a special indexing operator for this? How can we support
  2089. // initialization lists with different types for different elements? Maybe
  2090. // by using the variable arguments the initialization can be done with one
  2091. // call, passing all the elements as arguments. The registered function can
  2092. // then traverse them however it wants.
  2093. // Find the indexing operator that is not read-only that will be used for all elements
  2094. asCDataType retType;
  2095. retType = var->dataType.GetSubType();
  2096. retType.MakeReference(true);
  2097. retType.MakeReadOnly(false);
  2098. funcId = 0;
  2099. for( asUINT n = 0; n < var->dataType.GetObjectType()->methods.GetLength(); n++ )
  2100. {
  2101. asCScriptFunction *desc = builder->GetFunctionDescription(var->dataType.GetObjectType()->methods[n]);
  2102. if( !desc->isReadOnly &&
  2103. desc->parameterTypes.GetLength() == 1 &&
  2104. (desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttUInt, false) ||
  2105. desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttInt, false)) &&
  2106. desc->returnType == retType &&
  2107. desc->name == "opIndex" )
  2108. {
  2109. funcId = var->dataType.GetObjectType()->methods[n];
  2110. break;
  2111. }
  2112. }
  2113. if( funcId == 0 )
  2114. {
  2115. Error(TXT_NO_APPROPRIATE_INDEX_OPERATOR, node);
  2116. return;
  2117. }
  2118. asUINT index = 0;
  2119. el = node->firstChild;
  2120. while( el )
  2121. {
  2122. if( el->nodeType == snAssignment || el->nodeType == snInitList )
  2123. {
  2124. asSExprContext lctx(engine);
  2125. asSExprContext rctx(engine);
  2126. if( el->nodeType == snAssignment )
  2127. {
  2128. // Compile the assignment expression
  2129. CompileAssignment(el, &rctx);
  2130. }
  2131. else if( el->nodeType == snInitList )
  2132. {
  2133. int offset = AllocateVariable(var->dataType.GetSubType(), true);
  2134. rctx.type.Set(var->dataType.GetSubType());
  2135. rctx.type.isVariable = true;
  2136. rctx.type.isTemporary = true;
  2137. rctx.type.stackOffset = (short)offset;
  2138. CompileInitList(&rctx.type, el, &rctx.bc, 0);
  2139. // Put the object on the stack
  2140. rctx.bc.InstrSHORT(asBC_PSF, rctx.type.stackOffset);
  2141. // It is a reference that we place on the stack
  2142. rctx.type.dataType.MakeReference(true);
  2143. }
  2144. // Compile the lvalue
  2145. lctx.bc.InstrDWORD(asBC_PshC4, index);
  2146. if( var->isVariable )
  2147. lctx.bc.InstrSHORT(asBC_PSF, var->stackOffset);
  2148. else
  2149. {
  2150. // TODO: runtime optimize: should copy a handle to a local variable to avoid
  2151. // accessing the global variable or class member for each element
  2152. if( isVarGlobOrMem == 1 )
  2153. lctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  2154. else
  2155. {
  2156. lctx.bc.InstrSHORT(asBC_PSF, 0);
  2157. lctx.bc.Instr(asBC_RDSPtr);
  2158. lctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)var->stackOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2159. }
  2160. }
  2161. lctx.bc.Instr(asBC_RDSPtr);
  2162. lctx.bc.Call(asBC_CALLSYS, funcId, 1+AS_PTR_SIZE);
  2163. if( !var->dataType.GetSubType().IsPrimitive() )
  2164. lctx.bc.Instr(asBC_PshRPtr);
  2165. lctx.type.Set(var->dataType.GetSubType());
  2166. if( !lctx.type.dataType.IsObject() || lctx.type.dataType.IsObjectHandle() )
  2167. lctx.type.dataType.MakeReference(true);
  2168. // If the element type is handles, then we're expected to do handle assignments
  2169. if( lctx.type.dataType.IsObjectHandle() )
  2170. lctx.type.isExplicitHandle = true;
  2171. lctx.type.isLValue = true;
  2172. asSExprContext ctx(engine);
  2173. DoAssignment(&ctx, &lctx, &rctx, el, el, ttAssignment, el);
  2174. if( !lctx.type.dataType.IsPrimitive() )
  2175. ctx.bc.Instr(asBC_PopPtr);
  2176. // Release temporary variables used by expression
  2177. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  2178. ProcessDeferredParams(&ctx);
  2179. bc->AddCode(&ctx.bc);
  2180. }
  2181. el = el->next;
  2182. index++;
  2183. }
  2184. }
  2185. void asCCompiler::CompileStatement(asCScriptNode *statement, bool *hasReturn, asCByteCode *bc)
  2186. {
  2187. // Don't clear the hasReturn flag if this is an empty statement
  2188. // to avoid false errors of 'not all paths return'
  2189. if( statement->nodeType != snExpressionStatement || statement->firstChild )
  2190. *hasReturn = false;
  2191. if( statement->nodeType == snStatementBlock )
  2192. CompileStatementBlock(statement, true, hasReturn, bc);
  2193. else if( statement->nodeType == snIf )
  2194. CompileIfStatement(statement, hasReturn, bc);
  2195. else if( statement->nodeType == snFor )
  2196. CompileForStatement(statement, bc);
  2197. else if( statement->nodeType == snWhile )
  2198. CompileWhileStatement(statement, bc);
  2199. else if( statement->nodeType == snDoWhile )
  2200. CompileDoWhileStatement(statement, bc);
  2201. else if( statement->nodeType == snExpressionStatement )
  2202. CompileExpressionStatement(statement, bc);
  2203. else if( statement->nodeType == snBreak )
  2204. CompileBreakStatement(statement, bc);
  2205. else if( statement->nodeType == snContinue )
  2206. CompileContinueStatement(statement, bc);
  2207. else if( statement->nodeType == snSwitch )
  2208. CompileSwitchStatement(statement, hasReturn, bc);
  2209. else if( statement->nodeType == snReturn )
  2210. {
  2211. CompileReturnStatement(statement, bc);
  2212. *hasReturn = true;
  2213. }
  2214. }
  2215. void asCCompiler::CompileSwitchStatement(asCScriptNode *snode, bool *, asCByteCode *bc)
  2216. {
  2217. // TODO: inheritance: Must guarantee that all options in the switch case call a constructor, or that none call it.
  2218. // Reserve label for break statements
  2219. int breakLabel = nextLabel++;
  2220. breakLabels.PushLast(breakLabel);
  2221. // Add a variable scope that will be used by CompileBreak
  2222. // to know where to stop deallocating variables
  2223. AddVariableScope(true, false);
  2224. //---------------------------
  2225. // Compile the switch expression
  2226. //-------------------------------
  2227. // Compile the switch expression
  2228. asSExprContext expr(engine);
  2229. CompileAssignment(snode->firstChild, &expr);
  2230. // Verify that the expression is a primitive type
  2231. if( !expr.type.dataType.IsIntegerType() && !expr.type.dataType.IsUnsignedType() )
  2232. {
  2233. Error(TXT_SWITCH_MUST_BE_INTEGRAL, snode->firstChild);
  2234. return;
  2235. }
  2236. ProcessPropertyGetAccessor(&expr, snode);
  2237. // TODO: Need to support 64bit integers
  2238. // Convert the expression to a 32bit variable
  2239. asCDataType to;
  2240. if( expr.type.dataType.IsIntegerType() )
  2241. to.SetTokenType(ttInt);
  2242. else if( expr.type.dataType.IsUnsignedType() )
  2243. to.SetTokenType(ttUInt);
  2244. // Make sure the value is in a variable
  2245. if( expr.type.dataType.IsReference() )
  2246. ConvertToVariable(&expr);
  2247. ImplicitConversion(&expr, to, snode->firstChild, asIC_IMPLICIT_CONV, true);
  2248. ConvertToVariable(&expr);
  2249. int offset = expr.type.stackOffset;
  2250. ProcessDeferredParams(&expr);
  2251. //-------------------------------
  2252. // Determine case values and labels
  2253. //--------------------------------
  2254. // Remember the first label so that we can later pass the
  2255. // correct label to each CompileCase()
  2256. int firstCaseLabel = nextLabel;
  2257. int defaultLabel = 0;
  2258. asCArray<int> caseValues;
  2259. asCArray<int> caseLabels;
  2260. // Compile all case comparisons and make them jump to the right label
  2261. asCScriptNode *cnode = snode->firstChild->next;
  2262. while( cnode )
  2263. {
  2264. // Each case should have a constant expression
  2265. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  2266. {
  2267. // Compile expression
  2268. asSExprContext c(engine);
  2269. CompileExpression(cnode->firstChild, &c);
  2270. // Verify that the result is a constant
  2271. if( !c.type.isConstant )
  2272. Error(TXT_SWITCH_CASE_MUST_BE_CONSTANT, cnode->firstChild);
  2273. // Verify that the result is an integral number
  2274. if( !c.type.dataType.IsIntegerType() && !c.type.dataType.IsUnsignedType() )
  2275. Error(TXT_SWITCH_MUST_BE_INTEGRAL, cnode->firstChild);
  2276. ImplicitConversion(&c, to, cnode->firstChild, asIC_IMPLICIT_CONV, true);
  2277. // Has this case been declared already?
  2278. if( caseValues.IndexOf(c.type.intValue) >= 0 )
  2279. {
  2280. Error(TXT_DUPLICATE_SWITCH_CASE, cnode->firstChild);
  2281. }
  2282. // TODO: Optimize: We can insert the numbers sorted already
  2283. // Store constant for later use
  2284. caseValues.PushLast(c.type.intValue);
  2285. // Reserve label for this case
  2286. caseLabels.PushLast(nextLabel++);
  2287. }
  2288. else
  2289. {
  2290. // TODO: It shouldn't be necessary for the default case to be the last one.
  2291. // Is default the last case?
  2292. if( cnode->next )
  2293. {
  2294. Error(TXT_DEFAULT_MUST_BE_LAST, cnode);
  2295. break;
  2296. }
  2297. // Reserve label for this case
  2298. defaultLabel = nextLabel++;
  2299. }
  2300. cnode = cnode->next;
  2301. }
  2302. // check for empty switch
  2303. if (caseValues.GetLength() == 0)
  2304. {
  2305. Error(TXT_EMPTY_SWITCH, snode);
  2306. return;
  2307. }
  2308. if( defaultLabel == 0 )
  2309. defaultLabel = breakLabel;
  2310. //---------------------------------
  2311. // Output the optimized case comparisons
  2312. // with jumps to the case code
  2313. //------------------------------------
  2314. // Sort the case values by increasing value. Do the sort together with the labels
  2315. // A simple bubble sort is sufficient since we don't expect a huge number of values
  2316. for( asUINT fwd = 1; fwd < caseValues.GetLength(); fwd++ )
  2317. {
  2318. for( int bck = fwd - 1; bck >= 0; bck-- )
  2319. {
  2320. int bckp = bck + 1;
  2321. if( caseValues[bck] > caseValues[bckp] )
  2322. {
  2323. // Swap the values in both arrays
  2324. int swap = caseValues[bckp];
  2325. caseValues[bckp] = caseValues[bck];
  2326. caseValues[bck] = swap;
  2327. swap = caseLabels[bckp];
  2328. caseLabels[bckp] = caseLabels[bck];
  2329. caseLabels[bck] = swap;
  2330. }
  2331. else
  2332. break;
  2333. }
  2334. }
  2335. // Find ranges of consecutive numbers
  2336. asCArray<int> ranges;
  2337. ranges.PushLast(0);
  2338. asUINT n;
  2339. for( n = 1; n < caseValues.GetLength(); ++n )
  2340. {
  2341. // We can join numbers that are less than 5 numbers
  2342. // apart since the output code will still be smaller
  2343. if( caseValues[n] > caseValues[n-1] + 5 )
  2344. ranges.PushLast(n);
  2345. }
  2346. // If the value is larger than the largest case value, jump to default
  2347. int tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2348. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[caseValues.GetLength()-1]);
  2349. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2350. expr.bc.InstrDWORD(asBC_JP, defaultLabel);
  2351. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2352. // TODO: runtime optimize: We could possibly optimize this even more by doing a
  2353. // binary search instead of a linear search through the ranges
  2354. // For each range
  2355. int range;
  2356. for( range = 0; range < (int)ranges.GetLength(); range++ )
  2357. {
  2358. // Find the largest value in this range
  2359. int maxRange = caseValues[ranges[range]];
  2360. int index = ranges[range];
  2361. for( ; (index < (int)caseValues.GetLength()) && (caseValues[index] <= maxRange + 5); index++ )
  2362. maxRange = caseValues[index];
  2363. // If there are only 2 numbers then it is better to compare them directly
  2364. if( index - ranges[range] > 2 )
  2365. {
  2366. // If the value is smaller than the smallest case value in the range, jump to default
  2367. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2368. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  2369. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2370. expr.bc.InstrDWORD(asBC_JS, defaultLabel);
  2371. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2372. int nextRangeLabel = nextLabel++;
  2373. // If this is the last range we don't have to make this test
  2374. if( range < (int)ranges.GetLength() - 1 )
  2375. {
  2376. // If the value is larger than the largest case value in the range, jump to the next range
  2377. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2378. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, maxRange);
  2379. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2380. expr.bc.InstrDWORD(asBC_JP, nextRangeLabel);
  2381. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2382. }
  2383. // Jump forward according to the value
  2384. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2385. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  2386. expr.bc.InstrW_W_W(asBC_SUBi, tmpOffset, offset, tmpOffset);
  2387. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2388. expr.bc.JmpP(tmpOffset, maxRange - caseValues[ranges[range]]);
  2389. // Add the list of jumps to the correct labels (any holes, jump to default)
  2390. index = ranges[range];
  2391. for( int n = caseValues[index]; n <= maxRange; n++ )
  2392. {
  2393. if( caseValues[index] == n )
  2394. expr.bc.InstrINT(asBC_JMP, caseLabels[index++]);
  2395. else
  2396. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  2397. }
  2398. expr.bc.Label((short)nextRangeLabel);
  2399. }
  2400. else
  2401. {
  2402. // Simply make a comparison with each value
  2403. int n;
  2404. for( n = ranges[range]; n < index; ++n )
  2405. {
  2406. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2407. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[n]);
  2408. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2409. expr.bc.InstrDWORD(asBC_JZ, caseLabels[n]);
  2410. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2411. }
  2412. }
  2413. }
  2414. // Catch any value that falls trough
  2415. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  2416. // Release the temporary variable previously stored
  2417. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2418. // TODO: optimize: Should optimize each piece individually
  2419. expr.bc.OptimizeLocally(tempVariableOffsets);
  2420. //----------------------------------
  2421. // Output case implementations
  2422. //----------------------------------
  2423. // Compile case implementations, each one with the label before it
  2424. cnode = snode->firstChild->next;
  2425. while( cnode )
  2426. {
  2427. // Each case should have a constant expression
  2428. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  2429. {
  2430. expr.bc.Label((short)firstCaseLabel++);
  2431. CompileCase(cnode->firstChild->next, &expr.bc);
  2432. }
  2433. else
  2434. {
  2435. expr.bc.Label((short)defaultLabel);
  2436. // Is default the last case?
  2437. if( cnode->next )
  2438. {
  2439. // We've already reported this error
  2440. break;
  2441. }
  2442. CompileCase(cnode->firstChild, &expr.bc);
  2443. }
  2444. cnode = cnode->next;
  2445. }
  2446. //--------------------------------
  2447. bc->AddCode(&expr.bc);
  2448. // Add break label
  2449. bc->Label((short)breakLabel);
  2450. breakLabels.PopLast();
  2451. RemoveVariableScope();
  2452. }
  2453. void asCCompiler::CompileCase(asCScriptNode *node, asCByteCode *bc)
  2454. {
  2455. bool isFinished = false;
  2456. bool hasReturn = false;
  2457. bool hasUnreachableCode = false;
  2458. while( node )
  2459. {
  2460. if( !hasUnreachableCode && (hasReturn || isFinished) )
  2461. {
  2462. hasUnreachableCode = true;
  2463. Warning(TXT_UNREACHABLE_CODE, node);
  2464. break;
  2465. }
  2466. if( node->nodeType == snBreak || node->nodeType == snContinue )
  2467. isFinished = true;
  2468. asCByteCode statement(engine);
  2469. if( node->nodeType == snDeclaration )
  2470. {
  2471. Error(TXT_DECL_IN_SWITCH, node);
  2472. // Compile it anyway to avoid further compiler errors
  2473. CompileDeclaration(node, &statement);
  2474. }
  2475. else
  2476. CompileStatement(node, &hasReturn, &statement);
  2477. LineInstr(bc, node->tokenPos);
  2478. bc->AddCode(&statement);
  2479. if( !hasCompileErrors )
  2480. asASSERT( tempVariables.GetLength() == 0 );
  2481. node = node->next;
  2482. }
  2483. }
  2484. void asCCompiler::CompileIfStatement(asCScriptNode *inode, bool *hasReturn, asCByteCode *bc)
  2485. {
  2486. // We will use one label for the if statement
  2487. // and possibly another for the else statement
  2488. int afterLabel = nextLabel++;
  2489. // Compile the expression
  2490. asSExprContext expr(engine);
  2491. CompileAssignment(inode->firstChild, &expr);
  2492. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2493. {
  2494. Error(TXT_EXPR_MUST_BE_BOOL, inode->firstChild);
  2495. expr.type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 1);
  2496. }
  2497. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2498. ProcessDeferredParams(&expr);
  2499. if( !expr.type.isConstant )
  2500. {
  2501. ProcessPropertyGetAccessor(&expr, inode);
  2502. ConvertToVariable(&expr);
  2503. // Add a test
  2504. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2505. expr.bc.Instr(asBC_ClrHi);
  2506. expr.bc.InstrDWORD(asBC_JZ, afterLabel);
  2507. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2508. expr.bc.OptimizeLocally(tempVariableOffsets);
  2509. bc->AddCode(&expr.bc);
  2510. }
  2511. else if( expr.type.dwordValue == 0 )
  2512. {
  2513. // Jump to the else case
  2514. bc->InstrINT(asBC_JMP, afterLabel);
  2515. // TODO: Should we warn that the expression will always go to the else?
  2516. }
  2517. // Compile the if statement
  2518. bool origIsConstructorCalled = m_isConstructorCalled;
  2519. bool hasReturn1;
  2520. asCByteCode ifBC(engine);
  2521. CompileStatement(inode->firstChild->next, &hasReturn1, &ifBC);
  2522. // Add the byte code
  2523. LineInstr(bc, inode->firstChild->next->tokenPos);
  2524. bc->AddCode(&ifBC);
  2525. if( inode->firstChild->next->nodeType == snExpressionStatement && inode->firstChild->next->firstChild == 0 )
  2526. {
  2527. // Don't allow if( expr );
  2528. Error(TXT_IF_WITH_EMPTY_STATEMENT, inode->firstChild->next);
  2529. }
  2530. // If one of the statements call the constructor, the other must as well
  2531. // otherwise it is possible the constructor is never called
  2532. bool constructorCall1 = false;
  2533. bool constructorCall2 = false;
  2534. if( !origIsConstructorCalled && m_isConstructorCalled )
  2535. constructorCall1 = true;
  2536. // Do we have an else statement?
  2537. if( inode->firstChild->next != inode->lastChild )
  2538. {
  2539. // Reset the constructor called flag so the else statement can call the constructor too
  2540. m_isConstructorCalled = origIsConstructorCalled;
  2541. int afterElse = 0;
  2542. if( !hasReturn1 )
  2543. {
  2544. afterElse = nextLabel++;
  2545. // Add jump to after the else statement
  2546. bc->InstrINT(asBC_JMP, afterElse);
  2547. }
  2548. // Add label for the else statement
  2549. bc->Label((short)afterLabel);
  2550. bool hasReturn2;
  2551. asCByteCode elseBC(engine);
  2552. CompileStatement(inode->lastChild, &hasReturn2, &elseBC);
  2553. // Add byte code for the else statement
  2554. LineInstr(bc, inode->lastChild->tokenPos);
  2555. bc->AddCode(&elseBC);
  2556. if( inode->lastChild->nodeType == snExpressionStatement && inode->lastChild->firstChild == 0 )
  2557. {
  2558. // Don't allow if( expr ) {} else;
  2559. Error(TXT_ELSE_WITH_EMPTY_STATEMENT, inode->lastChild);
  2560. }
  2561. if( !hasReturn1 )
  2562. {
  2563. // Add label for the end of else statement
  2564. bc->Label((short)afterElse);
  2565. }
  2566. // The if statement only has return if both alternatives have
  2567. *hasReturn = hasReturn1 && hasReturn2;
  2568. if( !origIsConstructorCalled && m_isConstructorCalled )
  2569. constructorCall2 = true;
  2570. }
  2571. else
  2572. {
  2573. // Add label for the end of if statement
  2574. bc->Label((short)afterLabel);
  2575. *hasReturn = false;
  2576. }
  2577. // Make sure both or neither conditions call a constructor
  2578. if( (constructorCall1 && !constructorCall2) ||
  2579. (constructorCall2 && !constructorCall1) )
  2580. {
  2581. Error(TXT_BOTH_CONDITIONS_MUST_CALL_CONSTRUCTOR, inode);
  2582. }
  2583. m_isConstructorCalled = origIsConstructorCalled || constructorCall1 || constructorCall2;
  2584. }
  2585. void asCCompiler::CompileForStatement(asCScriptNode *fnode, asCByteCode *bc)
  2586. {
  2587. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2588. AddVariableScope(true, true);
  2589. // We will use three labels for the for loop
  2590. int conditionLabel = nextLabel++;
  2591. int afterLabel = nextLabel++;
  2592. int continueLabel = nextLabel++;
  2593. int insideLabel = nextLabel++;
  2594. continueLabels.PushLast(continueLabel);
  2595. breakLabels.PushLast(afterLabel);
  2596. //---------------------------------------
  2597. // Compile the initialization statement
  2598. asCByteCode initBC(engine);
  2599. LineInstr(&initBC, fnode->firstChild->tokenPos);
  2600. if( fnode->firstChild->nodeType == snDeclaration )
  2601. CompileDeclaration(fnode->firstChild, &initBC);
  2602. else
  2603. CompileExpressionStatement(fnode->firstChild, &initBC);
  2604. //-----------------------------------
  2605. // Compile the condition statement
  2606. asSExprContext expr(engine);
  2607. asCScriptNode *second = fnode->firstChild->next;
  2608. if( second->firstChild )
  2609. {
  2610. int r = CompileAssignment(second->firstChild, &expr);
  2611. if( r >= 0 )
  2612. {
  2613. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2614. Error(TXT_EXPR_MUST_BE_BOOL, second);
  2615. else
  2616. {
  2617. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2618. ProcessDeferredParams(&expr);
  2619. ProcessPropertyGetAccessor(&expr, second);
  2620. // If expression is false exit the loop
  2621. ConvertToVariable(&expr);
  2622. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2623. expr.bc.Instr(asBC_ClrHi);
  2624. expr.bc.InstrDWORD(asBC_JNZ, insideLabel);
  2625. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2626. expr.bc.OptimizeLocally(tempVariableOffsets);
  2627. // Prepend the line instruction for the condition
  2628. asCByteCode tmp(engine);
  2629. LineInstr(&tmp, second->firstChild->tokenPos);
  2630. tmp.AddCode(&expr.bc);
  2631. expr.bc.AddCode(&tmp);
  2632. }
  2633. }
  2634. }
  2635. //---------------------------
  2636. // Compile the increment statement
  2637. asCByteCode nextBC(engine);
  2638. asCScriptNode *third = second->next;
  2639. if( third->nodeType == snExpressionStatement )
  2640. {
  2641. LineInstr(&nextBC, third->tokenPos);
  2642. CompileExpressionStatement(third, &nextBC);
  2643. }
  2644. //------------------------------
  2645. // Compile loop statement
  2646. bool hasReturn;
  2647. asCByteCode forBC(engine);
  2648. CompileStatement(fnode->lastChild, &hasReturn, &forBC);
  2649. //-------------------------------
  2650. // Join the code pieces
  2651. bc->AddCode(&initBC);
  2652. bc->InstrDWORD(asBC_JMP, conditionLabel);
  2653. bc->Label((short)insideLabel);
  2654. // Add a suspend bytecode inside the loop to guarantee
  2655. // that the application can suspend the execution
  2656. bc->Instr(asBC_SUSPEND);
  2657. bc->InstrPTR(asBC_JitEntry, 0);
  2658. LineInstr(bc, fnode->lastChild->tokenPos);
  2659. bc->AddCode(&forBC);
  2660. bc->Label((short)continueLabel);
  2661. bc->AddCode(&nextBC);
  2662. bc->Label((short)conditionLabel);
  2663. if( expr.bc.GetLastInstr() == -1 )
  2664. // There is no condition, so we just always jump
  2665. bc->InstrDWORD(asBC_JMP, insideLabel);
  2666. else
  2667. bc->AddCode(&expr.bc);
  2668. bc->Label((short)afterLabel);
  2669. continueLabels.PopLast();
  2670. breakLabels.PopLast();
  2671. // Deallocate variables in this block, in reverse order
  2672. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  2673. {
  2674. sVariable *v = variables->variables[n];
  2675. // Call variable destructors here, for variables not yet destroyed
  2676. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  2677. // Don't deallocate function parameters
  2678. if( v->stackOffset > 0 )
  2679. DeallocateVariable(v->stackOffset);
  2680. }
  2681. RemoveVariableScope();
  2682. }
  2683. void asCCompiler::CompileWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2684. {
  2685. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2686. AddVariableScope(true, true);
  2687. // We will use two labels for the while loop
  2688. int beforeLabel = nextLabel++;
  2689. int afterLabel = nextLabel++;
  2690. continueLabels.PushLast(beforeLabel);
  2691. breakLabels.PushLast(afterLabel);
  2692. // Add label before the expression
  2693. bc->Label((short)beforeLabel);
  2694. // Compile expression
  2695. asSExprContext expr(engine);
  2696. CompileAssignment(wnode->firstChild, &expr);
  2697. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2698. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2699. else
  2700. {
  2701. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2702. ProcessDeferredParams(&expr);
  2703. ProcessPropertyGetAccessor(&expr, wnode);
  2704. // Add byte code for the expression
  2705. ConvertToVariable(&expr);
  2706. // Jump to end of statement if expression is false
  2707. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2708. expr.bc.Instr(asBC_ClrHi);
  2709. expr.bc.InstrDWORD(asBC_JZ, afterLabel);
  2710. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2711. expr.bc.OptimizeLocally(tempVariableOffsets);
  2712. bc->AddCode(&expr.bc);
  2713. }
  2714. // Add a suspend bytecode inside the loop to guarantee
  2715. // that the application can suspend the execution
  2716. bc->Instr(asBC_SUSPEND);
  2717. bc->InstrPTR(asBC_JitEntry, 0);
  2718. // Compile statement
  2719. bool hasReturn;
  2720. asCByteCode whileBC(engine);
  2721. CompileStatement(wnode->lastChild, &hasReturn, &whileBC);
  2722. // Add byte code for the statement
  2723. LineInstr(bc, wnode->lastChild->tokenPos);
  2724. bc->AddCode(&whileBC);
  2725. // Jump to the expression
  2726. bc->InstrINT(asBC_JMP, beforeLabel);
  2727. // Add label after the statement
  2728. bc->Label((short)afterLabel);
  2729. continueLabels.PopLast();
  2730. breakLabels.PopLast();
  2731. RemoveVariableScope();
  2732. }
  2733. void asCCompiler::CompileDoWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2734. {
  2735. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2736. AddVariableScope(true, true);
  2737. // We will use two labels for the while loop
  2738. int beforeLabel = nextLabel++;
  2739. int beforeTest = nextLabel++;
  2740. int afterLabel = nextLabel++;
  2741. continueLabels.PushLast(beforeTest);
  2742. breakLabels.PushLast(afterLabel);
  2743. // Add label before the statement
  2744. bc->Label((short)beforeLabel);
  2745. // Compile statement
  2746. bool hasReturn;
  2747. asCByteCode whileBC(engine);
  2748. CompileStatement(wnode->firstChild, &hasReturn, &whileBC);
  2749. // Add byte code for the statement
  2750. LineInstr(bc, wnode->firstChild->tokenPos);
  2751. bc->AddCode(&whileBC);
  2752. // Add label before the expression
  2753. bc->Label((short)beforeTest);
  2754. // Add a suspend bytecode inside the loop to guarantee
  2755. // that the application can suspend the execution
  2756. bc->Instr(asBC_SUSPEND);
  2757. bc->InstrPTR(asBC_JitEntry, 0);
  2758. // Add a line instruction
  2759. LineInstr(bc, wnode->lastChild->tokenPos);
  2760. // Compile expression
  2761. asSExprContext expr(engine);
  2762. CompileAssignment(wnode->lastChild, &expr);
  2763. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2764. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2765. else
  2766. {
  2767. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2768. ProcessDeferredParams(&expr);
  2769. ProcessPropertyGetAccessor(&expr, wnode);
  2770. // Add byte code for the expression
  2771. ConvertToVariable(&expr);
  2772. // Jump to next iteration if expression is true
  2773. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2774. expr.bc.Instr(asBC_ClrHi);
  2775. expr.bc.InstrDWORD(asBC_JNZ, beforeLabel);
  2776. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2777. expr.bc.OptimizeLocally(tempVariableOffsets);
  2778. bc->AddCode(&expr.bc);
  2779. }
  2780. // Add label after the statement
  2781. bc->Label((short)afterLabel);
  2782. continueLabels.PopLast();
  2783. breakLabels.PopLast();
  2784. RemoveVariableScope();
  2785. }
  2786. void asCCompiler::CompileBreakStatement(asCScriptNode *node, asCByteCode *bc)
  2787. {
  2788. if( breakLabels.GetLength() == 0 )
  2789. {
  2790. Error(TXT_INVALID_BREAK, node);
  2791. return;
  2792. }
  2793. // Add destructor calls for all variables that will go out of scope
  2794. // Put this clean up in a block to allow exception handler to understand them
  2795. bc->Block(true);
  2796. asCVariableScope *vs = variables;
  2797. while( !vs->isBreakScope )
  2798. {
  2799. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2800. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2801. vs = vs->parent;
  2802. }
  2803. bc->Block(false);
  2804. bc->InstrINT(asBC_JMP, breakLabels[breakLabels.GetLength()-1]);
  2805. }
  2806. void asCCompiler::CompileContinueStatement(asCScriptNode *node, asCByteCode *bc)
  2807. {
  2808. if( continueLabels.GetLength() == 0 )
  2809. {
  2810. Error(TXT_INVALID_CONTINUE, node);
  2811. return;
  2812. }
  2813. // Add destructor calls for all variables that will go out of scope
  2814. // Put this clean up in a block to allow exception handler to understand them
  2815. bc->Block(true);
  2816. asCVariableScope *vs = variables;
  2817. while( !vs->isContinueScope )
  2818. {
  2819. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2820. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2821. vs = vs->parent;
  2822. }
  2823. bc->Block(false);
  2824. bc->InstrINT(asBC_JMP, continueLabels[continueLabels.GetLength()-1]);
  2825. }
  2826. void asCCompiler::CompileExpressionStatement(asCScriptNode *enode, asCByteCode *bc)
  2827. {
  2828. if( enode->firstChild )
  2829. {
  2830. // Compile the expression
  2831. asSExprContext expr(engine);
  2832. CompileAssignment(enode->firstChild, &expr);
  2833. // If we get here and there is still an unprocessed property
  2834. // accessor, then process it as a get access. Don't call if there is
  2835. // already a compile error, or we might report an error that is not valid
  2836. if( !hasCompileErrors )
  2837. ProcessPropertyGetAccessor(&expr, enode);
  2838. // Pop the value from the stack
  2839. if( !expr.type.dataType.IsPrimitive() )
  2840. expr.bc.Instr(asBC_PopPtr);
  2841. // Release temporary variables used by expression
  2842. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2843. ProcessDeferredParams(&expr);
  2844. expr.bc.OptimizeLocally(tempVariableOffsets);
  2845. bc->AddCode(&expr.bc);
  2846. }
  2847. }
  2848. void asCCompiler::PrepareTemporaryObject(asCScriptNode *node, asSExprContext *ctx, bool forceOnHeap)
  2849. {
  2850. // If the object already is stored in temporary variable then nothing needs to be done
  2851. // Note, a type can be temporary without being a variable, in which case it is holding off
  2852. // on releasing a previously used object.
  2853. if( ctx->type.isTemporary && ctx->type.isVariable &&
  2854. !(forceOnHeap && !IsVariableOnHeap(ctx->type.stackOffset)) )
  2855. {
  2856. // If the temporary object is currently not a reference
  2857. // the expression needs to be reevaluated to a reference
  2858. if( !ctx->type.dataType.IsReference() )
  2859. {
  2860. ctx->bc.Instr(asBC_PopPtr);
  2861. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  2862. ctx->type.dataType.MakeReference(true);
  2863. }
  2864. return;
  2865. }
  2866. // Allocate temporary variable
  2867. asCDataType dt = ctx->type.dataType;
  2868. dt.MakeReference(false);
  2869. dt.MakeReadOnly(false);
  2870. int offset = AllocateVariable(dt, true, forceOnHeap);
  2871. // Objects stored on the stack are not considered references
  2872. dt.MakeReference(IsVariableOnHeap(offset));
  2873. asCTypeInfo lvalue;
  2874. lvalue.Set(dt);
  2875. lvalue.isTemporary = true;
  2876. lvalue.stackOffset = (short)offset;
  2877. lvalue.isVariable = true;
  2878. lvalue.isExplicitHandle = ctx->type.isExplicitHandle;
  2879. if( !dt.IsObjectHandle() &&
  2880. dt.GetObjectType() && (dt.GetBehaviour()->copyconstruct || dt.GetBehaviour()->copyfactory) )
  2881. {
  2882. PrepareForAssignment(&lvalue.dataType, ctx, node, true);
  2883. // Use the copy constructor/factory when available
  2884. CallCopyConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, ctx, node);
  2885. }
  2886. else
  2887. {
  2888. // Allocate and construct the temporary object
  2889. int r = CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, node);
  2890. if( r < 0 )
  2891. {
  2892. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  2893. }
  2894. else
  2895. {
  2896. // Assign the object to the temporary variable
  2897. PrepareForAssignment(&lvalue.dataType, ctx, node, true);
  2898. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2899. r = PerformAssignment(&lvalue, &ctx->type, &ctx->bc, node);
  2900. if( r < 0 )
  2901. {
  2902. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  2903. }
  2904. // Pop the original reference
  2905. ctx->bc.Instr(asBC_PopPtr);
  2906. }
  2907. // If the expression was holding off on releasing a
  2908. // previously used object, we need to release it now
  2909. if( ctx->type.isTemporary )
  2910. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  2911. }
  2912. // Push the reference to the temporary variable on the stack
  2913. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2914. lvalue.dataType.MakeReference(IsVariableOnHeap(offset));
  2915. ctx->type = lvalue;
  2916. }
  2917. void asCCompiler::CompileReturnStatement(asCScriptNode *rnode, asCByteCode *bc)
  2918. {
  2919. // Get return type and location
  2920. sVariable *v = variables->GetVariable("return");
  2921. // Basic validations
  2922. if( v->type.GetSizeOnStackDWords() > 0 && !rnode->firstChild )
  2923. {
  2924. Error(TXT_MUST_RETURN_VALUE, rnode);
  2925. return;
  2926. }
  2927. else if( v->type.GetSizeOnStackDWords() == 0 && rnode->firstChild )
  2928. {
  2929. Error(TXT_CANT_RETURN_VALUE, rnode);
  2930. return;
  2931. }
  2932. // Compile the expression
  2933. if( rnode->firstChild )
  2934. {
  2935. // Compile the expression
  2936. asSExprContext expr(engine);
  2937. int r = CompileAssignment(rnode->firstChild, &expr);
  2938. if( r < 0 ) return;
  2939. if( v->type.IsReference() )
  2940. {
  2941. // The expression that gives the reference must not use any of the
  2942. // variables that must be destroyed upon exit, because then it means
  2943. // reference will stay alive while the clean-up is done, which could
  2944. // potentially mean that the reference is invalidated by the clean-up.
  2945. //
  2946. // When the function is returning a reference, the clean-up of the
  2947. // variables must be done before the evaluation of the expression.
  2948. //
  2949. // A reference to a global variable, or a class member for class methods
  2950. // should be allowed to be returned.
  2951. if( !(expr.type.dataType.IsReference() ||
  2952. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle())) )
  2953. {
  2954. // Clean up the potential deferred parameters
  2955. ProcessDeferredParams(&expr);
  2956. Error(TXT_NOT_VALID_REFERENCE, rnode);
  2957. return;
  2958. }
  2959. // No references to local variables, temporary variables, or parameters
  2960. // are allowed to be returned, since they go out of scope when the function
  2961. // returns. Even reference parameters are disallowed, since it is not possible
  2962. // to know the scope of them. The exception is the 'this' pointer, which
  2963. // is treated by the compiler as a local variable, but isn't really so.
  2964. if( (expr.type.isVariable && !(expr.type.stackOffset == 0 && outFunc->objectType)) || expr.type.isTemporary )
  2965. {
  2966. // Clean up the potential deferred parameters
  2967. ProcessDeferredParams(&expr);
  2968. Error(TXT_CANNOT_RETURN_REF_TO_LOCAL, rnode);
  2969. return;
  2970. }
  2971. // The type must match exactly as we cannot convert
  2972. // the reference without loosing the original value
  2973. if( !(v->type.IsEqualExceptConst(expr.type.dataType) ||
  2974. (expr.type.dataType.IsObject() &&
  2975. !expr.type.dataType.IsObjectHandle() &&
  2976. v->type.IsEqualExceptRefAndConst(expr.type.dataType))) ||
  2977. (!v->type.IsReadOnly() && expr.type.dataType.IsReadOnly()) )
  2978. {
  2979. // Clean up the potential deferred parameters
  2980. ProcessDeferredParams(&expr);
  2981. asCString str;
  2982. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2983. Error(str, rnode);
  2984. return;
  2985. }
  2986. // The expression must not have any deferred expressions, because the evaluation
  2987. // of these cannot be done without keeping the reference which is not safe
  2988. if( expr.deferredParams.GetLength() )
  2989. {
  2990. // Clean up the potential deferred parameters
  2991. ProcessDeferredParams(&expr);
  2992. Error(TXT_REF_CANT_BE_RETURNED_DEFERRED_PARAM, rnode);
  2993. return;
  2994. }
  2995. // Make sure the expression isn't using any local variables that
  2996. // will need to be cleaned up before the function completes
  2997. asCArray<int> usedVars;
  2998. expr.bc.GetVarsUsed(usedVars);
  2999. for( asUINT n = 0; n < usedVars.GetLength(); n++ )
  3000. {
  3001. int var = GetVariableSlot(usedVars[n]);
  3002. if( var != -1 )
  3003. {
  3004. asCDataType dt = variableAllocations[var];
  3005. if( dt.IsObject() )
  3006. {
  3007. ProcessDeferredParams(&expr);
  3008. Error(TXT_REF_CANT_BE_RETURNED_LOCAL_VARS, rnode);
  3009. return;
  3010. }
  3011. }
  3012. }
  3013. // All objects in the function must be cleaned up before the expression
  3014. // is evaluated, otherwise there is a possibility that the cleanup will
  3015. // invalidate the reference.
  3016. // Destroy the local variables before loading
  3017. // the reference into the register. This will
  3018. // be done before the expression is evaluated.
  3019. DestroyVariables(bc);
  3020. // For primitives the reference is already in the register,
  3021. // but for non-primitives the reference is on the stack so we
  3022. // need to load it into the register
  3023. if( !expr.type.dataType.IsPrimitive() )
  3024. {
  3025. if( !expr.type.dataType.IsObjectHandle() &&
  3026. expr.type.dataType.IsReference() )
  3027. expr.bc.Instr(asBC_RDSPtr);
  3028. expr.bc.Instr(asBC_PopRPtr);
  3029. }
  3030. // There are no temporaries to release so we're done
  3031. }
  3032. else // if( !v->type.IsReference() )
  3033. {
  3034. ProcessPropertyGetAccessor(&expr, rnode);
  3035. // Prepare the value for assignment
  3036. IsVariableInitialized(&expr.type, rnode->firstChild);
  3037. if( v->type.IsPrimitive() )
  3038. {
  3039. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  3040. // Implicitly convert the value to the return type
  3041. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  3042. // Verify that the conversion was successful
  3043. if( expr.type.dataType != v->type )
  3044. {
  3045. asCString str;
  3046. str.Format(TXT_NO_CONVERSION_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  3047. Error(str, rnode);
  3048. return;
  3049. }
  3050. else
  3051. {
  3052. ConvertToVariable(&expr);
  3053. // Clean up the local variables and process deferred parameters
  3054. DestroyVariables(&expr.bc);
  3055. ProcessDeferredParams(&expr);
  3056. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3057. // Load the variable in the register
  3058. if( v->type.GetSizeOnStackDWords() == 1 )
  3059. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  3060. else
  3061. expr.bc.InstrSHORT(asBC_CpyVtoR8, expr.type.stackOffset);
  3062. }
  3063. }
  3064. else if( v->type.IsObject() )
  3065. {
  3066. // Value types are returned on the stack, in a location
  3067. // that has been reserved by the calling function.
  3068. if( outFunc->DoesReturnOnStack() )
  3069. {
  3070. // TODO: runtime optimize: If the return type has a constructor that takes the type of the expression,
  3071. // it should be called directly instead of first converting the expression and
  3072. // then copy the value.
  3073. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  3074. {
  3075. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  3076. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  3077. {
  3078. asCString str;
  3079. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  3080. Error(str, rnode->firstChild);
  3081. return;
  3082. }
  3083. }
  3084. int offset = outFunc->objectType ? -AS_PTR_SIZE : 0;
  3085. if( v->type.GetObjectType()->beh.copyconstruct )
  3086. {
  3087. PrepareForAssignment(&v->type, &expr, rnode->firstChild, false);
  3088. CallCopyConstructor(v->type, offset, false, &expr.bc, &expr, rnode->firstChild, false, true);
  3089. }
  3090. else
  3091. {
  3092. // If the copy constructor doesn't exist, then a manual assignment needs to be done instead.
  3093. CallDefaultConstructor(v->type, offset, false, &expr.bc, rnode->firstChild, 0, true);
  3094. PrepareForAssignment(&v->type, &expr, rnode->firstChild, false);
  3095. expr.bc.InstrSHORT(asBC_PSF, (short)offset);
  3096. expr.bc.Instr(asBC_RDSPtr);
  3097. asSExprContext lexpr(engine);
  3098. lexpr.type.Set(v->type);
  3099. lexpr.type.isLValue = true;
  3100. PerformAssignment(&lexpr.type, &expr.type, &expr.bc, rnode->firstChild);
  3101. expr.bc.Instr(asBC_PopPtr);
  3102. // Release any temporary variable
  3103. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3104. }
  3105. // Clean up the local variables and process deferred parameters
  3106. DestroyVariables(&expr.bc);
  3107. ProcessDeferredParams(&expr);
  3108. }
  3109. else
  3110. {
  3111. asASSERT( v->type.GetObjectType()->flags & asOBJ_REF );
  3112. // Prepare the expression to be loaded into the object
  3113. // register. This will place the reference in local variable
  3114. PrepareArgument(&v->type, &expr, rnode->firstChild, false, 0);
  3115. // Pop the reference to the temporary variable
  3116. expr.bc.Instr(asBC_PopPtr);
  3117. // Clean up the local variables and process deferred parameters
  3118. DestroyVariables(&expr.bc);
  3119. ProcessDeferredParams(&expr);
  3120. // Load the object pointer into the object register
  3121. // LOADOBJ also clears the address in the variable
  3122. expr.bc.InstrSHORT(asBC_LOADOBJ, expr.type.stackOffset);
  3123. // LOADOBJ cleared the address in the variable so the object will not be freed
  3124. // here, but the temporary variable must still be freed so the slot can be reused
  3125. // By releasing without the bytecode we do just that.
  3126. ReleaseTemporaryVariable(expr.type, 0);
  3127. }
  3128. }
  3129. }
  3130. expr.bc.OptimizeLocally(tempVariableOffsets);
  3131. bc->AddCode(&expr.bc);
  3132. }
  3133. else
  3134. {
  3135. // For functions that don't return anything
  3136. // we just detroy the local variables
  3137. DestroyVariables(bc);
  3138. }
  3139. // Jump to the end of the function
  3140. bc->InstrINT(asBC_JMP, 0);
  3141. }
  3142. void asCCompiler::DestroyVariables(asCByteCode *bc)
  3143. {
  3144. // Call destructor on all variables except for the function parameters
  3145. // Put the clean-up in a block to allow exception handler to understand this
  3146. bc->Block(true);
  3147. asCVariableScope *vs = variables;
  3148. while( vs )
  3149. {
  3150. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  3151. if( vs->variables[n]->stackOffset > 0 )
  3152. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  3153. vs = vs->parent;
  3154. }
  3155. bc->Block(false);
  3156. }
  3157. void asCCompiler::AddVariableScope(bool isBreakScope, bool isContinueScope)
  3158. {
  3159. variables = asNEW(asCVariableScope)(variables);
  3160. if( variables == 0 )
  3161. {
  3162. // Out of memory
  3163. return;
  3164. }
  3165. variables->isBreakScope = isBreakScope;
  3166. variables->isContinueScope = isContinueScope;
  3167. }
  3168. void asCCompiler::RemoveVariableScope()
  3169. {
  3170. if( variables )
  3171. {
  3172. asCVariableScope *var = variables;
  3173. variables = variables->parent;
  3174. asDELETE(var,asCVariableScope);
  3175. }
  3176. }
  3177. void asCCompiler::Error(const asCString &msg, asCScriptNode *node)
  3178. {
  3179. asCString str;
  3180. int r = 0, c = 0;
  3181. asASSERT( node );
  3182. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3183. builder->WriteError(script->name, msg, r, c);
  3184. hasCompileErrors = true;
  3185. }
  3186. void asCCompiler::Warning(const asCString &msg, asCScriptNode *node)
  3187. {
  3188. asCString str;
  3189. int r = 0, c = 0;
  3190. asASSERT( node );
  3191. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3192. builder->WriteWarning(script->name, msg, r, c);
  3193. }
  3194. void asCCompiler::Information(const asCString &msg, asCScriptNode *node)
  3195. {
  3196. asCString str;
  3197. int r = 0, c = 0;
  3198. asASSERT( node );
  3199. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3200. builder->WriteInfo(script->name, msg, r, c, false);
  3201. }
  3202. void asCCompiler::PrintMatchingFuncs(asCArray<int> &funcs, asCScriptNode *node)
  3203. {
  3204. int r = 0, c = 0;
  3205. asASSERT( node );
  3206. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3207. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  3208. {
  3209. asIScriptFunction *func = builder->GetFunctionDescription(funcs[n]);
  3210. builder->WriteInfo(script->name, func->GetDeclaration(true), r, c, false);
  3211. }
  3212. }
  3213. int asCCompiler::AllocateVariableNotIn(const asCDataType &type, bool isTemporary, bool forceOnHeap, asSExprContext *ctx)
  3214. {
  3215. int l = int(reservedVariables.GetLength());
  3216. ctx->bc.GetVarsUsed(reservedVariables);
  3217. int var = AllocateVariable(type, isTemporary, forceOnHeap);
  3218. reservedVariables.SetLength(l);
  3219. return var;
  3220. }
  3221. int asCCompiler::AllocateVariable(const asCDataType &type, bool isTemporary, bool forceOnHeap)
  3222. {
  3223. asCDataType t(type);
  3224. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 1 )
  3225. t.SetTokenType(ttInt);
  3226. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 2 )
  3227. t.SetTokenType(ttDouble);
  3228. // Only null handles have the token type unrecognized token
  3229. asASSERT( t.IsObjectHandle() || t.GetTokenType() != ttUnrecognizedToken );
  3230. bool isOnHeap = true;
  3231. if( t.IsPrimitive() ||
  3232. (t.GetObjectType() && (t.GetObjectType()->GetFlags() & asOBJ_VALUE) && !forceOnHeap) )
  3233. {
  3234. // Primitives and value types (unless overridden) are allocated on the stack
  3235. isOnHeap = false;
  3236. }
  3237. // Find a free location with the same type
  3238. for( asUINT n = 0; n < freeVariables.GetLength(); n++ )
  3239. {
  3240. int slot = freeVariables[n];
  3241. if( variableAllocations[slot].IsEqualExceptConst(t) &&
  3242. variableIsTemporary[slot] == isTemporary &&
  3243. variableIsOnHeap[slot] == isOnHeap )
  3244. {
  3245. // We can't return by slot, must count variable sizes
  3246. int offset = GetVariableOffset(slot);
  3247. // Verify that it is not in the list of reserved variables
  3248. bool isUsed = false;
  3249. if( reservedVariables.GetLength() )
  3250. isUsed = reservedVariables.Exists(offset);
  3251. if( !isUsed )
  3252. {
  3253. if( n != freeVariables.GetLength() - 1 )
  3254. freeVariables[n] = freeVariables.PopLast();
  3255. else
  3256. freeVariables.PopLast();
  3257. if( isTemporary )
  3258. tempVariables.PushLast(offset);
  3259. return offset;
  3260. }
  3261. }
  3262. }
  3263. variableAllocations.PushLast(t);
  3264. variableIsTemporary.PushLast(isTemporary);
  3265. variableIsOnHeap.PushLast(isOnHeap);
  3266. int offset = GetVariableOffset((int)variableAllocations.GetLength()-1);
  3267. if( isTemporary )
  3268. {
  3269. // Add offset to the currently allocated temporary variables
  3270. tempVariables.PushLast(offset);
  3271. // Add offset to all known offsets to temporary variables, whether allocated or not
  3272. tempVariableOffsets.PushLast(offset);
  3273. }
  3274. return offset;
  3275. }
  3276. int asCCompiler::GetVariableOffset(int varIndex)
  3277. {
  3278. // Return offset to the last dword on the stack
  3279. int varOffset = 1;
  3280. for( int n = 0; n < varIndex; n++ )
  3281. {
  3282. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  3283. varOffset += variableAllocations[n].GetSizeInMemoryDWords();
  3284. else
  3285. varOffset += variableAllocations[n].GetSizeOnStackDWords();
  3286. }
  3287. if( varIndex < (int)variableAllocations.GetLength() )
  3288. {
  3289. int size;
  3290. if( !variableIsOnHeap[varIndex] && variableAllocations[varIndex].IsObject() )
  3291. size = variableAllocations[varIndex].GetSizeInMemoryDWords();
  3292. else
  3293. size = variableAllocations[varIndex].GetSizeOnStackDWords();
  3294. if( size > 1 )
  3295. varOffset += size-1;
  3296. }
  3297. return varOffset;
  3298. }
  3299. int asCCompiler::GetVariableSlot(int offset)
  3300. {
  3301. int varOffset = 1;
  3302. for( asUINT n = 0; n < variableAllocations.GetLength(); n++ )
  3303. {
  3304. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  3305. varOffset += -1 + variableAllocations[n].GetSizeInMemoryDWords();
  3306. else
  3307. varOffset += -1 + variableAllocations[n].GetSizeOnStackDWords();
  3308. if( varOffset == offset )
  3309. return n;
  3310. varOffset++;
  3311. }
  3312. return -1;
  3313. }
  3314. bool asCCompiler::IsVariableOnHeap(int offset)
  3315. {
  3316. int varSlot = GetVariableSlot(offset);
  3317. if( varSlot < 0 )
  3318. {
  3319. // This happens for function arguments that are considered as on the heap
  3320. return true;
  3321. }
  3322. return variableIsOnHeap[varSlot];
  3323. }
  3324. void asCCompiler::DeallocateVariable(int offset)
  3325. {
  3326. // Remove temporary variable
  3327. int n;
  3328. for( n = 0; n < (int)tempVariables.GetLength(); n++ )
  3329. {
  3330. if( offset == tempVariables[n] )
  3331. {
  3332. if( n == (int)tempVariables.GetLength()-1 )
  3333. tempVariables.PopLast();
  3334. else
  3335. tempVariables[n] = tempVariables.PopLast();
  3336. break;
  3337. }
  3338. }
  3339. n = GetVariableSlot(offset);
  3340. if( n != -1 )
  3341. {
  3342. freeVariables.PushLast(n);
  3343. return;
  3344. }
  3345. // We might get here if the variable was implicitly declared
  3346. // because it was use before a formal declaration, in this case
  3347. // the offset is 0x7FFF
  3348. asASSERT(offset == 0x7FFF);
  3349. }
  3350. void asCCompiler::ReleaseTemporaryVariable(asCTypeInfo &t, asCByteCode *bc)
  3351. {
  3352. if( t.isTemporary )
  3353. {
  3354. ReleaseTemporaryVariable(t.stackOffset, bc);
  3355. t.isTemporary = false;
  3356. }
  3357. }
  3358. void asCCompiler::ReleaseTemporaryVariable(int offset, asCByteCode *bc)
  3359. {
  3360. if( bc )
  3361. {
  3362. // We need to call the destructor on the true variable type
  3363. int n = GetVariableSlot(offset);
  3364. asASSERT( n >= 0 );
  3365. if( n >= 0 )
  3366. {
  3367. asCDataType dt = variableAllocations[n];
  3368. bool isOnHeap = variableIsOnHeap[n];
  3369. // Call destructor
  3370. CallDestructor(dt, offset, isOnHeap, bc);
  3371. }
  3372. }
  3373. DeallocateVariable(offset);
  3374. }
  3375. void asCCompiler::Dereference(asSExprContext *ctx, bool generateCode)
  3376. {
  3377. if( ctx->type.dataType.IsReference() )
  3378. {
  3379. if( ctx->type.dataType.IsObject() )
  3380. {
  3381. ctx->type.dataType.MakeReference(false);
  3382. if( generateCode )
  3383. ctx->bc.Instr(asBC_RDSPtr);
  3384. }
  3385. else
  3386. {
  3387. // This should never happen as primitives are treated differently
  3388. asASSERT(false);
  3389. }
  3390. }
  3391. }
  3392. bool asCCompiler::IsVariableInitialized(asCTypeInfo *type, asCScriptNode *node)
  3393. {
  3394. // No need to check if there is no variable scope
  3395. if( variables == 0 ) return true;
  3396. // Temporary variables are assumed to be initialized
  3397. if( type->isTemporary ) return true;
  3398. // Verify that it is a variable
  3399. if( !type->isVariable ) return true;
  3400. // Find the variable
  3401. sVariable *v = variables->GetVariableByOffset(type->stackOffset);
  3402. // The variable isn't found if it is a constant, in which case it is guaranteed to be initialized
  3403. if( v == 0 ) return true;
  3404. if( v->isInitialized ) return true;
  3405. // Complex types don't need this test
  3406. if( v->type.IsObject() ) return true;
  3407. // Mark as initialized so that the user will not be bothered again
  3408. v->isInitialized = true;
  3409. // Write warning
  3410. asCString str;
  3411. str.Format(TXT_s_NOT_INITIALIZED, (const char *)v->name.AddressOf());
  3412. Warning(str, node);
  3413. return false;
  3414. }
  3415. void asCCompiler::PrepareOperand(asSExprContext *ctx, asCScriptNode *node)
  3416. {
  3417. // Check if the variable is initialized (if it indeed is a variable)
  3418. IsVariableInitialized(&ctx->type, node);
  3419. asCDataType to = ctx->type.dataType;
  3420. to.MakeReference(false);
  3421. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  3422. ProcessDeferredParams(ctx);
  3423. }
  3424. void asCCompiler::PrepareForAssignment(asCDataType *lvalue, asSExprContext *rctx, asCScriptNode *node, bool toTemporary, asSExprContext *lvalueExpr)
  3425. {
  3426. // Reserve the temporary variables used in the lvalue expression so they won't end up being used by the rvalue too
  3427. int l = int(reservedVariables.GetLength());
  3428. if( lvalueExpr ) lvalueExpr->bc.GetVarsUsed(reservedVariables);
  3429. ProcessPropertyGetAccessor(rctx, node);
  3430. // Make sure the rvalue is initialized if it is a variable
  3431. IsVariableInitialized(&rctx->type, node);
  3432. if( lvalue->IsPrimitive() )
  3433. {
  3434. if( rctx->type.dataType.IsPrimitive() )
  3435. {
  3436. if( rctx->type.dataType.IsReference() )
  3437. {
  3438. // Cannot do implicit conversion of references so we first convert the reference to a variable
  3439. ConvertToVariableNotIn(rctx, lvalueExpr);
  3440. }
  3441. }
  3442. // Implicitly convert the value to the right type
  3443. ImplicitConversion(rctx, *lvalue, node, asIC_IMPLICIT_CONV);
  3444. // Check data type
  3445. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  3446. {
  3447. asCString str;
  3448. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  3449. Error(str, node);
  3450. rctx->type.SetDummy();
  3451. }
  3452. // Make sure the rvalue is a variable
  3453. if( !rctx->type.isVariable )
  3454. ConvertToVariableNotIn(rctx, lvalueExpr);
  3455. }
  3456. else
  3457. {
  3458. asCDataType to = *lvalue;
  3459. to.MakeReference(false);
  3460. // TODO: ImplicitConversion should know to do this by itself
  3461. // First convert to a handle which will do a reference cast
  3462. if( !lvalue->IsObjectHandle() &&
  3463. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  3464. to.MakeHandle(true);
  3465. // Don't allow the implicit conversion to create an object
  3466. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, !toTemporary);
  3467. if( !lvalue->IsObjectHandle() &&
  3468. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  3469. {
  3470. // Then convert to a reference, which will validate the handle
  3471. to.MakeHandle(false);
  3472. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, !toTemporary);
  3473. }
  3474. // Check data type
  3475. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  3476. {
  3477. asCString str;
  3478. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  3479. Error(str, node);
  3480. }
  3481. else
  3482. {
  3483. // If the assignment will be made with the copy behaviour then the rvalue must not be a reference
  3484. if( lvalue->IsObject() )
  3485. asASSERT(!rctx->type.dataType.IsReference());
  3486. }
  3487. }
  3488. // Unreserve variables
  3489. reservedVariables.SetLength(l);
  3490. }
  3491. bool asCCompiler::IsLValue(asCTypeInfo &type)
  3492. {
  3493. if( !type.isLValue ) return false;
  3494. if( type.dataType.IsReadOnly() ) return false;
  3495. if( !type.dataType.IsObject() && !type.isVariable && !type.dataType.IsReference() ) return false;
  3496. return true;
  3497. }
  3498. int asCCompiler::PerformAssignment(asCTypeInfo *lvalue, asCTypeInfo *rvalue, asCByteCode *bc, asCScriptNode *node)
  3499. {
  3500. if( lvalue->dataType.IsReadOnly() )
  3501. {
  3502. Error(TXT_REF_IS_READ_ONLY, node);
  3503. return -1;
  3504. }
  3505. if( lvalue->dataType.IsPrimitive() )
  3506. {
  3507. if( lvalue->isVariable )
  3508. {
  3509. // Copy the value between the variables directly
  3510. if( lvalue->dataType.GetSizeInMemoryDWords() == 1 )
  3511. bc->InstrW_W(asBC_CpyVtoV4, lvalue->stackOffset, rvalue->stackOffset);
  3512. else
  3513. bc->InstrW_W(asBC_CpyVtoV8, lvalue->stackOffset, rvalue->stackOffset);
  3514. // Mark variable as initialized
  3515. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3516. if( v ) v->isInitialized = true;
  3517. }
  3518. else if( lvalue->dataType.IsReference() )
  3519. {
  3520. // Copy the value of the variable to the reference in the register
  3521. int s = lvalue->dataType.GetSizeInMemoryBytes();
  3522. if( s == 1 )
  3523. bc->InstrSHORT(asBC_WRTV1, rvalue->stackOffset);
  3524. else if( s == 2 )
  3525. bc->InstrSHORT(asBC_WRTV2, rvalue->stackOffset);
  3526. else if( s == 4 )
  3527. bc->InstrSHORT(asBC_WRTV4, rvalue->stackOffset);
  3528. else if( s == 8 )
  3529. bc->InstrSHORT(asBC_WRTV8, rvalue->stackOffset);
  3530. }
  3531. else
  3532. {
  3533. Error(TXT_NOT_VALID_LVALUE, node);
  3534. return -1;
  3535. }
  3536. }
  3537. else if( !lvalue->isExplicitHandle )
  3538. {
  3539. asSExprContext ctx(engine);
  3540. ctx.type = *lvalue;
  3541. Dereference(&ctx, true);
  3542. *lvalue = ctx.type;
  3543. bc->AddCode(&ctx.bc);
  3544. // TODO: Should find the opAssign method that implements the default copy behaviour.
  3545. // The beh->copy member will be removed.
  3546. asSTypeBehaviour *beh = lvalue->dataType.GetBehaviour();
  3547. if( beh->copy )
  3548. {
  3549. // Call the copy operator
  3550. asCScriptFunction *descr = builder->GetFunctionDescription(beh->copy);
  3551. if( descr->funcType == asFUNC_VIRTUAL )
  3552. bc->Call(asBC_CALLINTF, beh->copy, 2*AS_PTR_SIZE);
  3553. else if( descr->funcType == asFUNC_SCRIPT )
  3554. bc->Call(asBC_CALL, beh->copy, 2*AS_PTR_SIZE);
  3555. else
  3556. {
  3557. asASSERT( descr->funcType == asFUNC_SYSTEM );
  3558. bc->Call(asBC_CALLSYS, beh->copy, 2*AS_PTR_SIZE);
  3559. }
  3560. asASSERT( descr->returnType.IsReference() );
  3561. bc->Instr(asBC_PshRPtr);
  3562. }
  3563. else
  3564. {
  3565. // Default copy operator
  3566. if( lvalue->dataType.GetSizeInMemoryDWords() == 0 ||
  3567. !(lvalue->dataType.GetObjectType()->flags & asOBJ_POD) )
  3568. {
  3569. asCString msg;
  3570. msg.Format(TXT_NO_DEFAULT_COPY_OP_FOR_s, lvalue->dataType.GetObjectType()->name.AddressOf());
  3571. Error(msg, node);
  3572. return -1;
  3573. }
  3574. // Copy larger data types from a reference
  3575. // TODO: runtime optimize: COPY should pop both arguments and store the reference in the register.
  3576. bc->InstrSHORT_DW(asBC_COPY, (short)lvalue->dataType.GetSizeInMemoryDWords(), engine->GetTypeIdFromDataType(lvalue->dataType));
  3577. }
  3578. }
  3579. else
  3580. {
  3581. // TODO: The object handle can be stored in a variable as well
  3582. if( !lvalue->dataType.IsReference() )
  3583. {
  3584. Error(TXT_NOT_VALID_REFERENCE, node);
  3585. return -1;
  3586. }
  3587. bc->InstrPTR(asBC_REFCPY, lvalue->dataType.GetObjectType());
  3588. // Mark variable as initialized
  3589. if( variables )
  3590. {
  3591. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3592. if( v ) v->isInitialized = true;
  3593. }
  3594. }
  3595. return 0;
  3596. }
  3597. bool asCCompiler::CompileRefCast(asSExprContext *ctx, const asCDataType &to, bool isExplicit, asCScriptNode *node, bool generateCode)
  3598. {
  3599. bool conversionDone = false;
  3600. asCArray<int> ops;
  3601. asUINT n;
  3602. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT )
  3603. {
  3604. // We need it to be a reference
  3605. if( !ctx->type.dataType.IsReference() )
  3606. {
  3607. asCDataType to = ctx->type.dataType;
  3608. to.MakeReference(true);
  3609. ImplicitConversion(ctx, to, 0, isExplicit ? asIC_EXPLICIT_REF_CAST : asIC_IMPLICIT_CONV, generateCode);
  3610. }
  3611. if( isExplicit )
  3612. {
  3613. // Allow dynamic cast between object handles (only for script objects).
  3614. // At run time this may result in a null handle,
  3615. // which when used will throw an exception
  3616. conversionDone = true;
  3617. if( generateCode )
  3618. {
  3619. ctx->bc.InstrDWORD(asBC_Cast, engine->GetTypeIdFromDataType(to));
  3620. // Allocate a temporary variable for the returned object
  3621. int returnOffset = AllocateVariable(to, true);
  3622. // Move the pointer from the object register to the temporary variable
  3623. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  3624. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  3625. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3626. ctx->type.SetVariable(to, returnOffset, true);
  3627. ctx->type.dataType.MakeReference(true);
  3628. }
  3629. else
  3630. {
  3631. ctx->type.dataType = to;
  3632. ctx->type.dataType.MakeReference(true);
  3633. }
  3634. }
  3635. else
  3636. {
  3637. if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3638. {
  3639. conversionDone = true;
  3640. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3641. }
  3642. }
  3643. }
  3644. else
  3645. {
  3646. // Find a suitable registered behaviour
  3647. asSTypeBehaviour *beh = &ctx->type.dataType.GetObjectType()->beh;
  3648. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3649. {
  3650. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3651. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3652. {
  3653. int funcId = beh->operators[n+1];
  3654. // Is the operator for the output type?
  3655. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3656. if( func->returnType.GetObjectType() != to.GetObjectType() )
  3657. continue;
  3658. ops.PushLast(funcId);
  3659. }
  3660. }
  3661. // It shouldn't be possible to have more than one
  3662. asASSERT( ops.GetLength() <= 1 );
  3663. // Should only have one behaviour for each output type
  3664. if( ops.GetLength() == 1 )
  3665. {
  3666. if( generateCode )
  3667. {
  3668. // TODO: runtime optimize: Instead of producing bytecode for checking if the handle is
  3669. // null, we can create a special CALLSYS instruction that checks
  3670. // if the object pointer is null and if so sets the object register
  3671. // to null directly without executing the function.
  3672. //
  3673. // Alternatively I could force the ref cast behaviours be global
  3674. // functions with 1 parameter, even though they should still be
  3675. // registered with RegisterObjectBehaviour()
  3676. // Add code to avoid calling the cast behaviour if the handle is already null,
  3677. // because that will raise a null pointer exception due to the cast behaviour
  3678. // being a class method, and the this pointer cannot be null.
  3679. if( ctx->type.isVariable )
  3680. ctx->bc.Instr(asBC_PopPtr);
  3681. else
  3682. {
  3683. Dereference(ctx, true);
  3684. ConvertToVariable(ctx);
  3685. }
  3686. // TODO: runtime optimize: should have immediate comparison for null pointer
  3687. int offset = AllocateVariable(asCDataType::CreateNullHandle(), true);
  3688. // TODO: runtime optimize: ClrVPtr is not necessary, because the VM should initialize the variable to null anyway (it is currently not done for null pointers though)
  3689. ctx->bc.InstrSHORT(asBC_ClrVPtr, (asWORD)offset);
  3690. ctx->bc.InstrW_W(asBC_CmpPtr, ctx->type.stackOffset, offset);
  3691. DeallocateVariable(offset);
  3692. int afterLabel = nextLabel++;
  3693. ctx->bc.InstrDWORD(asBC_JZ, afterLabel);
  3694. // Call the cast operator
  3695. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3696. ctx->bc.Instr(asBC_RDSPtr);
  3697. ctx->type.dataType.MakeReference(false);
  3698. asCTypeInfo objType = ctx->type;
  3699. asCArray<asSExprContext *> args;
  3700. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  3701. ctx->bc.Instr(asBC_PopPtr);
  3702. int endLabel = nextLabel++;
  3703. ctx->bc.InstrINT(asBC_JMP, endLabel);
  3704. ctx->bc.Label((short)afterLabel);
  3705. // Make a NULL pointer
  3706. ctx->bc.InstrSHORT(asBC_ClrVPtr, ctx->type.stackOffset);
  3707. ctx->bc.Label((short)endLabel);
  3708. // Since we're receiving a handle, we can release the original variable
  3709. ReleaseTemporaryVariable(objType, &ctx->bc);
  3710. // Push the reference to the handle on the stack
  3711. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3712. }
  3713. else
  3714. {
  3715. asCScriptFunction *func = engine->scriptFunctions[ops[0]];
  3716. ctx->type.Set(func->returnType);
  3717. }
  3718. }
  3719. else if( ops.GetLength() == 0 )
  3720. {
  3721. // Check for the generic ref cast behaviour
  3722. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3723. {
  3724. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3725. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3726. {
  3727. int funcId = beh->operators[n+1];
  3728. // Does the operator take the ?&out parameter?
  3729. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3730. if( func->parameterTypes.GetLength() != 1 ||
  3731. func->parameterTypes[0].GetTokenType() != ttQuestion ||
  3732. func->inOutFlags[0] != asTM_OUTREF )
  3733. continue;
  3734. ops.PushLast(funcId);
  3735. }
  3736. }
  3737. // It shouldn't be possible to have more than one
  3738. asASSERT( ops.GetLength() <= 1 );
  3739. if( ops.GetLength() == 1 )
  3740. {
  3741. if( generateCode )
  3742. {
  3743. asASSERT(to.IsObjectHandle());
  3744. // Allocate a temporary variable of the requested handle type
  3745. int stackOffset = AllocateVariableNotIn(to, true, false, ctx);
  3746. // Pass the reference of that variable to the function as output parameter
  3747. asCDataType toRef(to);
  3748. toRef.MakeReference(true);
  3749. asCArray<asSExprContext *> args;
  3750. asSExprContext arg(engine);
  3751. arg.bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3752. // Don't mark the variable as temporary, so it won't be freed too early
  3753. arg.type.SetVariable(toRef, stackOffset, false);
  3754. arg.type.isLValue = true;
  3755. arg.type.isExplicitHandle = true;
  3756. args.PushLast(&arg);
  3757. asCTypeInfo prev = ctx->type;
  3758. // Call the behaviour method
  3759. MakeFunctionCall(ctx, ops[0], ctx->type.dataType.GetObjectType(), args, node);
  3760. // Release previous temporary variable
  3761. ReleaseTemporaryVariable(prev, &ctx->bc);
  3762. // Use the reference to the variable as the result of the expression
  3763. // Now we can mark the variable as temporary
  3764. ctx->type.SetVariable(toRef, stackOffset, true);
  3765. ctx->bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3766. }
  3767. else
  3768. {
  3769. // All casts are legal
  3770. ctx->type.Set(to);
  3771. }
  3772. }
  3773. }
  3774. }
  3775. return conversionDone;
  3776. }
  3777. asUINT asCCompiler::ImplicitConvPrimitiveToPrimitive(asSExprContext *ctx, const asCDataType &toOrig, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  3778. {
  3779. asCDataType to = toOrig;
  3780. to.MakeReference(false);
  3781. asASSERT( !ctx->type.dataType.IsReference() );
  3782. // Maybe no conversion is needed
  3783. if( to.IsEqualExceptConst(ctx->type.dataType) )
  3784. {
  3785. // A primitive is const or not
  3786. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3787. return asCC_NO_CONV;
  3788. }
  3789. // Determine the cost of this conversion
  3790. asUINT cost = asCC_NO_CONV;
  3791. if( (to.IsIntegerType() || to.IsUnsignedType()) && (ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType()) )
  3792. cost = asCC_INT_FLOAT_CONV;
  3793. else if( (to.IsFloatType() || to.IsDoubleType()) && (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType()) )
  3794. cost = asCC_INT_FLOAT_CONV;
  3795. else if( to.IsUnsignedType() && ctx->type.dataType.IsIntegerType() )
  3796. cost = asCC_SIGNED_CONV;
  3797. else if( to.IsIntegerType() && ctx->type.dataType.IsUnsignedType() )
  3798. cost = asCC_SIGNED_CONV;
  3799. else if( to.GetSizeInMemoryBytes() || ctx->type.dataType.GetSizeInMemoryBytes() )
  3800. cost = asCC_PRIMITIVE_SIZE_CONV;
  3801. // Start by implicitly converting constant values
  3802. if( ctx->type.isConstant )
  3803. {
  3804. ImplicitConversionConstant(ctx, to, node, convType);
  3805. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3806. return cost;
  3807. }
  3808. // Allow implicit conversion between numbers
  3809. if( generateCode )
  3810. {
  3811. // When generating the code the decision has already been made, so we don't bother determining the cost
  3812. // Convert smaller types to 32bit first
  3813. int s = ctx->type.dataType.GetSizeInMemoryBytes();
  3814. if( s < 4 )
  3815. {
  3816. ConvertToTempVariable(ctx);
  3817. if( ctx->type.dataType.IsIntegerType() )
  3818. {
  3819. if( s == 1 )
  3820. ctx->bc.InstrSHORT(asBC_sbTOi, ctx->type.stackOffset);
  3821. else if( s == 2 )
  3822. ctx->bc.InstrSHORT(asBC_swTOi, ctx->type.stackOffset);
  3823. ctx->type.dataType.SetTokenType(ttInt);
  3824. }
  3825. else if( ctx->type.dataType.IsUnsignedType() )
  3826. {
  3827. if( s == 1 )
  3828. ctx->bc.InstrSHORT(asBC_ubTOi, ctx->type.stackOffset);
  3829. else if( s == 2 )
  3830. ctx->bc.InstrSHORT(asBC_uwTOi, ctx->type.stackOffset);
  3831. ctx->type.dataType.SetTokenType(ttUInt);
  3832. }
  3833. }
  3834. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1 && !to.IsEnumType()) ||
  3835. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  3836. {
  3837. if( ctx->type.dataType.IsIntegerType() ||
  3838. ctx->type.dataType.IsUnsignedType() )
  3839. {
  3840. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3841. {
  3842. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3843. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3844. }
  3845. else
  3846. {
  3847. ConvertToTempVariable(ctx);
  3848. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3849. int offset = AllocateVariable(to, true);
  3850. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3851. ctx->type.SetVariable(to, offset, true);
  3852. }
  3853. }
  3854. else if( ctx->type.dataType.IsFloatType() )
  3855. {
  3856. ConvertToTempVariable(ctx);
  3857. ctx->bc.InstrSHORT(asBC_fTOi, ctx->type.stackOffset);
  3858. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3859. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3860. }
  3861. else if( ctx->type.dataType.IsDoubleType() )
  3862. {
  3863. ConvertToTempVariable(ctx);
  3864. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3865. int offset = AllocateVariable(to, true);
  3866. ctx->bc.InstrW_W(asBC_dTOi, offset, ctx->type.stackOffset);
  3867. ctx->type.SetVariable(to, offset, true);
  3868. }
  3869. // Convert to smaller integer if necessary
  3870. int s = to.GetSizeInMemoryBytes();
  3871. if( s < 4 )
  3872. {
  3873. ConvertToTempVariable(ctx);
  3874. if( s == 1 )
  3875. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3876. else if( s == 2 )
  3877. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3878. }
  3879. }
  3880. if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  3881. {
  3882. if( ctx->type.dataType.IsIntegerType() ||
  3883. ctx->type.dataType.IsUnsignedType() )
  3884. {
  3885. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3886. {
  3887. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3888. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3889. }
  3890. else
  3891. {
  3892. ConvertToTempVariable(ctx);
  3893. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3894. int offset = AllocateVariable(to, true);
  3895. if( ctx->type.dataType.IsUnsignedType() )
  3896. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3897. else
  3898. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3899. ctx->type.SetVariable(to, offset, true);
  3900. }
  3901. }
  3902. else if( ctx->type.dataType.IsFloatType() )
  3903. {
  3904. ConvertToTempVariable(ctx);
  3905. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3906. int offset = AllocateVariable(to, true);
  3907. ctx->bc.InstrW_W(asBC_fTOi64, offset, ctx->type.stackOffset);
  3908. ctx->type.SetVariable(to, offset, true);
  3909. }
  3910. else if( ctx->type.dataType.IsDoubleType() )
  3911. {
  3912. ConvertToTempVariable(ctx);
  3913. ctx->bc.InstrSHORT(asBC_dTOi64, ctx->type.stackOffset);
  3914. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3915. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3916. }
  3917. }
  3918. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  3919. {
  3920. if( ctx->type.dataType.IsIntegerType() ||
  3921. ctx->type.dataType.IsUnsignedType() )
  3922. {
  3923. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3924. {
  3925. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3926. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3927. }
  3928. else
  3929. {
  3930. ConvertToTempVariable(ctx);
  3931. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3932. int offset = AllocateVariable(to, true);
  3933. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3934. ctx->type.SetVariable(to, offset, true);
  3935. }
  3936. }
  3937. else if( ctx->type.dataType.IsFloatType() )
  3938. {
  3939. ConvertToTempVariable(ctx);
  3940. ctx->bc.InstrSHORT(asBC_fTOu, ctx->type.stackOffset);
  3941. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3942. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3943. }
  3944. else if( ctx->type.dataType.IsDoubleType() )
  3945. {
  3946. ConvertToTempVariable(ctx);
  3947. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3948. int offset = AllocateVariable(to, true);
  3949. ctx->bc.InstrW_W(asBC_dTOu, offset, ctx->type.stackOffset);
  3950. ctx->type.SetVariable(to, offset, true);
  3951. }
  3952. // Convert to smaller integer if necessary
  3953. int s = to.GetSizeInMemoryBytes();
  3954. if( s < 4 )
  3955. {
  3956. ConvertToTempVariable(ctx);
  3957. if( s == 1 )
  3958. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3959. else if( s == 2 )
  3960. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3961. }
  3962. }
  3963. if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  3964. {
  3965. if( ctx->type.dataType.IsIntegerType() ||
  3966. ctx->type.dataType.IsUnsignedType() )
  3967. {
  3968. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3969. {
  3970. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3971. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3972. }
  3973. else
  3974. {
  3975. ConvertToTempVariable(ctx);
  3976. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3977. int offset = AllocateVariable(to, true);
  3978. if( ctx->type.dataType.IsUnsignedType() )
  3979. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3980. else
  3981. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3982. ctx->type.SetVariable(to, offset, true);
  3983. }
  3984. }
  3985. else if( ctx->type.dataType.IsFloatType() )
  3986. {
  3987. ConvertToTempVariable(ctx);
  3988. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3989. int offset = AllocateVariable(to, true);
  3990. ctx->bc.InstrW_W(asBC_fTOu64, offset, ctx->type.stackOffset);
  3991. ctx->type.SetVariable(to, offset, true);
  3992. }
  3993. else if( ctx->type.dataType.IsDoubleType() )
  3994. {
  3995. ConvertToTempVariable(ctx);
  3996. ctx->bc.InstrSHORT(asBC_dTOu64, ctx->type.stackOffset);
  3997. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3998. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3999. }
  4000. }
  4001. else if( to.IsFloatType() )
  4002. {
  4003. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4004. {
  4005. ConvertToTempVariable(ctx);
  4006. ctx->bc.InstrSHORT(asBC_iTOf, ctx->type.stackOffset);
  4007. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4008. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4009. }
  4010. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4011. {
  4012. ConvertToTempVariable(ctx);
  4013. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4014. int offset = AllocateVariable(to, true);
  4015. ctx->bc.InstrW_W(asBC_i64TOf, offset, ctx->type.stackOffset);
  4016. ctx->type.SetVariable(to, offset, true);
  4017. }
  4018. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4019. {
  4020. ConvertToTempVariable(ctx);
  4021. ctx->bc.InstrSHORT(asBC_uTOf, ctx->type.stackOffset);
  4022. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4023. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4024. }
  4025. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4026. {
  4027. ConvertToTempVariable(ctx);
  4028. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4029. int offset = AllocateVariable(to, true);
  4030. ctx->bc.InstrW_W(asBC_u64TOf, offset, ctx->type.stackOffset);
  4031. ctx->type.SetVariable(to, offset, true);
  4032. }
  4033. else if( ctx->type.dataType.IsDoubleType() )
  4034. {
  4035. ConvertToTempVariable(ctx);
  4036. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4037. int offset = AllocateVariable(to, true);
  4038. ctx->bc.InstrW_W(asBC_dTOf, offset, ctx->type.stackOffset);
  4039. ctx->type.SetVariable(to, offset, true);
  4040. }
  4041. }
  4042. else if( to.IsDoubleType() )
  4043. {
  4044. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4045. {
  4046. ConvertToTempVariable(ctx);
  4047. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4048. int offset = AllocateVariable(to, true);
  4049. ctx->bc.InstrW_W(asBC_iTOd, offset, ctx->type.stackOffset);
  4050. ctx->type.SetVariable(to, offset, true);
  4051. }
  4052. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4053. {
  4054. ConvertToTempVariable(ctx);
  4055. ctx->bc.InstrSHORT(asBC_i64TOd, ctx->type.stackOffset);
  4056. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4057. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4058. }
  4059. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4060. {
  4061. ConvertToTempVariable(ctx);
  4062. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4063. int offset = AllocateVariable(to, true);
  4064. ctx->bc.InstrW_W(asBC_uTOd, offset, ctx->type.stackOffset);
  4065. ctx->type.SetVariable(to, offset, true);
  4066. }
  4067. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4068. {
  4069. ConvertToTempVariable(ctx);
  4070. ctx->bc.InstrSHORT(asBC_u64TOd, ctx->type.stackOffset);
  4071. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4072. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4073. }
  4074. else if( ctx->type.dataType.IsFloatType() )
  4075. {
  4076. ConvertToTempVariable(ctx);
  4077. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4078. int offset = AllocateVariable(to, true);
  4079. ctx->bc.InstrW_W(asBC_fTOd, offset, ctx->type.stackOffset);
  4080. ctx->type.SetVariable(to, offset, true);
  4081. }
  4082. }
  4083. }
  4084. else
  4085. {
  4086. if( ((to.IsIntegerType() && !to.IsEnumType()) || to.IsUnsignedType() ||
  4087. to.IsFloatType() || to.IsDoubleType() ||
  4088. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST)) &&
  4089. (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() ||
  4090. ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType()) )
  4091. {
  4092. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4093. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4094. }
  4095. }
  4096. // Primitive types on the stack, can be const or non-const
  4097. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4098. return cost;
  4099. }
  4100. asUINT asCCompiler::ImplicitConversion(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, bool allowObjectConstruct)
  4101. {
  4102. asASSERT( ctx->type.dataType.GetTokenType() != ttUnrecognizedToken ||
  4103. ctx->type.dataType.IsNullHandle() );
  4104. // No conversion from void to any other type
  4105. if( ctx->type.dataType.GetTokenType() == ttVoid )
  4106. return asCC_NO_CONV;
  4107. // Do we want a var type?
  4108. if( to.GetTokenType() == ttQuestion )
  4109. {
  4110. // Any type can be converted to a var type, but only when not generating code
  4111. asASSERT( !generateCode );
  4112. ctx->type.dataType = to;
  4113. return asCC_VARIABLE_CONV;
  4114. }
  4115. // Do we want a primitive?
  4116. else if( to.IsPrimitive() )
  4117. {
  4118. if( !ctx->type.dataType.IsPrimitive() )
  4119. return ImplicitConvObjectToPrimitive(ctx, to, node, convType, generateCode);
  4120. else
  4121. return ImplicitConvPrimitiveToPrimitive(ctx, to, node, convType, generateCode);
  4122. }
  4123. else // The target is a complex type
  4124. {
  4125. if( ctx->type.dataType.IsPrimitive() )
  4126. return ImplicitConvPrimitiveToObject(ctx, to, node, convType, generateCode, allowObjectConstruct);
  4127. else if( ctx->type.IsNullConstant() || ctx->type.dataType.GetObjectType() )
  4128. return ImplicitConvObjectToObject(ctx, to, node, convType, generateCode, allowObjectConstruct);
  4129. }
  4130. return asCC_NO_CONV;
  4131. }
  4132. asUINT asCCompiler::ImplicitConvObjectToPrimitive(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  4133. {
  4134. if( ctx->type.isExplicitHandle )
  4135. {
  4136. // An explicit handle cannot be converted to a primitive
  4137. if( convType != asIC_IMPLICIT_CONV && node )
  4138. {
  4139. asCString str;
  4140. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  4141. Error(str, node);
  4142. }
  4143. return asCC_NO_CONV;
  4144. }
  4145. // TODO: Must use the const cast behaviour if the object is read-only
  4146. // Find matching value cast behaviours
  4147. // Here we're only interested in those that convert the type to a primitive type
  4148. asCArray<int> funcs;
  4149. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  4150. if( beh )
  4151. {
  4152. if( convType == asIC_EXPLICIT_VAL_CAST )
  4153. {
  4154. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  4155. {
  4156. // accept both implicit and explicit cast
  4157. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  4158. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  4159. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  4160. funcs.PushLast(beh->operators[n+1]);
  4161. }
  4162. }
  4163. else
  4164. {
  4165. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  4166. {
  4167. // accept only implicit cast
  4168. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  4169. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  4170. funcs.PushLast(beh->operators[n+1]);
  4171. }
  4172. }
  4173. }
  4174. // This matrix describes the priorities of the types to search for, for each target type
  4175. // The first column is the target type, the priorities goes from left to right
  4176. eTokenType matchMtx[10][10] =
  4177. {
  4178. {ttDouble, ttFloat, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  4179. {ttFloat, ttDouble, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  4180. {ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  4181. {ttUInt64, ttInt64, ttUInt, ttInt, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  4182. {ttInt, ttUInt, ttInt64, ttUInt64, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  4183. {ttUInt, ttInt, ttUInt64, ttInt64, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  4184. {ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttInt8, ttUInt8, ttDouble, ttFloat},
  4185. {ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttUInt8, ttInt8, ttDouble, ttFloat},
  4186. {ttInt8, ttUInt8, ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttDouble, ttFloat},
  4187. {ttUInt8, ttInt8, ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttDouble, ttFloat},
  4188. };
  4189. // Which row to use?
  4190. eTokenType *row = 0;
  4191. for( unsigned int type = 0; type < 10; type++ )
  4192. {
  4193. if( to.GetTokenType() == matchMtx[type][0] )
  4194. {
  4195. row = &matchMtx[type][0];
  4196. break;
  4197. }
  4198. }
  4199. // Find the best matching cast operator
  4200. int funcId = 0;
  4201. if( row )
  4202. {
  4203. asCDataType target(to);
  4204. // Priority goes from left to right in the matrix
  4205. for( unsigned int attempt = 0; attempt < 10 && funcId == 0; attempt++ )
  4206. {
  4207. target.SetTokenType(row[attempt]);
  4208. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  4209. {
  4210. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[n]);
  4211. if( descr->returnType.IsEqualExceptConst(target) )
  4212. {
  4213. funcId = funcs[n];
  4214. break;
  4215. }
  4216. }
  4217. }
  4218. }
  4219. // Did we find a suitable function?
  4220. if( funcId != 0 )
  4221. {
  4222. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  4223. if( generateCode )
  4224. {
  4225. asCTypeInfo objType = ctx->type;
  4226. Dereference(ctx, true);
  4227. PerformFunctionCall(funcId, ctx);
  4228. ReleaseTemporaryVariable(objType, &ctx->bc);
  4229. }
  4230. else
  4231. ctx->type.Set(descr->returnType);
  4232. // Allow one more implicit conversion to another primitive type
  4233. return asCC_OBJ_TO_PRIMITIVE_CONV + ImplicitConversion(ctx, to, node, convType, generateCode, false);
  4234. }
  4235. else
  4236. {
  4237. if( convType != asIC_IMPLICIT_CONV && node )
  4238. {
  4239. asCString str;
  4240. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  4241. Error(str, node);
  4242. }
  4243. }
  4244. return asCC_NO_CONV;
  4245. }
  4246. asUINT asCCompiler::ImplicitConvObjectRef(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  4247. {
  4248. // Convert null to any object type handle, but not to a non-handle type
  4249. if( ctx->type.IsNullConstant() && ctx->methodName == "" )
  4250. {
  4251. if( to.IsObjectHandle() )
  4252. {
  4253. ctx->type.dataType = to;
  4254. return asCC_REF_CONV;
  4255. }
  4256. return asCC_NO_CONV;
  4257. }
  4258. asASSERT(ctx->type.dataType.GetObjectType() || ctx->methodName != "");
  4259. // First attempt to convert the base type without instanciating another instance
  4260. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() && ctx->methodName == "" )
  4261. {
  4262. // If the to type is an interface and the from type implements it, then we can convert it immediately
  4263. if( ctx->type.dataType.GetObjectType()->Implements(to.GetObjectType()) )
  4264. {
  4265. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4266. return asCC_REF_CONV;
  4267. }
  4268. // If the to type is a class and the from type derives from it, then we can convert it immediately
  4269. else if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  4270. {
  4271. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4272. return asCC_REF_CONV;
  4273. }
  4274. // If the types are not equal yet, then we may still be able to find a reference cast
  4275. else if( ctx->type.dataType.GetObjectType() != to.GetObjectType() )
  4276. {
  4277. // A ref cast must not remove the constness
  4278. bool isConst = false;
  4279. if( (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) ||
  4280. (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) )
  4281. isConst = true;
  4282. // We may still be able to find an implicit ref cast behaviour
  4283. CompileRefCast(ctx, to, convType == asIC_EXPLICIT_REF_CAST, node, generateCode);
  4284. ctx->type.dataType.MakeHandleToConst(isConst);
  4285. // Was the conversion done?
  4286. if( ctx->type.dataType.GetObjectType() == to.GetObjectType() )
  4287. return asCC_REF_CONV;
  4288. }
  4289. }
  4290. // Convert matching function types
  4291. if( to.GetFuncDef() )
  4292. {
  4293. // If the input expression is already a funcdef, check if it can be converted
  4294. if( ctx->type.dataType.GetFuncDef() &&
  4295. to.GetFuncDef() != ctx->type.dataType.GetFuncDef() )
  4296. {
  4297. asCScriptFunction *toFunc = to.GetFuncDef();
  4298. asCScriptFunction *fromFunc = ctx->type.dataType.GetFuncDef();
  4299. if( toFunc->IsSignatureExceptNameEqual(fromFunc) )
  4300. {
  4301. ctx->type.dataType.SetFuncDef(toFunc);
  4302. return asCC_REF_CONV;
  4303. }
  4304. }
  4305. // If the input expression is a deferred function ref, check if there is a matching func
  4306. if( ctx->methodName != "" )
  4307. {
  4308. // Determine the namespace
  4309. asSNameSpace *ns = 0;
  4310. asCString name = "";
  4311. int pos = ctx->methodName.FindLast("::");
  4312. if( pos >= 0 )
  4313. {
  4314. asCString nsName = ctx->methodName.SubString(0, pos+2);
  4315. // Trim off the last ::
  4316. if( nsName.GetLength() > 2 )
  4317. nsName.SetLength(nsName.GetLength()-2);
  4318. ns = DetermineNameSpace(nsName);
  4319. name = ctx->methodName.SubString(pos+2);
  4320. }
  4321. else
  4322. {
  4323. DetermineNameSpace("");
  4324. name = ctx->methodName;
  4325. }
  4326. asCArray<int> funcs;
  4327. if( ns )
  4328. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  4329. // Check if any of the functions have perfect match
  4330. for( asUINT n = 0; n < funcs.GetLength(); n++ )
  4331. {
  4332. asCScriptFunction *func = builder->GetFunctionDescription(funcs[n]);
  4333. if( to.GetFuncDef()->IsSignatureExceptNameEqual(func) )
  4334. {
  4335. if( generateCode )
  4336. {
  4337. ctx->bc.InstrPTR(asBC_FuncPtr, func);
  4338. // Make sure the identified function is shared if we're compiling a shared function
  4339. if( !func->IsShared() && outFunc->IsShared() )
  4340. {
  4341. asCString msg;
  4342. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, func->GetDeclaration());
  4343. Error(msg, node);
  4344. }
  4345. }
  4346. ctx->type.dataType = asCDataType::CreateFuncDef(to.GetFuncDef());
  4347. return asCC_REF_CONV;
  4348. }
  4349. }
  4350. }
  4351. }
  4352. return asCC_NO_CONV;
  4353. }
  4354. asUINT asCCompiler::ImplicitConvObjectValue(asSExprContext *ctx, const asCDataType &to, asCScriptNode * /*node*/, EImplicitConv convType, bool generateCode)
  4355. {
  4356. asUINT cost = asCC_NO_CONV;
  4357. // If the base type is still different, and we are allowed to instance
  4358. // another object then we can try an implicit value cast
  4359. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  4360. {
  4361. // TODO: Implement support for implicit constructor/factory
  4362. asCArray<int> funcs;
  4363. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  4364. if( beh )
  4365. {
  4366. if( convType == asIC_EXPLICIT_VAL_CAST )
  4367. {
  4368. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  4369. {
  4370. // accept both implicit and explicit cast
  4371. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  4372. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  4373. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  4374. funcs.PushLast(beh->operators[n+1]);
  4375. }
  4376. }
  4377. else
  4378. {
  4379. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  4380. {
  4381. // accept only implicit cast
  4382. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  4383. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  4384. funcs.PushLast(beh->operators[n+1]);
  4385. }
  4386. }
  4387. }
  4388. // TODO: If there are multiple valid value casts, then we must choose the most appropriate one
  4389. asASSERT( funcs.GetLength() <= 1 );
  4390. if( funcs.GetLength() == 1 )
  4391. {
  4392. asCScriptFunction *f = builder->GetFunctionDescription(funcs[0]);
  4393. if( generateCode )
  4394. {
  4395. asCTypeInfo objType = ctx->type;
  4396. Dereference(ctx, true);
  4397. bool useVariable = false;
  4398. int stackOffset = 0;
  4399. if( f->DoesReturnOnStack() )
  4400. {
  4401. useVariable = true;
  4402. stackOffset = AllocateVariable(f->returnType, true);
  4403. // Push the pointer to the pre-allocated space for the return value
  4404. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  4405. // The object pointer is already on the stack, but should be the top
  4406. // one, so we need to swap the pointers in order to get the correct
  4407. ctx->bc.Instr(asBC_SwapPtr);
  4408. }
  4409. PerformFunctionCall(funcs[0], ctx, false, 0, 0, useVariable, stackOffset);
  4410. ReleaseTemporaryVariable(objType, &ctx->bc);
  4411. }
  4412. else
  4413. ctx->type.Set(f->returnType);
  4414. cost = asCC_TO_OBJECT_CONV;
  4415. }
  4416. }
  4417. return cost;
  4418. }
  4419. asUINT asCCompiler::ImplicitConvObjectToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, bool allowObjectConstruct)
  4420. {
  4421. // First try a ref cast
  4422. asUINT cost = ImplicitConvObjectRef(ctx, to, node, convType, generateCode);
  4423. // If the desired type is an asOBJ_ASHANDLE then we'll assume it is allowed to implicitly
  4424. // construct the object through any of the available constructors
  4425. if( to.GetObjectType() && (to.GetObjectType()->flags & asOBJ_ASHANDLE) && to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  4426. {
  4427. asCArray<int> funcs;
  4428. funcs = to.GetObjectType()->beh.constructors;
  4429. asCArray<asSExprContext *> args;
  4430. args.PushLast(ctx);
  4431. cost = asCC_TO_OBJECT_CONV + MatchFunctions(funcs, args, node, 0, 0, false, true, false);
  4432. // Did we find a matching constructor?
  4433. if( funcs.GetLength() == 1 )
  4434. {
  4435. if( generateCode )
  4436. {
  4437. // TODO: This should really reuse the code from CompileConstructCall
  4438. // Allocate the new object
  4439. asCTypeInfo tempObj;
  4440. tempObj.dataType = to;
  4441. tempObj.dataType.MakeReference(false);
  4442. tempObj.stackOffset = (short)AllocateVariable(tempObj.dataType, true);
  4443. tempObj.dataType.MakeReference(true);
  4444. tempObj.isTemporary = true;
  4445. tempObj.isVariable = true;
  4446. bool onHeap = IsVariableOnHeap(tempObj.stackOffset);
  4447. // Push the address of the object on the stack
  4448. asSExprContext e(engine);
  4449. if( onHeap )
  4450. e.bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  4451. PrepareFunctionCall(funcs[0], &e.bc, args);
  4452. MoveArgsToStack(funcs[0], &e.bc, args, false);
  4453. // If the object is allocated on the stack, then call the constructor as a normal function
  4454. if( onHeap )
  4455. {
  4456. int offset = 0;
  4457. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  4458. offset = descr->parameterTypes[0].GetSizeOnStackDWords();
  4459. e.bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  4460. }
  4461. else
  4462. e.bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  4463. PerformFunctionCall(funcs[0], &e, onHeap, &args, tempObj.dataType.GetObjectType());
  4464. // Add tag that the object has been initialized
  4465. e.bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  4466. // The constructor doesn't return anything,
  4467. // so we have to manually inform the type of
  4468. // the return value
  4469. e.type = tempObj;
  4470. if( !onHeap )
  4471. e.type.dataType.MakeReference(false);
  4472. // Push the address of the object on the stack again
  4473. e.bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  4474. MergeExprBytecodeAndType(ctx, &e);
  4475. }
  4476. else
  4477. {
  4478. ctx->type.Set(asCDataType::CreateObject(to.GetObjectType(), false));
  4479. }
  4480. }
  4481. }
  4482. // If the base type is still different, and we are allowed to instance
  4483. // another object then we can try an implicit value cast
  4484. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  4485. {
  4486. // Attempt implicit value cast
  4487. cost = ImplicitConvObjectValue(ctx, to, node, convType, generateCode);
  4488. }
  4489. // If we still haven't converted the base type to the correct type, then there is
  4490. // no need to continue as it is not possible to do the conversion
  4491. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  4492. return asCC_NO_CONV;
  4493. if( to.IsObjectHandle() )
  4494. {
  4495. // There is no extra cost in converting to a handle
  4496. // reference to handle -> handle
  4497. // reference -> handle
  4498. // object -> handle
  4499. // handle -> reference to handle
  4500. // reference -> reference to handle
  4501. // object -> reference to handle
  4502. // TODO: If the type is handle, then we can't use IsReadOnly to determine the constness of the basetype
  4503. // If the rvalue is a handle to a const object, then
  4504. // the lvalue must also be a handle to a const object
  4505. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() )
  4506. {
  4507. if( convType != asIC_IMPLICIT_CONV )
  4508. {
  4509. asASSERT(node);
  4510. asCString str;
  4511. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  4512. Error(str, node);
  4513. }
  4514. }
  4515. if( !ctx->type.dataType.IsObjectHandle() )
  4516. {
  4517. // An object type can be directly converted to a handle of the
  4518. // same type by doing a ref copy to a new variable
  4519. if( ctx->type.dataType.SupportHandles() )
  4520. {
  4521. asCDataType dt = ctx->type.dataType;
  4522. dt.MakeHandle(true);
  4523. dt.MakeReference(false);
  4524. if( generateCode )
  4525. {
  4526. // If the expression is already a local variable, then it is not
  4527. // necessary to do a ref copy, as the ref objects on the stack are
  4528. // really handles, only the handles cannot be modified.
  4529. if( ctx->type.isVariable )
  4530. {
  4531. bool isHandleToConst = ctx->type.dataType.IsReadOnly();
  4532. ctx->type.dataType.MakeReadOnly(false);
  4533. ctx->type.dataType.MakeHandle(true);
  4534. ctx->type.dataType.MakeReadOnly(true);
  4535. ctx->type.dataType.MakeHandleToConst(isHandleToConst);
  4536. if( to.IsReference() && !ctx->type.dataType.IsReference() )
  4537. {
  4538. ctx->bc.Instr(asBC_PopPtr);
  4539. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  4540. ctx->type.dataType.MakeReference(true);
  4541. }
  4542. else if( ctx->type.dataType.IsReference() )
  4543. {
  4544. ctx->bc.Instr(asBC_RDSPtr);
  4545. ctx->type.dataType.MakeReference(false);
  4546. }
  4547. }
  4548. else
  4549. {
  4550. int offset = AllocateVariable(dt, true);
  4551. if( ctx->type.dataType.IsReference() )
  4552. ctx->bc.Instr(asBC_RDSPtr);
  4553. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  4554. ctx->bc.InstrPTR(asBC_REFCPY, dt.GetObjectType());
  4555. ctx->bc.Instr(asBC_PopPtr);
  4556. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  4557. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4558. if( to.IsReference() )
  4559. dt.MakeReference(true);
  4560. else
  4561. ctx->bc.Instr(asBC_RDSPtr);
  4562. ctx->type.SetVariable(dt, offset, true);
  4563. }
  4564. }
  4565. else
  4566. ctx->type.dataType = dt;
  4567. // When this conversion is done the expression is no longer an lvalue
  4568. ctx->type.isLValue = false;
  4569. }
  4570. }
  4571. if( ctx->type.dataType.IsObjectHandle() )
  4572. {
  4573. // A handle to non-const can be converted to a
  4574. // handle to const, but not the other way
  4575. if( to.IsHandleToConst() )
  4576. ctx->type.dataType.MakeHandleToConst(true);
  4577. // A const handle can be converted to a non-const
  4578. // handle and vice versa as the handle is just a value
  4579. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4580. }
  4581. if( to.IsReference() && !ctx->type.dataType.IsReference() )
  4582. {
  4583. if( generateCode )
  4584. {
  4585. asASSERT( ctx->type.dataType.IsObjectHandle() );
  4586. // If the input type is a handle, then a simple ref copy is enough
  4587. bool isExplicitHandle = ctx->type.isExplicitHandle;
  4588. ctx->type.isExplicitHandle = ctx->type.dataType.IsObjectHandle();
  4589. // If the input type is read-only we'll need to temporarily
  4590. // remove this constness, otherwise the assignment will fail
  4591. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  4592. ctx->type.dataType.MakeReadOnly(false);
  4593. // If the object already is a temporary variable, then the copy
  4594. // doesn't have to be made as it is already a unique object
  4595. PrepareTemporaryObject(node, ctx);
  4596. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  4597. ctx->type.isExplicitHandle = isExplicitHandle;
  4598. }
  4599. // A non-reference can be converted to a reference,
  4600. // by putting the value in a temporary variable
  4601. ctx->type.dataType.MakeReference(true);
  4602. // Since it is a new temporary variable it doesn't have to be const
  4603. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4604. }
  4605. else if( !to.IsReference() && ctx->type.dataType.IsReference() )
  4606. {
  4607. Dereference(ctx, generateCode);
  4608. }
  4609. }
  4610. else // if( !to.IsObjectHandle() )
  4611. {
  4612. if( !to.IsReference() )
  4613. {
  4614. // reference to handle -> object
  4615. // handle -> object
  4616. // reference -> object
  4617. // An implicit handle can be converted to an object by adding a check for null pointer
  4618. if( ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  4619. {
  4620. if( generateCode )
  4621. {
  4622. if( ctx->type.dataType.IsReference() )
  4623. {
  4624. // The pointer on the stack refers to the handle
  4625. ctx->bc.Instr(asBC_ChkRefS);
  4626. }
  4627. else
  4628. {
  4629. // The pointer on the stack refers to the object
  4630. ctx->bc.Instr(asBC_CHKREF);
  4631. }
  4632. }
  4633. ctx->type.dataType.MakeHandle(false);
  4634. }
  4635. // A const object can be converted to a non-const object through a copy
  4636. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() &&
  4637. allowObjectConstruct )
  4638. {
  4639. // Does the object type allow a copy to be made?
  4640. if( ctx->type.dataType.CanBeCopied() )
  4641. {
  4642. if( generateCode )
  4643. {
  4644. // Make a temporary object with the copy
  4645. PrepareTemporaryObject(node, ctx);
  4646. }
  4647. // In case the object was already in a temporary variable, then the function
  4648. // didn't really do anything so we need to remove the constness here
  4649. ctx->type.dataType.MakeReadOnly(false);
  4650. // Add the cost for the copy
  4651. cost += asCC_TO_OBJECT_CONV;
  4652. }
  4653. }
  4654. if( ctx->type.dataType.IsReference() )
  4655. {
  4656. // This may look strange, but a value type allocated on the stack is already
  4657. // correct, so nothing should be done other than remove the mark as reference.
  4658. // For types allocated on the heap, it is necessary to dereference the pointer
  4659. // that is currently on the stack
  4660. if( IsVariableOnHeap(ctx->type.stackOffset) )
  4661. Dereference(ctx, generateCode);
  4662. else
  4663. ctx->type.dataType.MakeReference(false);
  4664. }
  4665. // A non-const object can be converted to a const object directly
  4666. if( !ctx->type.dataType.IsReadOnly() && to.IsReadOnly() )
  4667. {
  4668. ctx->type.dataType.MakeReadOnly(true);
  4669. }
  4670. }
  4671. else // if( to.IsReference() )
  4672. {
  4673. // reference to handle -> reference
  4674. // handle -> reference
  4675. // object -> reference
  4676. if( ctx->type.dataType.IsReference() )
  4677. {
  4678. if( ctx->type.isExplicitHandle && ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  4679. {
  4680. // ASHANDLE objects are really value types, so explicit handle can be removed
  4681. ctx->type.isExplicitHandle = false;
  4682. ctx->type.dataType.MakeHandle(false);
  4683. }
  4684. // A reference to a handle can be converted to a reference to an object
  4685. // by first reading the address, then verifying that it is not null
  4686. if( !to.IsObjectHandle() && ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  4687. {
  4688. ctx->type.dataType.MakeHandle(false);
  4689. if( generateCode )
  4690. ctx->bc.Instr(asBC_ChkRefS);
  4691. }
  4692. // A reference to a non-const can be converted to a reference to a const
  4693. if( to.IsReadOnly() )
  4694. ctx->type.dataType.MakeReadOnly(true);
  4695. else if( ctx->type.dataType.IsReadOnly() )
  4696. {
  4697. // A reference to a const can be converted to a reference to a
  4698. // non-const by copying the object to a temporary variable
  4699. ctx->type.dataType.MakeReadOnly(false);
  4700. if( generateCode )
  4701. {
  4702. // If the object already is a temporary variable, then the copy
  4703. // doesn't have to be made as it is already a unique object
  4704. PrepareTemporaryObject(node, ctx);
  4705. }
  4706. // Add the cost for the copy
  4707. cost += asCC_TO_OBJECT_CONV;
  4708. }
  4709. }
  4710. else // if( !ctx->type.dataType.IsReference() )
  4711. {
  4712. // A non-reference handle can be converted to a non-handle reference by checking against null handle
  4713. if( ctx->type.dataType.IsObjectHandle() )
  4714. {
  4715. bool readOnly = false;
  4716. if( ctx->type.dataType.IsHandleToConst() )
  4717. readOnly = true;
  4718. if( generateCode )
  4719. {
  4720. if( ctx->type.isVariable )
  4721. ctx->bc.InstrSHORT(asBC_ChkNullV, ctx->type.stackOffset);
  4722. else
  4723. ctx->bc.Instr(asBC_CHKREF);
  4724. }
  4725. ctx->type.dataType.MakeHandle(false);
  4726. ctx->type.dataType.MakeReference(true);
  4727. // Make sure a handle to const isn't converted to non-const reference
  4728. if( readOnly )
  4729. ctx->type.dataType.MakeReadOnly(true);
  4730. }
  4731. else
  4732. {
  4733. // A value type allocated on the stack is differentiated
  4734. // by it not being a reference. But it can be handled as
  4735. // reference by pushing the pointer on the stack
  4736. if( (ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) &&
  4737. (ctx->type.isVariable || ctx->type.isTemporary) &&
  4738. !IsVariableOnHeap(ctx->type.stackOffset) )
  4739. {
  4740. // Actually the pointer is already pushed on the stack in
  4741. // CompileVariableAccess, so we don't need to do anything else
  4742. }
  4743. else if( generateCode )
  4744. {
  4745. // A non-reference can be converted to a reference,
  4746. // by putting the value in a temporary variable
  4747. // If the input type is read-only we'll need to temporarily
  4748. // remove this constness, otherwise the assignment will fail
  4749. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  4750. ctx->type.dataType.MakeReadOnly(false);
  4751. // If the object already is a temporary variable, then the copy
  4752. // doesn't have to be made as it is already a unique object
  4753. PrepareTemporaryObject(node, ctx);
  4754. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  4755. // Add the cost for the copy
  4756. cost += asCC_TO_OBJECT_CONV;
  4757. }
  4758. // This may look strange as the conversion was to make the expression a reference
  4759. // but a value type allocated on the stack is a reference even without the type
  4760. // being marked as such.
  4761. ctx->type.dataType.MakeReference(IsVariableOnHeap(ctx->type.stackOffset));
  4762. }
  4763. // TODO: If the variable is an object allocated on the stack the following is not true as the copy may not have been made
  4764. // Since it is a new temporary variable it doesn't have to be const
  4765. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4766. }
  4767. }
  4768. }
  4769. return cost;
  4770. }
  4771. asUINT asCCompiler::ImplicitConvPrimitiveToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode * /*node*/, EImplicitConv /*isExplicit*/, bool generateCode, bool /*allowObjectConstruct*/)
  4772. {
  4773. // Reference types currently don't allow implicit conversion from primitive to object
  4774. // TODO: Allow implicit conversion to scoped reference types as they are supposed to appear like ordinary value types
  4775. asCObjectType *objType = to.GetObjectType();
  4776. asASSERT( objType );
  4777. if( !objType || (objType->flags & asOBJ_REF) )
  4778. return asCC_NO_CONV;
  4779. // For value types the object must have a constructor that takes a single primitive argument either by value or as input reference
  4780. asCArray<int> funcs;
  4781. for( asUINT n = 0; n < objType->beh.constructors.GetLength(); n++ )
  4782. {
  4783. asCScriptFunction *func = engine->scriptFunctions[objType->beh.constructors[n]];
  4784. if( func->parameterTypes.GetLength() == 1 &&
  4785. func->parameterTypes[0].IsPrimitive() &&
  4786. !(func->inOutFlags[0] & asTM_OUTREF) )
  4787. {
  4788. funcs.PushLast(func->id);
  4789. }
  4790. }
  4791. if( funcs.GetLength() == 0 )
  4792. return asCC_NO_CONV;
  4793. // Check if it is possible to choose a best match
  4794. asSExprContext arg(engine);
  4795. arg.type = ctx->type;
  4796. asCArray<asSExprContext*> args;
  4797. args.PushLast(&arg);
  4798. asUINT cost = asCC_TO_OBJECT_CONV + MatchFunctions(funcs, args, 0, 0, objType, false, true, false);
  4799. if( funcs.GetLength() != 1 )
  4800. return asCC_NO_CONV;
  4801. if( !generateCode )
  4802. {
  4803. ctx->type.Set(to);
  4804. return cost;
  4805. }
  4806. // TODO: clean up: This part is similar to CompileConstructCall(). It should be put in a common function
  4807. bool onHeap = true;
  4808. // Value types and script types are allocated through the constructor
  4809. asCTypeInfo tempObj;
  4810. tempObj.dataType = to;
  4811. tempObj.stackOffset = (short)AllocateVariable(to, true);
  4812. tempObj.dataType.MakeReference(true);
  4813. tempObj.isTemporary = true;
  4814. tempObj.isVariable = true;
  4815. onHeap = IsVariableOnHeap(tempObj.stackOffset);
  4816. // Push the address of the object on the stack
  4817. if( onHeap )
  4818. ctx->bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  4819. PrepareFunctionCall(funcs[0], &ctx->bc, args);
  4820. MoveArgsToStack(funcs[0], &ctx->bc, args, false);
  4821. if( !(objType->flags & asOBJ_REF) )
  4822. {
  4823. // If the object is allocated on the stack, then call the constructor as a normal function
  4824. if( onHeap )
  4825. {
  4826. int offset = 0;
  4827. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  4828. for( asUINT n = 0; n < args.GetLength(); n++ )
  4829. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  4830. ctx->bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  4831. }
  4832. else
  4833. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  4834. PerformFunctionCall(funcs[0], ctx, onHeap, &args, tempObj.dataType.GetObjectType());
  4835. // Add tag that the object has been initialized
  4836. ctx->bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  4837. // The constructor doesn't return anything,
  4838. // so we have to manually inform the type of
  4839. // the return value
  4840. ctx->type = tempObj;
  4841. if( !onHeap )
  4842. ctx->type.dataType.MakeReference(false);
  4843. // Push the address of the object on the stack again
  4844. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  4845. }
  4846. else
  4847. {
  4848. asASSERT( objType->flags & asOBJ_SCOPED );
  4849. // Call the factory to create the reference type
  4850. PerformFunctionCall(funcs[0], ctx, false, &args);
  4851. }
  4852. return cost;
  4853. }
  4854. void asCCompiler::ImplicitConversionConstant(asSExprContext *from, const asCDataType &to, asCScriptNode *node, EImplicitConv convType)
  4855. {
  4856. asASSERT(from->type.isConstant);
  4857. // TODO: node should be the node of the value that is
  4858. // converted (not the operator that provokes the implicit
  4859. // conversion)
  4860. // If the base type is correct there is no more to do
  4861. if( to.IsEqualExceptRefAndConst(from->type.dataType) ) return;
  4862. // References cannot be constants
  4863. if( from->type.dataType.IsReference() ) return;
  4864. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1 && !to.IsEnumType()) ||
  4865. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  4866. {
  4867. if( from->type.dataType.IsFloatType() ||
  4868. from->type.dataType.IsDoubleType() ||
  4869. from->type.dataType.IsUnsignedType() ||
  4870. from->type.dataType.IsIntegerType() )
  4871. {
  4872. // Transform the value
  4873. // Float constants can be implicitly converted to int
  4874. if( from->type.dataType.IsFloatType() )
  4875. {
  4876. float fc = from->type.floatValue;
  4877. int ic = int(fc);
  4878. if( float(ic) != fc )
  4879. {
  4880. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4881. }
  4882. from->type.intValue = ic;
  4883. }
  4884. // Double constants can be implicitly converted to int
  4885. else if( from->type.dataType.IsDoubleType() )
  4886. {
  4887. double fc = from->type.doubleValue;
  4888. int ic = int(fc);
  4889. if( double(ic) != fc )
  4890. {
  4891. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4892. }
  4893. from->type.intValue = ic;
  4894. }
  4895. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4896. {
  4897. // Verify that it is possible to convert to signed without getting negative
  4898. if( from->type.intValue < 0 )
  4899. {
  4900. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4901. }
  4902. // Convert to 32bit
  4903. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4904. from->type.intValue = from->type.byteValue;
  4905. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4906. from->type.intValue = from->type.wordValue;
  4907. }
  4908. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4909. {
  4910. // Convert to 32bit
  4911. from->type.intValue = int(from->type.qwordValue);
  4912. }
  4913. else if( from->type.dataType.IsIntegerType() &&
  4914. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4915. {
  4916. // Convert to 32bit
  4917. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4918. from->type.intValue = (signed char)from->type.byteValue;
  4919. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4920. from->type.intValue = (short)from->type.wordValue;
  4921. }
  4922. // Set the resulting type
  4923. if( to.IsEnumType() )
  4924. from->type.dataType = to;
  4925. else
  4926. from->type.dataType = asCDataType::CreatePrimitive(ttInt, true);
  4927. }
  4928. // Check if a downsize is necessary
  4929. if( to.IsIntegerType() &&
  4930. from->type.dataType.IsIntegerType() &&
  4931. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4932. {
  4933. // Verify if it is possible
  4934. if( to.GetSizeInMemoryBytes() == 1 )
  4935. {
  4936. if( char(from->type.intValue) != from->type.intValue )
  4937. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4938. from->type.byteValue = char(from->type.intValue);
  4939. }
  4940. else if( to.GetSizeInMemoryBytes() == 2 )
  4941. {
  4942. if( short(from->type.intValue) != from->type.intValue )
  4943. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4944. from->type.wordValue = short(from->type.intValue);
  4945. }
  4946. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4947. }
  4948. }
  4949. else if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  4950. {
  4951. // Float constants can be implicitly converted to int
  4952. if( from->type.dataType.IsFloatType() )
  4953. {
  4954. float fc = from->type.floatValue;
  4955. asINT64 ic = asINT64(fc);
  4956. if( float(ic) != fc )
  4957. {
  4958. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4959. }
  4960. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4961. from->type.qwordValue = ic;
  4962. }
  4963. // Double constants can be implicitly converted to int
  4964. else if( from->type.dataType.IsDoubleType() )
  4965. {
  4966. double fc = from->type.doubleValue;
  4967. asINT64 ic = asINT64(fc);
  4968. if( double(ic) != fc )
  4969. {
  4970. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4971. }
  4972. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4973. from->type.qwordValue = ic;
  4974. }
  4975. else if( from->type.dataType.IsUnsignedType() )
  4976. {
  4977. // Convert to 64bit
  4978. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4979. from->type.qwordValue = from->type.byteValue;
  4980. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4981. from->type.qwordValue = from->type.wordValue;
  4982. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4983. from->type.qwordValue = from->type.dwordValue;
  4984. else if( from->type.dataType.GetSizeInMemoryBytes() == 8 )
  4985. {
  4986. if( asINT64(from->type.qwordValue) < 0 )
  4987. {
  4988. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4989. }
  4990. }
  4991. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4992. }
  4993. else if( from->type.dataType.IsIntegerType() )
  4994. {
  4995. // Convert to 64bit
  4996. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4997. from->type.qwordValue = (signed char)from->type.byteValue;
  4998. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4999. from->type.qwordValue = (short)from->type.wordValue;
  5000. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  5001. from->type.qwordValue = from->type.intValue;
  5002. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  5003. }
  5004. }
  5005. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  5006. {
  5007. if( from->type.dataType.IsFloatType() )
  5008. {
  5009. float fc = from->type.floatValue;
  5010. // Some compilers set the value to 0 when converting a negative float to unsigned int.
  5011. // To maintain a consistent behaviour across compilers we convert to int first.
  5012. asUINT uic = asUINT(int(fc));
  5013. if( float(uic) != fc )
  5014. {
  5015. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5016. }
  5017. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  5018. from->type.intValue = uic;
  5019. // Try once more, in case of a smaller type
  5020. ImplicitConversionConstant(from, to, node, convType);
  5021. }
  5022. else if( from->type.dataType.IsDoubleType() )
  5023. {
  5024. double fc = from->type.doubleValue;
  5025. // Some compilers set the value to 0 when converting a negative double to unsigned int.
  5026. // To maintain a consistent behaviour across compilers we convert to int first.
  5027. asUINT uic = asUINT(int(fc));
  5028. if( double(uic) != fc )
  5029. {
  5030. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5031. }
  5032. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  5033. from->type.intValue = uic;
  5034. // Try once more, in case of a smaller type
  5035. ImplicitConversionConstant(from, to, node, convType);
  5036. }
  5037. else if( from->type.dataType.IsIntegerType() )
  5038. {
  5039. // Verify that it is possible to convert to unsigned without loosing negative
  5040. if( from->type.intValue < 0 )
  5041. {
  5042. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  5043. }
  5044. // Convert to 32bit
  5045. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5046. from->type.intValue = (signed char)from->type.byteValue;
  5047. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5048. from->type.intValue = (short)from->type.wordValue;
  5049. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  5050. // Try once more, in case of a smaller type
  5051. ImplicitConversionConstant(from, to, node, convType);
  5052. }
  5053. else if( from->type.dataType.IsUnsignedType() &&
  5054. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  5055. {
  5056. // Convert to 32bit
  5057. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5058. from->type.dwordValue = from->type.byteValue;
  5059. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5060. from->type.dwordValue = from->type.wordValue;
  5061. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  5062. // Try once more, in case of a smaller type
  5063. ImplicitConversionConstant(from, to, node, convType);
  5064. }
  5065. else if( from->type.dataType.IsUnsignedType() &&
  5066. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  5067. {
  5068. // Verify if it is possible
  5069. if( to.GetSizeInMemoryBytes() == 1 )
  5070. {
  5071. if( asBYTE(from->type.dwordValue) != from->type.dwordValue )
  5072. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  5073. from->type.byteValue = asBYTE(from->type.dwordValue);
  5074. }
  5075. else if( to.GetSizeInMemoryBytes() == 2 )
  5076. {
  5077. if( asWORD(from->type.dwordValue) != from->type.dwordValue )
  5078. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  5079. from->type.wordValue = asWORD(from->type.dwordValue);
  5080. }
  5081. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5082. }
  5083. }
  5084. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  5085. {
  5086. if( from->type.dataType.IsFloatType() )
  5087. {
  5088. float fc = from->type.floatValue;
  5089. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  5090. asQWORD uic = asQWORD(asINT64(fc));
  5091. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  5092. // MSVC6 doesn't support this conversion
  5093. if( float(uic) != fc )
  5094. {
  5095. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5096. }
  5097. #endif
  5098. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  5099. from->type.qwordValue = uic;
  5100. }
  5101. else if( from->type.dataType.IsDoubleType() )
  5102. {
  5103. double fc = from->type.doubleValue;
  5104. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  5105. asQWORD uic = asQWORD(asINT64(fc));
  5106. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  5107. // MSVC6 doesn't support this conversion
  5108. if( double(uic) != fc )
  5109. {
  5110. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5111. }
  5112. #endif
  5113. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  5114. from->type.qwordValue = uic;
  5115. }
  5116. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  5117. {
  5118. // Convert to 64bit
  5119. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5120. from->type.qwordValue = (asINT64)(signed char)from->type.byteValue;
  5121. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5122. from->type.qwordValue = (asINT64)(short)from->type.wordValue;
  5123. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  5124. from->type.qwordValue = (asINT64)from->type.intValue;
  5125. // Verify that it is possible to convert to unsigned without loosing negative
  5126. if( asINT64(from->type.qwordValue) < 0 )
  5127. {
  5128. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  5129. }
  5130. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  5131. }
  5132. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  5133. {
  5134. // Verify that it is possible to convert to unsigned without loosing negative
  5135. if( asINT64(from->type.qwordValue) < 0 )
  5136. {
  5137. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  5138. }
  5139. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  5140. }
  5141. else if( from->type.dataType.IsUnsignedType() )
  5142. {
  5143. // Convert to 64bit
  5144. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5145. from->type.qwordValue = from->type.byteValue;
  5146. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5147. from->type.qwordValue = from->type.wordValue;
  5148. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  5149. from->type.qwordValue = from->type.dwordValue;
  5150. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  5151. }
  5152. }
  5153. else if( to.IsFloatType() )
  5154. {
  5155. if( from->type.dataType.IsDoubleType() )
  5156. {
  5157. double ic = from->type.doubleValue;
  5158. float fc = float(ic);
  5159. // Don't bother warning about this
  5160. // if( double(fc) != ic )
  5161. // {
  5162. // asCString str;
  5163. // str.Format(TXT_POSSIBLE_LOSS_OF_PRECISION);
  5164. // if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(str, node);
  5165. // }
  5166. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5167. from->type.floatValue = fc;
  5168. }
  5169. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  5170. {
  5171. // Must properly convert value in case the from value is smaller
  5172. int ic;
  5173. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5174. ic = (signed char)from->type.byteValue;
  5175. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5176. ic = (short)from->type.wordValue;
  5177. else
  5178. ic = from->type.intValue;
  5179. float fc = float(ic);
  5180. if( int(fc) != ic )
  5181. {
  5182. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5183. }
  5184. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5185. from->type.floatValue = fc;
  5186. }
  5187. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  5188. {
  5189. float fc = float(asINT64(from->type.qwordValue));
  5190. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  5191. {
  5192. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5193. }
  5194. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5195. from->type.floatValue = fc;
  5196. }
  5197. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  5198. {
  5199. // Must properly convert value in case the from value is smaller
  5200. unsigned int uic;
  5201. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5202. uic = from->type.byteValue;
  5203. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5204. uic = from->type.wordValue;
  5205. else
  5206. uic = from->type.dwordValue;
  5207. float fc = float(uic);
  5208. if( (unsigned int)(fc) != uic )
  5209. {
  5210. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5211. }
  5212. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5213. from->type.floatValue = fc;
  5214. }
  5215. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  5216. {
  5217. float fc = float((asINT64)from->type.qwordValue);
  5218. if( asQWORD(fc) != from->type.qwordValue )
  5219. {
  5220. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5221. }
  5222. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5223. from->type.floatValue = fc;
  5224. }
  5225. }
  5226. else if( to.IsDoubleType() )
  5227. {
  5228. if( from->type.dataType.IsFloatType() )
  5229. {
  5230. float ic = from->type.floatValue;
  5231. double fc = double(ic);
  5232. // Don't check for float->double
  5233. // if( float(fc) != ic )
  5234. // {
  5235. // acCString str;
  5236. // str.Format(TXT_NOT_EXACT_g_g_g, ic, fc, float(fc));
  5237. // if( !isExplicit ) Warning(str, node);
  5238. // }
  5239. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5240. from->type.doubleValue = fc;
  5241. }
  5242. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  5243. {
  5244. // Must properly convert value in case the from value is smaller
  5245. int ic;
  5246. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5247. ic = (signed char)from->type.byteValue;
  5248. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5249. ic = (short)from->type.wordValue;
  5250. else
  5251. ic = from->type.intValue;
  5252. double fc = double(ic);
  5253. if( int(fc) != ic )
  5254. {
  5255. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5256. }
  5257. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5258. from->type.doubleValue = fc;
  5259. }
  5260. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  5261. {
  5262. double fc = double(asINT64(from->type.qwordValue));
  5263. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  5264. {
  5265. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5266. }
  5267. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5268. from->type.doubleValue = fc;
  5269. }
  5270. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  5271. {
  5272. // Must properly convert value in case the from value is smaller
  5273. unsigned int uic;
  5274. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5275. uic = from->type.byteValue;
  5276. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5277. uic = from->type.wordValue;
  5278. else
  5279. uic = from->type.dwordValue;
  5280. double fc = double(uic);
  5281. if( (unsigned int)(fc) != uic )
  5282. {
  5283. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5284. }
  5285. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5286. from->type.doubleValue = fc;
  5287. }
  5288. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  5289. {
  5290. double fc = double((asINT64)from->type.qwordValue);
  5291. if( asQWORD(fc) != from->type.qwordValue )
  5292. {
  5293. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5294. }
  5295. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5296. from->type.doubleValue = fc;
  5297. }
  5298. }
  5299. }
  5300. int asCCompiler::DoAssignment(asSExprContext *ctx, asSExprContext *lctx, asSExprContext *rctx, asCScriptNode *lexpr, asCScriptNode *rexpr, int op, asCScriptNode *opNode)
  5301. {
  5302. // Don't allow any operators on expressions that take address of class method
  5303. // If methodName is set but the type is not an object, then it is a global function
  5304. if( lctx->methodName != "" || (rctx->type.dataType.GetObjectType() && rctx->methodName != "") )
  5305. {
  5306. Error(TXT_INVALID_OP_ON_METHOD, opNode);
  5307. return -1;
  5308. }
  5309. // Implicit handle types should always be treated as handles in assignments
  5310. if (lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  5311. {
  5312. lctx->type.dataType.MakeHandle(true);
  5313. lctx->type.isExplicitHandle = true;
  5314. }
  5315. // Urho3D: if there is a handle type, and it does not have an overloaded assignment operator, convert to an explicit handle
  5316. // for scripting convenience. (For the Urho3D handle types, value assignment is not supported)
  5317. if (lctx->type.dataType.IsObjectHandle() && !lctx->type.dataType.IsTemplate() && !lctx->type.isExplicitHandle &&
  5318. !lctx->type.dataType.GetBehaviour()->copy)
  5319. lctx->type.isExplicitHandle = true;
  5320. // If the left hand expression is a property accessor, then that should be used
  5321. // to do the assignment instead of the ordinary operator. The exception is when
  5322. // the property accessor is for a handle property, and the operation is a value
  5323. // assignment.
  5324. if( (lctx->property_get || lctx->property_set) &&
  5325. !(lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle) )
  5326. {
  5327. if( op != ttAssignment )
  5328. {
  5329. // TODO: getset: We may actually be able to support this, if we can
  5330. // guarantee that the object reference will stay valid
  5331. // between the calls to the get and set accessors.
  5332. // Process the property to free the memory
  5333. ProcessPropertySetAccessor(lctx, rctx, opNode);
  5334. // Compound assignments are not allowed for properties
  5335. Error(TXT_COMPOUND_ASGN_WITH_PROP, opNode);
  5336. return -1;
  5337. }
  5338. // It is not allowed to do a handle assignment on a property
  5339. // accessor that doesn't take a handle in the set accessor.
  5340. if( lctx->property_set && lctx->type.isExplicitHandle )
  5341. {
  5342. // set_opIndex has 2 arguments, where as normal setters have only 1
  5343. asCArray<asCDataType>& parameterTypes =
  5344. builder->GetFunctionDescription(lctx->property_set)->parameterTypes;
  5345. if( !parameterTypes[parameterTypes.GetLength() - 1].IsObjectHandle() )
  5346. {
  5347. // Process the property to free the memory
  5348. ProcessPropertySetAccessor(lctx, rctx, opNode);
  5349. Error(TXT_HANDLE_ASSIGN_ON_NON_HANDLE_PROP, opNode);
  5350. return -1;
  5351. }
  5352. }
  5353. MergeExprBytecodeAndType(ctx, lctx);
  5354. return ProcessPropertySetAccessor(ctx, rctx, opNode);
  5355. }
  5356. else if( lctx->property_get && lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  5357. {
  5358. // Get the handle to the object that will be used for the value assignment
  5359. ProcessPropertyGetAccessor(lctx, opNode);
  5360. }
  5361. if( lctx->type.dataType.IsPrimitive() )
  5362. {
  5363. if( !lctx->type.isLValue )
  5364. {
  5365. Error(TXT_NOT_LVALUE, lexpr);
  5366. return -1;
  5367. }
  5368. if( op != ttAssignment )
  5369. {
  5370. // Compute the operator before the assignment
  5371. asCTypeInfo lvalue = lctx->type;
  5372. if( lctx->type.isTemporary && !lctx->type.isVariable )
  5373. {
  5374. // The temporary variable must not be freed until the
  5375. // assignment has been performed. lvalue still holds
  5376. // the information about the temporary variable
  5377. lctx->type.isTemporary = false;
  5378. }
  5379. asSExprContext o(engine);
  5380. CompileOperator(opNode, lctx, rctx, &o);
  5381. MergeExprBytecode(rctx, &o);
  5382. rctx->type = o.type;
  5383. // Convert the rvalue to the right type and validate it
  5384. PrepareForAssignment(&lvalue.dataType, rctx, rexpr, false);
  5385. MergeExprBytecode(ctx, rctx);
  5386. lctx->type = lvalue;
  5387. // The lvalue continues the same, either it was a variable, or a reference in the register
  5388. }
  5389. else
  5390. {
  5391. // Convert the rvalue to the right type and validate it
  5392. PrepareForAssignment(&lctx->type.dataType, rctx, rexpr, false, lctx);
  5393. MergeExprBytecode(ctx, rctx);
  5394. MergeExprBytecode(ctx, lctx);
  5395. }
  5396. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  5397. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  5398. ctx->type = lctx->type;
  5399. }
  5400. else if( lctx->type.isExplicitHandle )
  5401. {
  5402. if( !lctx->type.isLValue )
  5403. {
  5404. Error(TXT_NOT_LVALUE, lexpr);
  5405. return -1;
  5406. }
  5407. // Object handles don't have any compound assignment operators
  5408. if( op != ttAssignment )
  5409. {
  5410. asCString str;
  5411. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  5412. Error(str, lexpr);
  5413. return -1;
  5414. }
  5415. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  5416. {
  5417. // The object is a value type but that should be treated as a handle
  5418. // Make sure the right hand value is a handle
  5419. if( !rctx->type.isExplicitHandle &&
  5420. !(rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  5421. {
  5422. // Function names can be considered handles already
  5423. if( rctx->methodName == "" )
  5424. {
  5425. asCDataType dt = rctx->type.dataType;
  5426. dt.MakeHandle(true);
  5427. dt.MakeReference(false);
  5428. PrepareArgument(&dt, rctx, rexpr, true, asTM_INREF);
  5429. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  5430. {
  5431. asCString str;
  5432. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  5433. Error(str, rexpr);
  5434. return -1;
  5435. }
  5436. }
  5437. }
  5438. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  5439. {
  5440. // An overloaded assignment operator was found (or a compilation error occured)
  5441. return 0;
  5442. }
  5443. // The object must implement the opAssign method
  5444. Error(TXT_NO_APPROPRIATE_OPASSIGN, opNode);
  5445. return -1;
  5446. }
  5447. else
  5448. {
  5449. asCDataType dt = lctx->type.dataType;
  5450. dt.MakeReference(false);
  5451. PrepareArgument(&dt, rctx, rexpr, true, asTM_INREF , true);
  5452. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  5453. {
  5454. asCString str;
  5455. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  5456. Error(str, rexpr);
  5457. return -1;
  5458. }
  5459. MergeExprBytecode(ctx, rctx);
  5460. MergeExprBytecode(ctx, lctx);
  5461. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  5462. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  5463. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  5464. ctx->type = lctx->type;
  5465. }
  5466. }
  5467. else // if( lctx->type.dataType.IsObject() )
  5468. {
  5469. // An ASHANDLE type must not allow a value assignment, as
  5470. // the opAssign operator is used for the handle assignment
  5471. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  5472. {
  5473. asCString str;
  5474. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  5475. Error(str, lexpr);
  5476. return -1;
  5477. }
  5478. // The lvalue reference may be marked as a temporary, if for example
  5479. // it was originated as a handle returned from a function. In such
  5480. // cases it must be possible to assign values to it anyway.
  5481. if( lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  5482. {
  5483. // Convert the handle to a object reference
  5484. asCDataType to;
  5485. to = lctx->type.dataType;
  5486. to.MakeHandle(false);
  5487. ImplicitConversion(lctx, to, lexpr, asIC_IMPLICIT_CONV);
  5488. lctx->type.isLValue = true; // Handle may not have been an lvalue, but the dereferenced object is
  5489. }
  5490. // Check for overloaded assignment operator
  5491. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  5492. {
  5493. // An overloaded assignment operator was found (or a compilation error occured)
  5494. return 0;
  5495. }
  5496. // No registered operator was found. In case the operation is a direct
  5497. // assignment and the rvalue is the same type as the lvalue, then we can
  5498. // still use the byte-for-byte copy to do the assignment
  5499. if( op != ttAssignment )
  5500. {
  5501. asCString str;
  5502. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  5503. Error(str, lexpr);
  5504. return -1;
  5505. }
  5506. // If the left hand expression is simple, i.e. without any
  5507. // function calls or allocations of memory, then we can avoid
  5508. // doing a copy of the right hand expression (done by PrepareArgument).
  5509. // Instead the reference to the value can be placed directly on the
  5510. // stack.
  5511. //
  5512. // This optimization should only be done for value types, where
  5513. // the application developer is responsible for making the
  5514. // implementation safe against unwanted destruction of the input
  5515. // reference before the time.
  5516. bool simpleExpr = (lctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) && lctx->bc.IsSimpleExpression();
  5517. // Implicitly convert the rvalue to the type of the lvalue
  5518. bool needConversion = false;
  5519. if( !lctx->type.dataType.IsEqualExceptRefAndConst(rctx->type.dataType) )
  5520. needConversion = true;
  5521. if( !simpleExpr || needConversion )
  5522. {
  5523. asCDataType dt = lctx->type.dataType;
  5524. dt.MakeReference(true);
  5525. dt.MakeReadOnly(true);
  5526. PrepareArgument(&dt, rctx, rexpr, true, 1, !needConversion);
  5527. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  5528. {
  5529. asCString str;
  5530. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  5531. Error(str, rexpr);
  5532. return -1;
  5533. }
  5534. }
  5535. else
  5536. {
  5537. // Process any property accessor first, before placing the final reference on the stack
  5538. ProcessPropertyGetAccessor(rctx, rexpr);
  5539. if( rctx->type.dataType.IsReference() && (!(rctx->type.isVariable || rctx->type.isTemporary) || IsVariableOnHeap(rctx->type.stackOffset)) )
  5540. rctx->bc.Instr(asBC_RDSPtr);
  5541. }
  5542. MergeExprBytecode(ctx, rctx);
  5543. MergeExprBytecode(ctx, lctx);
  5544. if( !simpleExpr || needConversion )
  5545. {
  5546. if( (rctx->type.isVariable || rctx->type.isTemporary) )
  5547. {
  5548. if( !IsVariableOnHeap(rctx->type.stackOffset) )
  5549. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  5550. // as the value allocated on the stack is guaranteed to be safe.
  5551. // The bytecode optimizer should be able to determine this and optimize away the VAR + GETREF
  5552. ctx->bc.InstrWORD(asBC_GETREF, AS_PTR_SIZE);
  5553. else
  5554. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  5555. }
  5556. }
  5557. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  5558. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  5559. ctx->type = lctx->type;
  5560. }
  5561. return 0;
  5562. }
  5563. int asCCompiler::CompileAssignment(asCScriptNode *expr, asSExprContext *ctx)
  5564. {
  5565. asCScriptNode *lexpr = expr->firstChild;
  5566. if( lexpr->next )
  5567. {
  5568. // Compile the two expression terms
  5569. asSExprContext lctx(engine), rctx(engine);
  5570. int rr = CompileAssignment(lexpr->next->next, &rctx);
  5571. int lr = CompileCondition(lexpr, &lctx);
  5572. if( lr >= 0 && rr >= 0 )
  5573. return DoAssignment(ctx, &lctx, &rctx, lexpr, lexpr->next->next, lexpr->next->tokenType, lexpr->next);
  5574. // Since the operands failed, the assignment was not computed
  5575. ctx->type.SetDummy();
  5576. return -1;
  5577. }
  5578. return CompileCondition(lexpr, ctx);
  5579. }
  5580. int asCCompiler::CompileCondition(asCScriptNode *expr, asSExprContext *ctx)
  5581. {
  5582. asCTypeInfo ctype;
  5583. // Compile the conditional expression
  5584. asCScriptNode *cexpr = expr->firstChild;
  5585. if( cexpr->next )
  5586. {
  5587. //-------------------------------
  5588. // Compile the condition
  5589. asSExprContext e(engine);
  5590. int r = CompileExpression(cexpr, &e);
  5591. if( r < 0 )
  5592. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  5593. if( r >= 0 && !e.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  5594. {
  5595. Error(TXT_EXPR_MUST_BE_BOOL, cexpr);
  5596. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  5597. }
  5598. ctype = e.type;
  5599. ProcessPropertyGetAccessor(&e, cexpr);
  5600. if( e.type.dataType.IsReference() ) ConvertToVariable(&e);
  5601. ProcessDeferredParams(&e);
  5602. //-------------------------------
  5603. // Compile the left expression
  5604. asSExprContext le(engine);
  5605. int lr = CompileAssignment(cexpr->next, &le);
  5606. //-------------------------------
  5607. // Compile the right expression
  5608. asSExprContext re(engine);
  5609. int rr = CompileAssignment(cexpr->next->next, &re);
  5610. if( lr >= 0 && rr >= 0 )
  5611. {
  5612. // Don't allow any operators on expressions that take address of class method
  5613. if( le.methodName != "" || re.methodName != "" )
  5614. {
  5615. Error(TXT_INVALID_OP_ON_METHOD, expr);
  5616. return -1;
  5617. }
  5618. ProcessPropertyGetAccessor(&le, cexpr->next);
  5619. ProcessPropertyGetAccessor(&re, cexpr->next->next);
  5620. bool isExplicitHandle = le.type.isExplicitHandle || re.type.isExplicitHandle;
  5621. // Allow a 0 or null in the first case to be implicitly converted to the second type
  5622. if( le.type.isConstant && le.type.intValue == 0 && le.type.dataType.IsUnsignedType() )
  5623. {
  5624. asCDataType to = re.type.dataType;
  5625. to.MakeReference(false);
  5626. to.MakeReadOnly(true);
  5627. ImplicitConversionConstant(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  5628. }
  5629. else if( le.type.IsNullConstant() )
  5630. {
  5631. asCDataType to = re.type.dataType;
  5632. to.MakeHandle(true);
  5633. ImplicitConversion(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  5634. }
  5635. //---------------------------------
  5636. // Output the byte code
  5637. int afterLabel = nextLabel++;
  5638. int elseLabel = nextLabel++;
  5639. // If left expression is void, then we don't need to store the result
  5640. if( le.type.dataType.IsEqualExceptConst(asCDataType::CreatePrimitive(ttVoid, false)) )
  5641. {
  5642. // Put the code for the condition expression on the output
  5643. MergeExprBytecode(ctx, &e);
  5644. // Added the branch decision
  5645. ctx->type = e.type;
  5646. ConvertToVariable(ctx);
  5647. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  5648. ctx->bc.Instr(asBC_ClrHi);
  5649. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  5650. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  5651. // Add the left expression
  5652. MergeExprBytecode(ctx, &le);
  5653. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  5654. // Add the right expression
  5655. ctx->bc.Label((short)elseLabel);
  5656. MergeExprBytecode(ctx, &re);
  5657. ctx->bc.Label((short)afterLabel);
  5658. // Make sure both expressions have the same type
  5659. if( le.type.dataType != re.type.dataType )
  5660. Error(TXT_BOTH_MUST_BE_SAME, expr);
  5661. // Set the type of the result
  5662. ctx->type = le.type;
  5663. }
  5664. else
  5665. {
  5666. // Allocate temporary variable and copy the result to that one
  5667. asCTypeInfo temp;
  5668. temp = le.type;
  5669. temp.dataType.MakeReference(false);
  5670. temp.dataType.MakeReadOnly(false);
  5671. // Make sure the variable isn't used in the initial expression
  5672. int offset = AllocateVariableNotIn(temp.dataType, true, false, &e);
  5673. temp.SetVariable(temp.dataType, offset, true);
  5674. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  5675. CallDefaultConstructor(temp.dataType, offset, IsVariableOnHeap(offset), &ctx->bc, expr);
  5676. // Put the code for the condition expression on the output
  5677. MergeExprBytecode(ctx, &e);
  5678. // Add the branch decision
  5679. ctx->type = e.type;
  5680. ConvertToVariable(ctx);
  5681. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  5682. ctx->bc.Instr(asBC_ClrHi);
  5683. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  5684. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  5685. // Assign the result of the left expression to the temporary variable
  5686. asCTypeInfo rtemp;
  5687. rtemp = temp;
  5688. if( rtemp.dataType.IsObjectHandle() )
  5689. rtemp.isExplicitHandle = true;
  5690. PrepareForAssignment(&rtemp.dataType, &le, cexpr->next, true);
  5691. MergeExprBytecode(ctx, &le);
  5692. if( !rtemp.dataType.IsPrimitive() )
  5693. {
  5694. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5695. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  5696. }
  5697. PerformAssignment(&rtemp, &le.type, &ctx->bc, cexpr->next);
  5698. if( !rtemp.dataType.IsPrimitive() )
  5699. ctx->bc.Instr(asBC_PopPtr); // Pop the original value (always a pointer)
  5700. // Release the old temporary variable
  5701. ReleaseTemporaryVariable(le.type, &ctx->bc);
  5702. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  5703. // Start of the right expression
  5704. ctx->bc.Label((short)elseLabel);
  5705. // Copy the result to the same temporary variable
  5706. PrepareForAssignment(&rtemp.dataType, &re, cexpr->next, true);
  5707. MergeExprBytecode(ctx, &re);
  5708. if( !rtemp.dataType.IsPrimitive() )
  5709. {
  5710. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5711. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  5712. }
  5713. PerformAssignment(&rtemp, &re.type, &ctx->bc, cexpr->next);
  5714. if( !rtemp.dataType.IsPrimitive() )
  5715. ctx->bc.Instr(asBC_PopPtr); // Pop the original value (always a pointer)
  5716. // Release the old temporary variable
  5717. ReleaseTemporaryVariable(re.type, &ctx->bc);
  5718. ctx->bc.Label((short)afterLabel);
  5719. // Make sure both expressions have the same type
  5720. if( !le.type.dataType.IsEqualExceptConst(re.type.dataType) )
  5721. Error(TXT_BOTH_MUST_BE_SAME, expr);
  5722. // Set the temporary variable as output
  5723. ctx->type = rtemp;
  5724. ctx->type.isExplicitHandle = isExplicitHandle;
  5725. if( !ctx->type.dataType.IsPrimitive() )
  5726. {
  5727. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5728. ctx->type.dataType.MakeReference(IsVariableOnHeap(offset));
  5729. }
  5730. // Make sure the output isn't marked as being a literal constant
  5731. ctx->type.isConstant = false;
  5732. }
  5733. }
  5734. else
  5735. {
  5736. ctx->type.SetDummy();
  5737. return -1;
  5738. }
  5739. }
  5740. else
  5741. return CompileExpression(cexpr, ctx);
  5742. return 0;
  5743. }
  5744. int asCCompiler::CompileExpression(asCScriptNode *expr, asSExprContext *ctx)
  5745. {
  5746. asASSERT(expr->nodeType == snExpression);
  5747. // Convert to polish post fix, i.e: a+b => ab+
  5748. // The algorithm that I've implemented here is similar to
  5749. // Djikstra's Shunting Yard algorithm, though I didn't know it at the time.
  5750. // ref: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
  5751. // Count the nodes in order to preallocate the buffers
  5752. int count = 0;
  5753. asCScriptNode *node = expr->firstChild;
  5754. while( node )
  5755. {
  5756. count++;
  5757. node = node->next;
  5758. }
  5759. asCArray<asCScriptNode *> stack(count);
  5760. asCArray<asCScriptNode *> stack2(count);
  5761. node = expr->firstChild;
  5762. while( node )
  5763. {
  5764. int precedence = GetPrecedence(node);
  5765. while( stack.GetLength() > 0 &&
  5766. precedence <= GetPrecedence(stack[stack.GetLength()-1]) )
  5767. stack2.PushLast(stack.PopLast());
  5768. stack.PushLast(node);
  5769. node = node->next;
  5770. }
  5771. while( stack.GetLength() > 0 )
  5772. stack2.PushLast(stack.PopLast());
  5773. // Compile the postfix formatted expression
  5774. return CompilePostFixExpression(&stack2, ctx);
  5775. }
  5776. int asCCompiler::CompilePostFixExpression(asCArray<asCScriptNode *> *postfix, asSExprContext *ctx)
  5777. {
  5778. // Shouldn't send any byte code
  5779. asASSERT(ctx->bc.GetLastInstr() == -1);
  5780. // Set the context to a dummy type to avoid further
  5781. // errors in case the expression fails to compile
  5782. ctx->type.SetDummy();
  5783. // Evaluate the operands and operators
  5784. asCArray<asSExprContext*> free;
  5785. asCArray<asSExprContext*> expr;
  5786. int ret = 0;
  5787. for( asUINT n = 0; ret == 0 && n < postfix->GetLength(); n++ )
  5788. {
  5789. asCScriptNode *node = (*postfix)[n];
  5790. if( node->nodeType == snExprTerm )
  5791. {
  5792. asSExprContext *e = free.GetLength() ? free.PopLast() : asNEW(asSExprContext)(engine);
  5793. expr.PushLast(e);
  5794. e->exprNode = node;
  5795. ret = CompileExpressionTerm(node, e);
  5796. }
  5797. else
  5798. {
  5799. asSExprContext *r = expr.PopLast();
  5800. asSExprContext *l = expr.PopLast();
  5801. // Now compile the operator
  5802. asSExprContext *e = free.GetLength() ? free.PopLast() : asNEW(asSExprContext)(engine);
  5803. ret = CompileOperator(node, l, r, e);
  5804. expr.PushLast(e);
  5805. // Free the operands
  5806. l->Clear();
  5807. free.PushLast(l);
  5808. r->Clear();
  5809. free.PushLast(r);
  5810. }
  5811. }
  5812. if( ret == 0 )
  5813. {
  5814. asASSERT(expr.GetLength() == 1);
  5815. // The final result should be moved to the output context
  5816. MergeExprBytecodeAndType(ctx, expr[0]);
  5817. }
  5818. // Clean up
  5819. for( asUINT e = 0; e < expr.GetLength(); e++ )
  5820. asDELETE(expr[e], asSExprContext);
  5821. for( asUINT f = 0; f < free.GetLength(); f++ )
  5822. asDELETE(free[f], asSExprContext);
  5823. return ret;
  5824. }
  5825. int asCCompiler::CompileExpressionTerm(asCScriptNode *node, asSExprContext *ctx)
  5826. {
  5827. // Shouldn't send any byte code
  5828. asASSERT(ctx->bc.GetLastInstr() == -1);
  5829. // Set the type as a dummy by default, in case of any compiler errors
  5830. ctx->type.SetDummy();
  5831. // Compile the value node
  5832. asCScriptNode *vnode = node->firstChild;
  5833. while( vnode->nodeType != snExprValue )
  5834. vnode = vnode->next;
  5835. asSExprContext v(engine);
  5836. int r = CompileExpressionValue(vnode, &v); if( r < 0 ) return r;
  5837. // Compile post fix operators
  5838. asCScriptNode *pnode = vnode->next;
  5839. while( pnode )
  5840. {
  5841. r = CompileExpressionPostOp(pnode, &v); if( r < 0 ) return r;
  5842. pnode = pnode->next;
  5843. }
  5844. // Compile pre fix operators
  5845. pnode = vnode->prev;
  5846. while( pnode )
  5847. {
  5848. r = CompileExpressionPreOp(pnode, &v); if( r < 0 ) return r;
  5849. pnode = pnode->prev;
  5850. }
  5851. // Return the byte code and final type description
  5852. MergeExprBytecodeAndType(ctx, &v);
  5853. return 0;
  5854. }
  5855. int asCCompiler::CompileVariableAccess(const asCString &name, const asCString &scope, asSExprContext *ctx, asCScriptNode *errNode, bool isOptional, bool noFunction, bool noGlobal, asCObjectType *objType)
  5856. {
  5857. bool found = false;
  5858. // It is a local variable or parameter?
  5859. // This is not accessible by default arg expressions
  5860. sVariable *v = 0;
  5861. if( !isCompilingDefaultArg && scope == "" && !objType && variables )
  5862. v = variables->GetVariable(name.AddressOf());
  5863. if( v )
  5864. {
  5865. found = true;
  5866. if( v->isPureConstant )
  5867. ctx->type.SetConstantQW(v->type, v->constantValue);
  5868. else if( v->type.IsPrimitive() )
  5869. {
  5870. if( v->type.IsReference() )
  5871. {
  5872. // Copy the reference into the register
  5873. ctx->bc.InstrSHORT(asBC_PshVPtr, (short)v->stackOffset);
  5874. ctx->bc.Instr(asBC_PopRPtr);
  5875. ctx->type.Set(v->type);
  5876. }
  5877. else
  5878. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5879. ctx->type.isLValue = true;
  5880. }
  5881. else
  5882. {
  5883. ctx->bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  5884. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5885. // If the variable is allocated on the heap we have a reference,
  5886. // otherwise the actual object pointer is pushed on the stack.
  5887. if( v->onHeap || v->type.IsObjectHandle() ) ctx->type.dataType.MakeReference(true);
  5888. // Implicitly dereference handle parameters sent by reference
  5889. if( v->type.IsReference() && (!v->type.IsObject() || v->type.IsObjectHandle()) )
  5890. ctx->bc.Instr(asBC_RDSPtr);
  5891. ctx->type.isLValue = true;
  5892. }
  5893. }
  5894. // Is it a class member?
  5895. // This is not accessible by default arg expressions
  5896. if( !isCompilingDefaultArg && !found && ((objType) || (outFunc && outFunc->objectType && scope == "")) )
  5897. {
  5898. if( name == THIS_TOKEN && !objType )
  5899. {
  5900. asCDataType dt = asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly);
  5901. // The object pointer is located at stack position 0
  5902. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5903. ctx->type.SetVariable(dt, 0, false);
  5904. ctx->type.dataType.MakeReference(true);
  5905. ctx->type.isLValue = true;
  5906. found = true;
  5907. }
  5908. if( !found )
  5909. {
  5910. // See if there are any matching property accessors
  5911. asSExprContext access(engine);
  5912. if( objType )
  5913. access.type.Set(asCDataType::CreateObject(objType, false));
  5914. else
  5915. access.type.Set(asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly));
  5916. access.type.dataType.MakeReference(true);
  5917. int r = 0;
  5918. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5919. {
  5920. // This is an index access, check if there is a property accessor that takes an index arg
  5921. asSExprContext dummyArg(engine);
  5922. r = FindPropertyAccessor(name, &access, &dummyArg, errNode, 0, true);
  5923. }
  5924. if( r == 0 )
  5925. {
  5926. // Normal property access
  5927. r = FindPropertyAccessor(name, &access, errNode, 0, true);
  5928. }
  5929. if( r < 0 ) return -1;
  5930. if( access.property_get || access.property_set )
  5931. {
  5932. if( !objType )
  5933. {
  5934. // Prepare the bytecode for the member access
  5935. // This is only done when accessing through the implicit this pointer
  5936. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5937. }
  5938. MergeExprBytecodeAndType(ctx, &access);
  5939. found = true;
  5940. }
  5941. }
  5942. if( !found )
  5943. {
  5944. asCDataType dt;
  5945. if( objType )
  5946. dt = asCDataType::CreateObject(objType, false);
  5947. else
  5948. dt = asCDataType::CreateObject(outFunc->objectType, false);
  5949. asCObjectProperty *prop = builder->GetObjectProperty(dt, name.AddressOf());
  5950. if( prop )
  5951. {
  5952. if( !objType )
  5953. {
  5954. // The object pointer is located at stack position 0
  5955. // This is only done when accessing through the implicit this pointer
  5956. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5957. ctx->type.SetVariable(dt, 0, false);
  5958. ctx->type.dataType.MakeReference(true);
  5959. Dereference(ctx, true);
  5960. }
  5961. // TODO: This is the same as what is in CompileExpressionPostOp
  5962. // Put the offset on the stack
  5963. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(dt));
  5964. if( prop->type.IsReference() )
  5965. ctx->bc.Instr(asBC_RDSPtr);
  5966. // Reference to primitive must be stored in the temp register
  5967. if( prop->type.IsPrimitive() )
  5968. {
  5969. // TODO: runtime optimize: The ADD offset command should store the reference in the register directly
  5970. ctx->bc.Instr(asBC_PopRPtr);
  5971. }
  5972. // Set the new type (keeping info about temp variable)
  5973. ctx->type.dataType = prop->type;
  5974. ctx->type.dataType.MakeReference(true);
  5975. ctx->type.isVariable = false;
  5976. ctx->type.isLValue = true;
  5977. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  5978. {
  5979. // Objects that are members are not references
  5980. ctx->type.dataType.MakeReference(false);
  5981. }
  5982. // If the object reference is const, the property will also be const
  5983. ctx->type.dataType.MakeReadOnly(outFunc->isReadOnly);
  5984. found = true;
  5985. }
  5986. else if( outFunc->objectType )
  5987. {
  5988. // If it is not a property, it may still be the name of a method which can be used to create delegates
  5989. asCObjectType *ot = outFunc->objectType;
  5990. asCScriptFunction *func = 0;
  5991. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  5992. {
  5993. if( engine->scriptFunctions[ot->methods[n]]->name == name )
  5994. {
  5995. func = engine->scriptFunctions[ot->methods[n]];
  5996. break;
  5997. }
  5998. }
  5999. if( func )
  6000. {
  6001. // An object method was found. Keep the name of the method in the expression, but
  6002. // don't actually modify the bytecode at this point since it is not yet known what
  6003. // the method will be used for, or even what overloaded method should be used.
  6004. ctx->methodName = name;
  6005. // Place the object pointer on the stack, as if the expression was this.func
  6006. if( !objType )
  6007. {
  6008. // The object pointer is located at stack position 0
  6009. // This is only done when accessing through the implicit this pointer
  6010. ctx->bc.InstrSHORT(asBC_PSF, 0);
  6011. ctx->type.SetVariable(asCDataType::CreateObject(outFunc->objectType, false), 0, false);
  6012. ctx->type.dataType.MakeReference(true);
  6013. Dereference(ctx, true);
  6014. }
  6015. found = true;
  6016. }
  6017. }
  6018. }
  6019. }
  6020. // Recursively search parent namespaces for global entities
  6021. asCString currScope = scope;
  6022. if( scope == "" )
  6023. currScope = outFunc->nameSpace->name;
  6024. while( !found && !noGlobal && !objType )
  6025. {
  6026. asSNameSpace *ns = DetermineNameSpace(currScope);
  6027. // Is it a global property?
  6028. if( !found && ns )
  6029. {
  6030. // See if there are any matching global property accessors
  6031. asSExprContext access(engine);
  6032. int r = 0;
  6033. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  6034. {
  6035. // This is an index access, check if there is a property accessor that takes an index arg
  6036. asSExprContext dummyArg(engine);
  6037. r = FindPropertyAccessor(name, &access, &dummyArg, errNode, ns);
  6038. }
  6039. if( r == 0 )
  6040. {
  6041. // Normal property access
  6042. r = FindPropertyAccessor(name, &access, errNode, ns);
  6043. }
  6044. if( r < 0 ) return -1;
  6045. if( access.property_get || access.property_set )
  6046. {
  6047. // Prepare the bytecode for the function call
  6048. MergeExprBytecodeAndType(ctx, &access);
  6049. found = true;
  6050. }
  6051. // See if there is any matching global property
  6052. if( !found )
  6053. {
  6054. bool isCompiled = true;
  6055. bool isPureConstant = false;
  6056. bool isAppProp = false;
  6057. asQWORD constantValue = 0;
  6058. asCGlobalProperty *prop = builder->GetGlobalProperty(name.AddressOf(), ns, &isCompiled, &isPureConstant, &constantValue, &isAppProp);
  6059. if( prop )
  6060. {
  6061. found = true;
  6062. // Verify that the global property has been compiled already
  6063. if( isCompiled )
  6064. {
  6065. if( ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  6066. {
  6067. ctx->type.dataType.MakeHandle(true);
  6068. ctx->type.isExplicitHandle = true;
  6069. }
  6070. // If the global property is a pure constant
  6071. // we can allow the compiler to optimize it. Pure
  6072. // constants are global constant variables that were
  6073. // initialized by literal constants.
  6074. if( isPureConstant )
  6075. ctx->type.SetConstantQW(prop->type, constantValue);
  6076. else
  6077. {
  6078. // A shared type must not access global vars, unless they
  6079. // too are shared, e.g. application registered vars
  6080. if( outFunc->IsShared() )
  6081. {
  6082. if( !isAppProp )
  6083. {
  6084. asCString str;
  6085. str.Format(TXT_SHARED_CANNOT_ACCESS_NON_SHARED_VAR_s, prop->name.AddressOf());
  6086. Error(str, errNode);
  6087. // Allow the compilation to continue to catch other problems
  6088. }
  6089. }
  6090. ctx->type.Set(prop->type);
  6091. ctx->type.isLValue = true;
  6092. if( ctx->type.dataType.IsPrimitive() )
  6093. {
  6094. // Load the address of the variable into the register
  6095. ctx->bc.InstrPTR(asBC_LDG, prop->GetAddressOfValue());
  6096. ctx->type.dataType.MakeReference(true);
  6097. }
  6098. else
  6099. {
  6100. // Push the address of the variable on the stack
  6101. ctx->bc.InstrPTR(asBC_PGA, prop->GetAddressOfValue());
  6102. // If the object is a value type or a non-handle variable to a reference type,
  6103. // then we must validate the existance as it could potentially be accessed
  6104. // before it is initialized.
  6105. if( (ctx->type.dataType.GetObjectType()->flags & asOBJ_VALUE) ||
  6106. !ctx->type.dataType.IsObjectHandle() )
  6107. {
  6108. // TODO: runtime optimize: This is not necessary for application registered properties
  6109. ctx->bc.Instr(asBC_ChkRefS);
  6110. }
  6111. // If the address pushed on the stack is to a value type or an object
  6112. // handle, then mark the expression as a reference. Addresses to a reference
  6113. // type aren't marked as references to get correct behaviour
  6114. if( (ctx->type.dataType.GetObjectType()->flags & asOBJ_VALUE) ||
  6115. ctx->type.dataType.IsObjectHandle() )
  6116. {
  6117. ctx->type.dataType.MakeReference(true);
  6118. }
  6119. else
  6120. {
  6121. asASSERT( (ctx->type.dataType.GetObjectType()->flags & asOBJ_REF) && !ctx->type.dataType.IsObjectHandle() );
  6122. // It's necessary to dereference the pointer so the pointer on the stack will point to the actual object
  6123. ctx->bc.Instr(asBC_RDSPtr);
  6124. }
  6125. }
  6126. }
  6127. }
  6128. else
  6129. {
  6130. asCString str;
  6131. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, prop->name.AddressOf());
  6132. Error(str, errNode);
  6133. return -1;
  6134. }
  6135. }
  6136. }
  6137. }
  6138. // Is it the name of a global function?
  6139. if( !noFunction && !found && ns )
  6140. {
  6141. asCArray<int> funcs;
  6142. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  6143. if( funcs.GetLength() > 0 )
  6144. {
  6145. found = true;
  6146. // Defer the evaluation of which function until it is actually used
  6147. // Store the namespace and name of the function for later
  6148. ctx->type.SetNullConstant();
  6149. // Clear the explicit handle so that the script writer is allowed to explicitly set it
  6150. ctx->type.isExplicitHandle = false;
  6151. ctx->methodName = ns ? ns->name + "::" + name : name;
  6152. }
  6153. }
  6154. // Is it an enum value?
  6155. if( !found )
  6156. {
  6157. // The enum type may be declared in a namespace too
  6158. asCObjectType *scopeType = 0;
  6159. if( currScope != "" && currScope != "::" )
  6160. {
  6161. // Use the last scope name as the enum type
  6162. asCString enumType = currScope;
  6163. asCString nsScope;
  6164. int p = currScope.FindLast("::");
  6165. if( p != -1 )
  6166. {
  6167. enumType = currScope.SubString(p+2);
  6168. nsScope = currScope.SubString(0, p);
  6169. }
  6170. asSNameSpace *ns = engine->FindNameSpace(nsScope.AddressOf());
  6171. if( ns )
  6172. scopeType = builder->GetObjectType(enumType.AddressOf(), ns);
  6173. }
  6174. asDWORD value = 0;
  6175. asCDataType dt;
  6176. if( scopeType && builder->GetEnumValueFromObjectType(scopeType, name.AddressOf(), dt, value) )
  6177. {
  6178. // scoped enum value found
  6179. found = true;
  6180. }
  6181. else if( !engine->ep.requireEnumScope )
  6182. {
  6183. // Look for the enum value without explicitly informing the enum type
  6184. asSNameSpace *ns = DetermineNameSpace(currScope);
  6185. int e = 0;
  6186. if( ns )
  6187. e = builder->GetEnumValue(name.AddressOf(), dt, value, ns);
  6188. if( e )
  6189. {
  6190. found = true;
  6191. if( e == 2 )
  6192. {
  6193. Error(TXT_FOUND_MULTIPLE_ENUM_VALUES, errNode);
  6194. }
  6195. }
  6196. }
  6197. if( found )
  6198. {
  6199. // Even if the enum type is not shared, and we're compiling a shared object,
  6200. // the use of the values are still allowed, since they are treated as constants.
  6201. // an enum value was resolved
  6202. ctx->type.SetConstantDW(dt, value);
  6203. }
  6204. else
  6205. {
  6206. // If nothing was found because the scope doesn't match a namespace or an enum
  6207. // then this should be reported as an error and the search interrupted
  6208. if( !ns && !scopeType )
  6209. {
  6210. ctx->type.SetDummy();
  6211. asCString str;
  6212. str.Format(TXT_UNKNOWN_SCOPE_s, currScope.AddressOf());
  6213. Error(str, errNode);
  6214. return -1;
  6215. }
  6216. }
  6217. }
  6218. if( !found )
  6219. {
  6220. if( currScope == "" || currScope == "::" )
  6221. break;
  6222. // Move up to parent namespace
  6223. int pos = currScope.FindLast("::");
  6224. if( pos >= 0 )
  6225. currScope = currScope.SubString(0, pos);
  6226. else
  6227. currScope = "::";
  6228. }
  6229. }
  6230. // The name doesn't match any variable
  6231. if( !found )
  6232. {
  6233. // Give dummy value
  6234. ctx->type.SetDummy();
  6235. if( !isOptional )
  6236. {
  6237. // Prepend the scope to the name for the error message
  6238. asCString ename;
  6239. if( scope != "" && scope != "::" )
  6240. ename = scope + "::";
  6241. else
  6242. ename = scope;
  6243. ename += name;
  6244. asCString str;
  6245. str.Format(TXT_s_NOT_DECLARED, ename.AddressOf());
  6246. Error(str, errNode);
  6247. // Declare the variable now so that it will not be reported again
  6248. variables->DeclareVariable(name.AddressOf(), asCDataType::CreatePrimitive(ttInt, false), 0x7FFF, true);
  6249. // Mark the variable as initialized so that the user will not be bother by it again
  6250. sVariable *v = variables->GetVariable(name.AddressOf());
  6251. asASSERT(v);
  6252. if( v ) v->isInitialized = true;
  6253. }
  6254. // Return -1 to signal that the variable wasn't found
  6255. return -1;
  6256. }
  6257. return 0;
  6258. }
  6259. int asCCompiler::CompileExpressionValue(asCScriptNode *node, asSExprContext *ctx)
  6260. {
  6261. // Shouldn't receive any byte code
  6262. asASSERT(ctx->bc.GetLastInstr() == -1);
  6263. asCScriptNode *vnode = node->firstChild;
  6264. ctx->exprNode = vnode;
  6265. if( vnode->nodeType == snVariableAccess )
  6266. {
  6267. // Determine the scope resolution of the variable
  6268. asCString scope = builder->GetScopeFromNode(vnode->firstChild, script, &vnode);
  6269. // Determine the name of the variable
  6270. asASSERT(vnode->nodeType == snIdentifier );
  6271. asCString name(&script->code[vnode->tokenPos], vnode->tokenLength);
  6272. return CompileVariableAccess(name, scope, ctx, node);
  6273. }
  6274. else if( vnode->nodeType == snConstant )
  6275. {
  6276. if( vnode->tokenType == ttIntConstant )
  6277. {
  6278. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  6279. asQWORD val = asStringScanUInt64(value.AddressOf(), 10, 0);
  6280. // Do we need 64 bits?
  6281. if( val>>32 )
  6282. {
  6283. // Only if the value uses the last bit of a 64bit word do we consider the number unsigned
  6284. if( val>>63 )
  6285. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  6286. else
  6287. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttInt64, true), val);
  6288. }
  6289. else
  6290. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttInt, true), asDWORD(val));
  6291. }
  6292. else if( vnode->tokenType == ttBitsConstant )
  6293. {
  6294. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  6295. // Let the function determine the radix from the prefix 0x = 16, 0d = 10, 0o = 8, or 0b = 2
  6296. // TODO: Check for overflow
  6297. asQWORD val = asStringScanUInt64(value.AddressOf(), 0, 0);
  6298. // Do we need 64 bits?
  6299. if( val>>32 )
  6300. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  6301. else
  6302. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  6303. }
  6304. else if( vnode->tokenType == ttFloatConstant )
  6305. {
  6306. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  6307. // TODO: Check for overflow
  6308. size_t numScanned;
  6309. float v = float(asStringScanDouble(value.AddressOf(), &numScanned));
  6310. ctx->type.SetConstantF(asCDataType::CreatePrimitive(ttFloat, true), v);
  6311. #ifndef AS_USE_DOUBLE_AS_FLOAT
  6312. // Don't check this if we have double as float, because then the whole token would be scanned (i.e. no f suffix)
  6313. asASSERT(numScanned == vnode->tokenLength - 1);
  6314. #endif
  6315. }
  6316. else if( vnode->tokenType == ttDoubleConstant )
  6317. {
  6318. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  6319. // TODO: Check for overflow
  6320. size_t numScanned;
  6321. double v = asStringScanDouble(value.AddressOf(), &numScanned);
  6322. ctx->type.SetConstantD(asCDataType::CreatePrimitive(ttDouble, true), v);
  6323. asASSERT(numScanned == vnode->tokenLength);
  6324. }
  6325. else if( vnode->tokenType == ttTrue ||
  6326. vnode->tokenType == ttFalse )
  6327. {
  6328. #if AS_SIZEOF_BOOL == 1
  6329. ctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  6330. #else
  6331. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  6332. #endif
  6333. }
  6334. else if( vnode->tokenType == ttStringConstant ||
  6335. vnode->tokenType == ttMultilineStringConstant ||
  6336. vnode->tokenType == ttHeredocStringConstant )
  6337. {
  6338. asCString str;
  6339. asCScriptNode *snode = vnode->firstChild;
  6340. if( script->code[snode->tokenPos] == '\'' && engine->ep.useCharacterLiterals )
  6341. {
  6342. // Treat the single quoted string as a single character literal
  6343. str.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  6344. asDWORD val = 0;
  6345. if( str.GetLength() && (unsigned char)str[0] > 127 && engine->ep.scanner == 1 )
  6346. {
  6347. // This is the start of a UTF8 encoded character. We need to decode it
  6348. val = asStringDecodeUTF8(str.AddressOf(), 0);
  6349. if( val == (asDWORD)-1 )
  6350. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  6351. }
  6352. else
  6353. {
  6354. val = ProcessStringConstant(str, snode);
  6355. if( val == (asDWORD)-1 )
  6356. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  6357. }
  6358. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), val);
  6359. }
  6360. else
  6361. {
  6362. // Process the string constants
  6363. while( snode )
  6364. {
  6365. asCString cat;
  6366. if( snode->tokenType == ttStringConstant )
  6367. {
  6368. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  6369. ProcessStringConstant(cat, snode);
  6370. }
  6371. else if( snode->tokenType == ttMultilineStringConstant )
  6372. {
  6373. if( !engine->ep.allowMultilineStrings )
  6374. Error(TXT_MULTILINE_STRINGS_NOT_ALLOWED, snode);
  6375. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  6376. ProcessStringConstant(cat, snode);
  6377. }
  6378. else if( snode->tokenType == ttHeredocStringConstant )
  6379. {
  6380. cat.Assign(&script->code[snode->tokenPos+3], snode->tokenLength-6);
  6381. ProcessHeredocStringConstant(cat, snode);
  6382. }
  6383. str += cat;
  6384. snode = snode->next;
  6385. }
  6386. // Call the string factory function to create a string object
  6387. asCScriptFunction *descr = engine->stringFactory;
  6388. if( descr == 0 )
  6389. {
  6390. // Error
  6391. Error(TXT_STRINGS_NOT_RECOGNIZED, vnode);
  6392. // Give dummy value
  6393. ctx->type.SetDummy();
  6394. return -1;
  6395. }
  6396. else
  6397. {
  6398. // Register the constant string with the engine
  6399. int id = engine->AddConstantString(str.AddressOf(), str.GetLength());
  6400. ctx->bc.InstrWORD(asBC_STR, (asWORD)id);
  6401. bool useVariable = false;
  6402. int stackOffset = 0;
  6403. if( descr->DoesReturnOnStack() )
  6404. {
  6405. useVariable = true;
  6406. stackOffset = AllocateVariable(descr->returnType, true);
  6407. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  6408. }
  6409. PerformFunctionCall(descr->id, ctx, false, 0, 0, useVariable, stackOffset);
  6410. }
  6411. }
  6412. }
  6413. else if( vnode->tokenType == ttNull )
  6414. {
  6415. ctx->bc.Instr(asBC_PshNull);
  6416. ctx->type.SetNullConstant();
  6417. }
  6418. else
  6419. asASSERT(false);
  6420. }
  6421. else if( vnode->nodeType == snFunctionCall )
  6422. {
  6423. // Determine the scope resolution
  6424. asCString scope = builder->GetScopeFromNode(vnode->firstChild, script);
  6425. return CompileFunctionCall(vnode, ctx, 0, false, scope);
  6426. }
  6427. else if( vnode->nodeType == snConstructCall )
  6428. {
  6429. CompileConstructCall(vnode, ctx);
  6430. }
  6431. else if( vnode->nodeType == snAssignment )
  6432. {
  6433. asSExprContext e(engine);
  6434. int r = CompileAssignment(vnode, &e);
  6435. if( r < 0 )
  6436. {
  6437. ctx->type.SetDummy();
  6438. return r;
  6439. }
  6440. MergeExprBytecodeAndType(ctx, &e);
  6441. }
  6442. else if( vnode->nodeType == snCast )
  6443. {
  6444. // Implement the cast operator
  6445. CompileConversion(vnode, ctx);
  6446. }
  6447. else
  6448. asASSERT(false);
  6449. return 0;
  6450. }
  6451. asUINT asCCompiler::ProcessStringConstant(asCString &cstr, asCScriptNode *node, bool processEscapeSequences)
  6452. {
  6453. int charLiteral = -1;
  6454. // Process escape sequences
  6455. asCArray<char> str((int)cstr.GetLength());
  6456. for( asUINT n = 0; n < cstr.GetLength(); n++ )
  6457. {
  6458. #ifdef AS_DOUBLEBYTE_CHARSET
  6459. // Double-byte charset is only allowed for ASCII and not UTF16 encoded strings
  6460. if( (cstr[n] & 0x80) && engine->ep.scanner == 0 && engine->ep.stringEncoding != 1 )
  6461. {
  6462. // This is the lead character of a double byte character
  6463. // include the trail character without checking it's value.
  6464. str.PushLast(cstr[n]);
  6465. n++;
  6466. str.PushLast(cstr[n]);
  6467. continue;
  6468. }
  6469. #endif
  6470. asUINT val;
  6471. if( processEscapeSequences && cstr[n] == '\\' )
  6472. {
  6473. ++n;
  6474. if( n == cstr.GetLength() )
  6475. {
  6476. if( charLiteral == -1 ) charLiteral = 0;
  6477. return charLiteral;
  6478. }
  6479. // Hexadecimal escape sequences will allow the construction of
  6480. // invalid unicode sequences, but the string should also work as
  6481. // a bytearray so we must support this. The code for working with
  6482. // unicode text must be prepared to handle invalid unicode sequences
  6483. if( cstr[n] == 'x' || cstr[n] == 'X' )
  6484. {
  6485. ++n;
  6486. if( n == cstr.GetLength() ) break;
  6487. val = 0;
  6488. int c = engine->ep.stringEncoding == 1 ? 4 : 2;
  6489. for( ; c > 0 && n < cstr.GetLength(); c--, n++ )
  6490. {
  6491. if( cstr[n] >= '0' && cstr[n] <= '9' )
  6492. val = val*16 + cstr[n] - '0';
  6493. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  6494. val = val*16 + cstr[n] - 'a' + 10;
  6495. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  6496. val = val*16 + cstr[n] - 'A' + 10;
  6497. else
  6498. break;
  6499. }
  6500. // Rewind one, since the loop will increment it again
  6501. n--;
  6502. // Hexadecimal escape sequences produce exact value, even if it is not proper unicode chars
  6503. if( engine->ep.stringEncoding == 0 )
  6504. {
  6505. str.PushLast((asBYTE)val);
  6506. }
  6507. else
  6508. {
  6509. #ifndef AS_BIG_ENDIAN
  6510. str.PushLast((asBYTE)val);
  6511. str.PushLast((asBYTE)(val>>8));
  6512. #else
  6513. str.PushLast((asBYTE)(val>>8));
  6514. str.PushLast((asBYTE)val);
  6515. #endif
  6516. }
  6517. if( charLiteral == -1 ) charLiteral = val;
  6518. continue;
  6519. }
  6520. else if( cstr[n] == 'u' || cstr[n] == 'U' )
  6521. {
  6522. // \u expects 4 hex digits
  6523. // \U expects 8 hex digits
  6524. bool expect2 = cstr[n] == 'u';
  6525. int c = expect2 ? 4 : 8;
  6526. val = 0;
  6527. for( ; c > 0; c-- )
  6528. {
  6529. ++n;
  6530. if( n == cstr.GetLength() ) break;
  6531. if( cstr[n] >= '0' && cstr[n] <= '9' )
  6532. val = val*16 + cstr[n] - '0';
  6533. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  6534. val = val*16 + cstr[n] - 'a' + 10;
  6535. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  6536. val = val*16 + cstr[n] - 'A' + 10;
  6537. else
  6538. break;
  6539. }
  6540. if( c != 0 )
  6541. {
  6542. // Give warning about invalid code point
  6543. // TODO: Need code position for warning
  6544. asCString msg;
  6545. msg.Format(TXT_INVALID_UNICODE_FORMAT_EXPECTED_d, expect2 ? 4 : 8);
  6546. Warning(msg, node);
  6547. continue;
  6548. }
  6549. }
  6550. else
  6551. {
  6552. if( cstr[n] == '"' )
  6553. val = '"';
  6554. else if( cstr[n] == '\'' )
  6555. val = '\'';
  6556. else if( cstr[n] == 'n' )
  6557. val = '\n';
  6558. else if( cstr[n] == 'r' )
  6559. val = '\r';
  6560. else if( cstr[n] == 't' )
  6561. val = '\t';
  6562. else if( cstr[n] == '0' )
  6563. val = '\0';
  6564. else if( cstr[n] == '\\' )
  6565. val = '\\';
  6566. else
  6567. {
  6568. // Invalid escape sequence
  6569. Warning(TXT_INVALID_ESCAPE_SEQUENCE, node);
  6570. continue;
  6571. }
  6572. }
  6573. }
  6574. else
  6575. {
  6576. if( engine->ep.scanner == 1 && (cstr[n] & 0x80) )
  6577. {
  6578. unsigned int len;
  6579. val = asStringDecodeUTF8(&cstr[n], &len);
  6580. if( val == 0xFFFFFFFF )
  6581. {
  6582. // Incorrect UTF8 encoding. Use only the first byte
  6583. // TODO: Need code position for warning
  6584. Warning(TXT_INVALID_UNICODE_SEQUENCE_IN_SRC, node);
  6585. val = (unsigned char)cstr[n];
  6586. }
  6587. else
  6588. n += len-1;
  6589. }
  6590. else
  6591. val = (unsigned char)cstr[n];
  6592. }
  6593. // Add the character to the final string
  6594. char encodedValue[5];
  6595. int len;
  6596. if( engine->ep.scanner == 1 && engine->ep.stringEncoding == 0 )
  6597. {
  6598. // Convert to UTF8 encoded
  6599. len = asStringEncodeUTF8(val, encodedValue);
  6600. }
  6601. else if( engine->ep.stringEncoding == 1 )
  6602. {
  6603. // Convert to 16bit wide character string (even if the script is scanned as ASCII)
  6604. len = asStringEncodeUTF16(val, encodedValue);
  6605. }
  6606. else
  6607. {
  6608. // Do not convert ASCII characters
  6609. encodedValue[0] = (asBYTE)val;
  6610. len = 1;
  6611. }
  6612. if( len < 0 )
  6613. {
  6614. // Give warning about invalid code point
  6615. // TODO: Need code position for warning
  6616. Warning(TXT_INVALID_UNICODE_VALUE, node);
  6617. }
  6618. else
  6619. {
  6620. // Add the encoded value to the final string
  6621. str.Concatenate(encodedValue, len);
  6622. if( charLiteral == -1 ) charLiteral = val;
  6623. }
  6624. }
  6625. cstr.Assign(str.AddressOf(), str.GetLength());
  6626. return charLiteral;
  6627. }
  6628. void asCCompiler::ProcessHeredocStringConstant(asCString &str, asCScriptNode *node)
  6629. {
  6630. // Remove first line if it only contains whitespace
  6631. int start;
  6632. for( start = 0; start < (int)str.GetLength(); start++ )
  6633. {
  6634. if( str[start] == '\n' )
  6635. {
  6636. // Remove the linebreak as well
  6637. start++;
  6638. break;
  6639. }
  6640. if( str[start] != ' ' &&
  6641. str[start] != '\t' &&
  6642. str[start] != '\r' )
  6643. {
  6644. // Don't remove anything
  6645. start = 0;
  6646. break;
  6647. }
  6648. }
  6649. // Remove the line after the last line break if it only contains whitespaces
  6650. int end;
  6651. for( end = (int)str.GetLength() - 1; end >= 0; end-- )
  6652. {
  6653. if( str[end] == '\n' )
  6654. {
  6655. // Don't remove the last line break
  6656. end++;
  6657. break;
  6658. }
  6659. if( str[end] != ' ' &&
  6660. str[end] != '\t' &&
  6661. str[end] != '\r' )
  6662. {
  6663. // Don't remove anything
  6664. end = (int)str.GetLength();
  6665. break;
  6666. }
  6667. }
  6668. if( end < 0 ) end = 0;
  6669. asCString tmp;
  6670. if( end > start )
  6671. tmp.Assign(&str[start], end-start);
  6672. ProcessStringConstant(tmp, node, false);
  6673. str = tmp;
  6674. }
  6675. void asCCompiler::CompileConversion(asCScriptNode *node, asSExprContext *ctx)
  6676. {
  6677. asSExprContext expr(engine);
  6678. asCDataType to;
  6679. bool anyErrors = false;
  6680. EImplicitConv convType;
  6681. if( node->nodeType == snConstructCall )
  6682. {
  6683. convType = asIC_EXPLICIT_VAL_CAST;
  6684. // Verify that there is only one argument
  6685. if( node->lastChild->firstChild == 0 ||
  6686. node->lastChild->firstChild != node->lastChild->lastChild )
  6687. {
  6688. Error(TXT_ONLY_ONE_ARGUMENT_IN_CAST, node->lastChild);
  6689. expr.type.SetDummy();
  6690. anyErrors = true;
  6691. }
  6692. else
  6693. {
  6694. // Compile the expression
  6695. int r = CompileAssignment(node->lastChild->firstChild, &expr);
  6696. if( r < 0 )
  6697. anyErrors = true;
  6698. }
  6699. // Determine the requested type
  6700. to = builder->CreateDataTypeFromNode(node->firstChild, script, outFunc->nameSpace);
  6701. to.MakeReadOnly(true); // Default to const
  6702. asASSERT(to.IsPrimitive());
  6703. }
  6704. else
  6705. {
  6706. convType = asIC_EXPLICIT_REF_CAST;
  6707. // Compile the expression
  6708. int r = CompileAssignment(node->lastChild, &expr);
  6709. if( r < 0 )
  6710. anyErrors = true;
  6711. // Determine the requested type
  6712. to = builder->CreateDataTypeFromNode(node->firstChild, script, outFunc->nameSpace);
  6713. to = builder->ModifyDataTypeFromNode(to, node->firstChild->next, script, 0, 0);
  6714. // If the type support object handles, then use it
  6715. if( to.SupportHandles() )
  6716. {
  6717. to.MakeHandle(true);
  6718. }
  6719. else if( !to.IsObjectHandle() )
  6720. {
  6721. // The cast<type> operator can only be used for reference casts
  6722. Error(TXT_ILLEGAL_TARGET_TYPE_FOR_REF_CAST, node->firstChild);
  6723. anyErrors = true;
  6724. }
  6725. }
  6726. // Do not allow casting to non shared type if we're compiling a shared method
  6727. if( outFunc->IsShared() &&
  6728. to.GetObjectType() && !to.GetObjectType()->IsShared() )
  6729. {
  6730. asCString msg;
  6731. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, to.GetObjectType()->name.AddressOf());
  6732. Error(msg, node);
  6733. anyErrors = true;
  6734. }
  6735. if( anyErrors )
  6736. {
  6737. // Assume that the error can be fixed and allow the compilation to continue
  6738. ctx->type.SetConstantDW(to, 0);
  6739. return;
  6740. }
  6741. ProcessPropertyGetAccessor(&expr, node);
  6742. // Don't allow any operators on expressions that take address of class method
  6743. if( expr.methodName != "" )
  6744. {
  6745. Error(TXT_INVALID_OP_ON_METHOD, node);
  6746. return;
  6747. }
  6748. // We don't want a reference
  6749. if( expr.type.dataType.IsReference() )
  6750. {
  6751. if( expr.type.dataType.IsObject() )
  6752. Dereference(&expr, true);
  6753. else
  6754. ConvertToVariable(&expr);
  6755. }
  6756. ImplicitConversion(&expr, to, node, convType);
  6757. IsVariableInitialized(&expr.type, node);
  6758. // If no type conversion is really tried ignore it
  6759. if( to == expr.type.dataType )
  6760. {
  6761. // This will keep information about constant type
  6762. MergeExprBytecode(ctx, &expr);
  6763. ctx->type = expr.type;
  6764. return;
  6765. }
  6766. if( to.IsEqualExceptConst(expr.type.dataType) && to.IsPrimitive() )
  6767. {
  6768. MergeExprBytecode(ctx, &expr);
  6769. ctx->type = expr.type;
  6770. ctx->type.dataType.MakeReadOnly(true);
  6771. return;
  6772. }
  6773. // The implicit conversion already does most of the conversions permitted,
  6774. // here we'll only treat those conversions that require an explicit cast.
  6775. bool conversionOK = false;
  6776. if( !expr.type.isConstant )
  6777. {
  6778. if( !expr.type.dataType.IsObject() )
  6779. ConvertToTempVariable(&expr);
  6780. if( to.IsObjectHandle() &&
  6781. expr.type.dataType.IsObjectHandle() &&
  6782. !(!to.IsHandleToConst() && expr.type.dataType.IsHandleToConst()) )
  6783. {
  6784. conversionOK = CompileRefCast(&expr, to, true, node);
  6785. MergeExprBytecode(ctx, &expr);
  6786. ctx->type = expr.type;
  6787. }
  6788. }
  6789. if( conversionOK )
  6790. return;
  6791. // Conversion not available
  6792. ctx->type.SetDummy();
  6793. asCString strTo, strFrom;
  6794. strTo = to.Format();
  6795. strFrom = expr.type.dataType.Format();
  6796. asCString msg;
  6797. msg.Format(TXT_NO_CONVERSION_s_TO_s, strFrom.AddressOf(), strTo.AddressOf());
  6798. Error(msg, node);
  6799. }
  6800. void asCCompiler::AfterFunctionCall(int funcID, asCArray<asSExprContext*> &args, asSExprContext *ctx, bool deferAll)
  6801. {
  6802. asCScriptFunction *descr = builder->GetFunctionDescription(funcID);
  6803. // Parameters that are sent by reference should be assigned
  6804. // to the evaluated expression if it is an lvalue
  6805. // Evaluate the arguments from last to first
  6806. int n = (int)descr->parameterTypes.GetLength() - 1;
  6807. for( ; n >= 0; n-- )
  6808. {
  6809. if( (descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] & asTM_OUTREF)) ||
  6810. (descr->parameterTypes[n].IsObject() && deferAll) )
  6811. {
  6812. asASSERT( !(descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] == asTM_OUTREF)) || args[n]->origExpr );
  6813. // For &inout, only store the argument if it is for a temporary variable
  6814. if( engine->ep.allowUnsafeReferences ||
  6815. descr->inOutFlags[n] != asTM_INOUTREF || args[n]->type.isTemporary )
  6816. {
  6817. // Store the argument for later processing
  6818. asSDeferredParam outParam;
  6819. outParam.argNode = args[n]->exprNode;
  6820. outParam.argType = args[n]->type;
  6821. outParam.argInOutFlags = descr->inOutFlags[n];
  6822. outParam.origExpr = args[n]->origExpr;
  6823. ctx->deferredParams.PushLast(outParam);
  6824. }
  6825. }
  6826. else
  6827. {
  6828. // Release the temporary variable now
  6829. ReleaseTemporaryVariable(args[n]->type, &ctx->bc);
  6830. }
  6831. // Move the argument's deferred expressions over to the final expression
  6832. for( asUINT m = 0; m < args[n]->deferredParams.GetLength(); m++ )
  6833. {
  6834. ctx->deferredParams.PushLast(args[n]->deferredParams[m]);
  6835. args[n]->deferredParams[m].origExpr = 0;
  6836. }
  6837. args[n]->deferredParams.SetLength(0);
  6838. }
  6839. }
  6840. void asCCompiler::ProcessDeferredParams(asSExprContext *ctx)
  6841. {
  6842. if( isProcessingDeferredParams ) return;
  6843. isProcessingDeferredParams = true;
  6844. for( asUINT n = 0; n < ctx->deferredParams.GetLength(); n++ )
  6845. {
  6846. asSDeferredParam outParam = ctx->deferredParams[n];
  6847. if( outParam.argInOutFlags < asTM_OUTREF ) // &in, or not reference
  6848. {
  6849. // Just release the variable
  6850. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6851. }
  6852. else if( outParam.argInOutFlags == asTM_OUTREF )
  6853. {
  6854. asSExprContext *expr = outParam.origExpr;
  6855. outParam.origExpr = 0;
  6856. if( outParam.argType.dataType.IsObjectHandle() )
  6857. {
  6858. // Implicitly convert the value to a handle
  6859. if( expr->type.dataType.IsObjectHandle() )
  6860. expr->type.isExplicitHandle = true;
  6861. }
  6862. // Verify that the expression result in a lvalue, or a property accessor
  6863. if( IsLValue(expr->type) || expr->property_get || expr->property_set )
  6864. {
  6865. asSExprContext rctx(engine);
  6866. rctx.type = outParam.argType;
  6867. if( rctx.type.dataType.IsPrimitive() )
  6868. rctx.type.dataType.MakeReference(false);
  6869. else
  6870. {
  6871. rctx.bc.InstrSHORT(asBC_PSF, outParam.argType.stackOffset);
  6872. rctx.type.dataType.MakeReference(IsVariableOnHeap(outParam.argType.stackOffset));
  6873. if( expr->type.isExplicitHandle )
  6874. rctx.type.isExplicitHandle = true;
  6875. }
  6876. asSExprContext o(engine);
  6877. DoAssignment(&o, expr, &rctx, outParam.argNode, outParam.argNode, ttAssignment, outParam.argNode);
  6878. if( !o.type.dataType.IsPrimitive() ) o.bc.Instr(asBC_PopPtr);
  6879. // The assignment may itself have resulted in a new temporary variable, e.g. if
  6880. // the opAssign returns a non-reference. We must release this temporary variable
  6881. // since it won't be used
  6882. ReleaseTemporaryVariable(o.type, &o.bc);
  6883. MergeExprBytecode(ctx, &o);
  6884. }
  6885. else
  6886. {
  6887. // We must still evaluate the expression
  6888. MergeExprBytecode(ctx, expr);
  6889. if( !expr->type.isConstant || expr->type.IsNullConstant() )
  6890. ctx->bc.Instr(asBC_PopPtr);
  6891. // Give a warning, except if the argument is null or 0 which indicate the argument is really to be ignored
  6892. if( !expr->type.IsNullConstant() && !(expr->type.isConstant && expr->type.qwordValue == 0) )
  6893. Warning(TXT_ARG_NOT_LVALUE, outParam.argNode);
  6894. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6895. }
  6896. ReleaseTemporaryVariable(expr->type, &ctx->bc);
  6897. // Delete the original expression context
  6898. asDELETE(expr,asSExprContext);
  6899. }
  6900. else // &inout
  6901. {
  6902. if( outParam.argType.isTemporary )
  6903. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6904. else if( !outParam.argType.isVariable )
  6905. {
  6906. if( outParam.argType.dataType.IsObject() &&
  6907. ((outParam.argType.dataType.GetBehaviour()->addref &&
  6908. outParam.argType.dataType.GetBehaviour()->release) ||
  6909. (outParam.argType.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) )
  6910. {
  6911. // Release the object handle that was taken to guarantee the reference
  6912. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6913. }
  6914. }
  6915. }
  6916. }
  6917. ctx->deferredParams.SetLength(0);
  6918. isProcessingDeferredParams = false;
  6919. }
  6920. void asCCompiler::CompileConstructCall(asCScriptNode *node, asSExprContext *ctx)
  6921. {
  6922. // The first node is a datatype node
  6923. asCString name;
  6924. asCTypeInfo tempObj;
  6925. bool onHeap = true;
  6926. asCArray<int> funcs;
  6927. // It is possible that the name is really a constructor
  6928. asCDataType dt;
  6929. dt = builder->CreateDataTypeFromNode(node->firstChild, script, outFunc->nameSpace);
  6930. if( dt.IsPrimitive() )
  6931. {
  6932. // This is a cast to a primitive type
  6933. CompileConversion(node, ctx);
  6934. return;
  6935. }
  6936. // Do not allow constructing non-shared types in shared functions
  6937. if( outFunc->IsShared() &&
  6938. dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  6939. {
  6940. asCString msg;
  6941. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  6942. Error(msg, node);
  6943. }
  6944. // Compile the arguments
  6945. asCArray<asSExprContext *> args;
  6946. asCArray<asCTypeInfo> temporaryVariables;
  6947. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6948. {
  6949. // Check for a value cast behaviour
  6950. if( args.GetLength() == 1 && args[0]->type.dataType.GetObjectType() )
  6951. {
  6952. asSExprContext conv(engine);
  6953. conv.type = args[0]->type;
  6954. ImplicitConversion(&conv, dt, node->lastChild, asIC_EXPLICIT_VAL_CAST, false);
  6955. if( conv.type.dataType.IsEqualExceptRef(dt) )
  6956. {
  6957. ImplicitConversion(args[0], dt, node->lastChild, asIC_EXPLICIT_VAL_CAST);
  6958. ctx->bc.AddCode(&args[0]->bc);
  6959. ctx->type = args[0]->type;
  6960. asDELETE(args[0],asSExprContext);
  6961. return;
  6962. }
  6963. }
  6964. // Check for possible constructor/factory
  6965. name = dt.Format();
  6966. asSTypeBehaviour *beh = dt.GetBehaviour();
  6967. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6968. {
  6969. funcs = beh->constructors;
  6970. // Value types and script types are allocated through the constructor
  6971. tempObj.dataType = dt;
  6972. tempObj.stackOffset = (short)AllocateVariable(dt, true);
  6973. tempObj.dataType.MakeReference(true);
  6974. tempObj.isTemporary = true;
  6975. tempObj.isVariable = true;
  6976. onHeap = IsVariableOnHeap(tempObj.stackOffset);
  6977. // Push the address of the object on the stack
  6978. if( onHeap )
  6979. ctx->bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  6980. }
  6981. else
  6982. {
  6983. funcs = beh->factories;
  6984. }
  6985. // Special case: Allow calling func(void) with a void expression.
  6986. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6987. {
  6988. // Evaluate the expression before the function call
  6989. MergeExprBytecode(ctx, args[0]);
  6990. asDELETE(args[0],asSExprContext);
  6991. args.SetLength(0);
  6992. }
  6993. // Special case: If this is an object constructor and there are no arguments use the default constructor.
  6994. // If none has been registered, just allocate the variable and push it on the stack.
  6995. if( args.GetLength() == 0 )
  6996. {
  6997. asSTypeBehaviour *beh = tempObj.dataType.GetBehaviour();
  6998. if( beh && beh->construct == 0 && !(dt.GetObjectType()->flags & asOBJ_REF) )
  6999. {
  7000. // Call the default constructor
  7001. ctx->type = tempObj;
  7002. if( onHeap )
  7003. {
  7004. asASSERT(ctx->bc.GetLastInstr() == asBC_VAR);
  7005. ctx->bc.RemoveLastInstr();
  7006. }
  7007. CallDefaultConstructor(tempObj.dataType, tempObj.stackOffset, IsVariableOnHeap(tempObj.stackOffset), &ctx->bc, node);
  7008. // Push the reference on the stack
  7009. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  7010. return;
  7011. }
  7012. }
  7013. // Special case: If this is a construction of a delegate and the expression names an object method
  7014. if( dt.GetFuncDef() && args.GetLength() == 1 && args[0]->methodName != "" )
  7015. {
  7016. // TODO: delegate: It is possible that the argument returns a function pointer already, in which
  7017. // case no object delegate will be created, but instead a delegate for a function pointer
  7018. // In theory a simple cast would be good in this case, but this is a construct call so it
  7019. // is expected that a new object is created.
  7020. dt.MakeHandle(true);
  7021. ctx->type.Set(dt);
  7022. // The delegate must be able to hold on to a reference to the object
  7023. if( !args[0]->type.dataType.SupportHandles() )
  7024. Error(TXT_CANNOT_CREATE_DELEGATE_FOR_NOREF_TYPES, node);
  7025. else
  7026. {
  7027. // Filter the available object methods to find the one that matches the func def
  7028. asCObjectType *type = args[0]->type.dataType.GetObjectType();
  7029. asCScriptFunction *bestMethod = 0;
  7030. for( asUINT n = 0; n < type->methods.GetLength(); n++ )
  7031. {
  7032. asCScriptFunction *func = engine->scriptFunctions[type->methods[n]];
  7033. if( func->name != args[0]->methodName )
  7034. continue;
  7035. // If the expression is for a const object, then only const methods should be accepted
  7036. if( args[0]->type.dataType.IsReadOnly() && !func->IsReadOnly() )
  7037. continue;
  7038. if( func->IsSignatureExceptNameAndObjectTypeEqual(dt.GetFuncDef()) )
  7039. {
  7040. bestMethod = func;
  7041. // If the expression is non-const the non-const overloaded method has priority
  7042. if( args[0]->type.dataType.IsReadOnly() == func->IsReadOnly() )
  7043. break;
  7044. }
  7045. }
  7046. if( bestMethod )
  7047. {
  7048. // The object pointer is already on the stack
  7049. MergeExprBytecode(ctx, args[0]);
  7050. // Push the function pointer as an additional argument
  7051. ctx->bc.InstrPTR(asBC_FuncPtr, bestMethod);
  7052. // Call the factory function for the delegate
  7053. asCArray<int> funcs;
  7054. builder->GetFunctionDescriptions(DELEGATE_FACTORY, funcs, engine->nameSpaces[0]);
  7055. asASSERT( funcs.GetLength() == 1 );
  7056. ctx->bc.Call(asBC_CALLSYS , funcs[0], 2*AS_PTR_SIZE);
  7057. // Store the returned delegate in a temporary variable
  7058. int returnOffset = AllocateVariable(dt, true, false);
  7059. dt.MakeReference(true);
  7060. ctx->type.SetVariable(dt, returnOffset, true);
  7061. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  7062. // Push a reference to the temporary variable on the stack
  7063. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  7064. }
  7065. else
  7066. {
  7067. asCString msg;
  7068. msg.Format(TXT_NO_MATCHING_SIGNATURES_TO_s, dt.GetFuncDef()->GetDeclaration());
  7069. Error(msg.AddressOf(), node);
  7070. }
  7071. }
  7072. // Clean-up arg
  7073. asDELETE(args[0],asSExprContext);
  7074. return;
  7075. }
  7076. MatchFunctions(funcs, args, node, name.AddressOf(), NULL, false);
  7077. if( funcs.GetLength() != 1 )
  7078. {
  7079. // The error was reported by MatchFunctions()
  7080. // Dummy value
  7081. ctx->type.SetDummy();
  7082. }
  7083. else
  7084. {
  7085. int r = asSUCCESS;
  7086. // Add the default values for arguments not explicitly supplied
  7087. asCScriptFunction *func = (funcs[0] & FUNC_IMPORTED) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  7088. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  7089. r = CompileDefaultArgs(node, args, func);
  7090. if( r == asSUCCESS )
  7091. {
  7092. asCByteCode objBC(engine);
  7093. PrepareFunctionCall(funcs[0], &ctx->bc, args);
  7094. MoveArgsToStack(funcs[0], &ctx->bc, args, false);
  7095. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  7096. {
  7097. // If the object is allocated on the stack, then call the constructor as a normal function
  7098. if( onHeap )
  7099. {
  7100. int offset = 0;
  7101. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  7102. for( asUINT n = 0; n < args.GetLength(); n++ )
  7103. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  7104. ctx->bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  7105. }
  7106. else
  7107. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  7108. PerformFunctionCall(funcs[0], ctx, onHeap, &args, tempObj.dataType.GetObjectType());
  7109. // Add tag that the object has been initialized
  7110. ctx->bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  7111. // The constructor doesn't return anything,
  7112. // so we have to manually inform the type of
  7113. // the return value
  7114. ctx->type = tempObj;
  7115. if( !onHeap )
  7116. ctx->type.dataType.MakeReference(false);
  7117. // Push the address of the object on the stack again
  7118. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  7119. }
  7120. else
  7121. {
  7122. // Call the factory to create the reference type
  7123. PerformFunctionCall(funcs[0], ctx, false, &args);
  7124. }
  7125. }
  7126. }
  7127. }
  7128. else
  7129. {
  7130. // Failed to compile the argument list, set the result to the dummy type
  7131. ctx->type.SetDummy();
  7132. }
  7133. // Cleanup
  7134. for( asUINT n = 0; n < args.GetLength(); n++ )
  7135. if( args[n] )
  7136. {
  7137. asDELETE(args[n],asSExprContext);
  7138. }
  7139. }
  7140. int asCCompiler::CompileFunctionCall(asCScriptNode *node, asSExprContext *ctx, asCObjectType *objectType, bool objIsConst, const asCString &scope)
  7141. {
  7142. asCString name;
  7143. asCTypeInfo tempObj;
  7144. asCArray<int> funcs;
  7145. int localVar = -1;
  7146. bool initializeMembers = false;
  7147. asCScriptNode *nm = node->lastChild->prev;
  7148. name.Assign(&script->code[nm->tokenPos], nm->tokenLength);
  7149. // First check for a local variable of a function type as it would take precedence
  7150. // Must not allow function names, nor global variables to be returned in this instance
  7151. // If objectType is set then this is a post op expression and we shouldn't look for local variables
  7152. asSExprContext funcPtr(engine);
  7153. if( objectType == 0 )
  7154. {
  7155. localVar = CompileVariableAccess(name, scope, &funcPtr, node, true, true, true);
  7156. if( localVar >= 0 && !funcPtr.type.dataType.GetFuncDef() && funcPtr.methodName == "" )
  7157. {
  7158. // The variable is not a function
  7159. asCString msg;
  7160. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  7161. Error(msg, node);
  7162. return -1;
  7163. }
  7164. // If the name matches a method name, then reset the indicator that nothing was found
  7165. if( funcPtr.methodName != "" )
  7166. localVar = -1;
  7167. }
  7168. if( localVar < 0 )
  7169. {
  7170. // If this is an expression post op, or if a class method is
  7171. // being compiled, then we should look for matching class methods
  7172. if( objectType || (outFunc && outFunc->objectType && scope != "::") )
  7173. {
  7174. // If we're compiling a constructor and the name of the function is super then
  7175. // the constructor of the base class is being called.
  7176. // super cannot be prefixed with a scope operator
  7177. if( scope == "" && m_isConstructor && name == SUPER_TOKEN )
  7178. {
  7179. // If the class is not derived from anyone else, calling super should give an error
  7180. if( outFunc && outFunc->objectType->derivedFrom )
  7181. funcs = outFunc->objectType->derivedFrom->beh.constructors;
  7182. // Must not allow calling base class' constructor multiple times
  7183. if( continueLabels.GetLength() > 0 )
  7184. {
  7185. // If a continue label is set we are in a loop
  7186. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_LOOPS, node);
  7187. }
  7188. else if( breakLabels.GetLength() > 0 )
  7189. {
  7190. // TODO: inheritance: Should eventually allow constructors in switch statements
  7191. // If a break label is set we are either in a loop or a switch statements
  7192. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_SWITCH, node);
  7193. }
  7194. else if( m_isConstructorCalled )
  7195. {
  7196. Error(TXT_CANNOT_CALL_CONSTRUCTOR_TWICE, node);
  7197. }
  7198. m_isConstructorCalled = true;
  7199. // We need to initialize the class members, but only after all the deferred arguments have been completed
  7200. initializeMembers = true;
  7201. }
  7202. else
  7203. {
  7204. // The scope is can be used to specify the base class
  7205. builder->GetObjectMethodDescriptions(name.AddressOf(), objectType ? objectType : outFunc->objectType, funcs, objIsConst, scope);
  7206. }
  7207. // It is still possible that there is a class member of a function type
  7208. if( funcs.GetLength() == 0 )
  7209. {
  7210. int r = CompileVariableAccess(name, scope, &funcPtr, node, true, true, true, objectType);
  7211. if( r >= 0 && !funcPtr.type.dataType.GetFuncDef() && funcPtr.methodName == "" )
  7212. {
  7213. // The variable is not a function
  7214. asCString msg;
  7215. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  7216. Error(msg, node);
  7217. return -1;
  7218. }
  7219. }
  7220. // If a class method is being called implicitly, then add the this pointer for the call
  7221. if( funcs.GetLength() && !objectType )
  7222. {
  7223. objectType = outFunc->objectType;
  7224. asCDataType dt = asCDataType::CreateObject(objectType, false);
  7225. // The object pointer is located at stack position 0
  7226. ctx->bc.InstrSHORT(asBC_PSF, 0);
  7227. ctx->type.SetVariable(dt, 0, false);
  7228. ctx->type.dataType.MakeReference(true);
  7229. Dereference(ctx, true);
  7230. }
  7231. }
  7232. // If it is not a class method or member function pointer,
  7233. // then look for global functions or global function pointers,
  7234. // unless this is an expression post op, incase only member
  7235. // functions are expected
  7236. if( objectType == 0 && funcs.GetLength() == 0 && funcPtr.type.dataType.GetFuncDef() == 0 )
  7237. {
  7238. // The scope is used to define the namespace
  7239. asSNameSpace *ns = DetermineNameSpace(scope);
  7240. if( ns )
  7241. {
  7242. // Search recursively in parent namespaces
  7243. while( ns && funcs.GetLength() == 0 && funcPtr.type.dataType.GetFuncDef() == 0 )
  7244. {
  7245. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  7246. if( funcs.GetLength() == 0 )
  7247. {
  7248. int r = CompileVariableAccess(name, scope, &funcPtr, node, true, true);
  7249. if( r >= 0 && !funcPtr.type.dataType.GetFuncDef() )
  7250. {
  7251. // The variable is not a function
  7252. asCString msg;
  7253. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  7254. Error(msg, node);
  7255. return -1;
  7256. }
  7257. }
  7258. ns = builder->GetParentNameSpace(ns);
  7259. }
  7260. }
  7261. else
  7262. {
  7263. asCString msg;
  7264. msg.Format(TXT_NAMESPACE_s_DOESNT_EXIST, scope.AddressOf());
  7265. Error(msg, node);
  7266. return -1;
  7267. }
  7268. }
  7269. }
  7270. if( funcs.GetLength() == 0 && funcPtr.type.dataType.GetFuncDef() )
  7271. {
  7272. funcs.PushLast(funcPtr.type.dataType.GetFuncDef()->id);
  7273. }
  7274. // Compile the arguments
  7275. asCArray<asSExprContext *> args;
  7276. asCArray<asCTypeInfo> temporaryVariables;
  7277. if( CompileArgumentList(node->lastChild, args) >= 0 )
  7278. {
  7279. // Special case: Allow calling func(void) with a void expression.
  7280. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  7281. {
  7282. // Evaluate the expression before the function call
  7283. MergeExprBytecode(ctx, args[0]);
  7284. asDELETE(args[0],asSExprContext);
  7285. args.SetLength(0);
  7286. }
  7287. MatchFunctions(funcs, args, node, name.AddressOf(), objectType, objIsConst, false, true, scope);
  7288. if( funcs.GetLength() != 1 )
  7289. {
  7290. // The error was reported by MatchFunctions()
  7291. // Dummy value
  7292. ctx->type.SetDummy();
  7293. }
  7294. else
  7295. {
  7296. int r = asSUCCESS;
  7297. // Add the default values for arguments not explicitly supplied
  7298. asCScriptFunction *func = builder->GetFunctionDescription(funcs[0]);
  7299. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  7300. r = CompileDefaultArgs(node, args, func);
  7301. // TODO: funcdef: Do we have to make sure the handle is stored in a temporary variable, or
  7302. // is it enough to make sure it is in a local variable?
  7303. // For function pointer we must guarantee that the function is safe, i.e.
  7304. // by first storing the function pointer in a local variable (if it isn't already in one)
  7305. if( r == asSUCCESS )
  7306. {
  7307. if( func->funcType == asFUNC_FUNCDEF )
  7308. {
  7309. if( objectType && funcPtr.property_get <= 0 )
  7310. {
  7311. Dereference(ctx, true); // Dereference the object pointer to access the member
  7312. // The actual function should be called as if a global function
  7313. objectType = 0;
  7314. }
  7315. if( funcPtr.property_get > 0 )
  7316. {
  7317. ProcessPropertyGetAccessor(&funcPtr, node);
  7318. Dereference(&funcPtr, true);
  7319. // The function call will be made directly from the local variable so the function pointer shouldn't be on the stack
  7320. funcPtr.bc.Instr(asBC_PopPtr);
  7321. }
  7322. else
  7323. {
  7324. Dereference(&funcPtr, true);
  7325. ConvertToVariable(&funcPtr);
  7326. // The function call will be made directly from the local variable so the function pointer shouldn't be on the stack
  7327. if( !funcPtr.type.isTemporary )
  7328. funcPtr.bc.Instr(asBC_PopPtr);
  7329. }
  7330. MergeExprBytecodeAndType(ctx, &funcPtr);
  7331. }
  7332. MakeFunctionCall(ctx, funcs[0], objectType, args, node, false, 0, funcPtr.type.stackOffset);
  7333. // If the function pointer was copied to a local variable for the call, then
  7334. // release it again (temporary local variable)
  7335. if( (funcs[0] & FUNC_IMPORTED) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  7336. {
  7337. ReleaseTemporaryVariable(funcPtr.type, &ctx->bc);
  7338. }
  7339. }
  7340. }
  7341. }
  7342. else
  7343. {
  7344. // Failed to compile the argument list, set the dummy type and continue compilation
  7345. ctx->type.SetDummy();
  7346. }
  7347. // Cleanup
  7348. for( asUINT n = 0; n < args.GetLength(); n++ )
  7349. if( args[n] )
  7350. {
  7351. asDELETE(args[n],asSExprContext);
  7352. }
  7353. if( initializeMembers )
  7354. {
  7355. asASSERT( m_isConstructor );
  7356. // Need to initialize members here, as they may use the properties of the base class
  7357. // If there are multiple paths that call super(), then there will also be multiple
  7358. // locations with initializations of the members. It is not possible to consolidate
  7359. // these in one place, as the expressions for the initialization are evaluated where
  7360. // they are compiled, which means that they may access different variables depending
  7361. // on the scope where super() is called.
  7362. // Members that don't have an explicit initialization expression will be initialized
  7363. // beginning of the constructor as they are guaranteed not to use at the any
  7364. // members of the base class.
  7365. CompileMemberInitialization(&ctx->bc, false);
  7366. }
  7367. return 0;
  7368. }
  7369. asSNameSpace *asCCompiler::DetermineNameSpace(const asCString &scope)
  7370. {
  7371. asSNameSpace *ns;
  7372. if( scope == "" )
  7373. {
  7374. if( outFunc->nameSpace->name != "" )
  7375. ns = outFunc->nameSpace;
  7376. else if( outFunc->objectType && outFunc->objectType->nameSpace->name != "" )
  7377. ns = outFunc->objectType->nameSpace;
  7378. else
  7379. ns = engine->nameSpaces[0];
  7380. }
  7381. else if( scope == "::" )
  7382. ns = engine->nameSpaces[0];
  7383. else
  7384. ns = engine->FindNameSpace(scope.AddressOf());
  7385. return ns;
  7386. }
  7387. int asCCompiler::CompileExpressionPreOp(asCScriptNode *node, asSExprContext *ctx)
  7388. {
  7389. int op = node->tokenType;
  7390. // Don't allow any prefix operators except handle on expressions that take address of class method
  7391. if( ctx->methodName != "" && op != ttHandle )
  7392. {
  7393. Error(TXT_INVALID_OP_ON_METHOD, node);
  7394. return -1;
  7395. }
  7396. IsVariableInitialized(&ctx->type, node);
  7397. if( op == ttHandle )
  7398. {
  7399. if( ctx->methodName != "" )
  7400. {
  7401. // Don't allow taking the handle of a handle
  7402. if( ctx->type.isExplicitHandle )
  7403. {
  7404. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  7405. return -1;
  7406. }
  7407. }
  7408. else
  7409. {
  7410. // Verify that the type allow its handle to be taken
  7411. if( ctx->type.isExplicitHandle ||
  7412. !ctx->type.dataType.IsObject() ||
  7413. !(((ctx->type.dataType.GetObjectType()->beh.addref && ctx->type.dataType.GetObjectType()->beh.release) || (ctx->type.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) ||
  7414. (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  7415. {
  7416. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  7417. return -1;
  7418. }
  7419. // Objects that are not local variables are not references
  7420. // Objects allocated on the stack are also not marked as references
  7421. if( !ctx->type.dataType.IsReference() &&
  7422. !(ctx->type.dataType.IsObject() && !ctx->type.isVariable) &&
  7423. !(ctx->type.isVariable && !IsVariableOnHeap(ctx->type.stackOffset)) )
  7424. {
  7425. Error(TXT_NOT_VALID_REFERENCE, node);
  7426. return -1;
  7427. }
  7428. // Convert the expression to a handle
  7429. if( !ctx->type.dataType.IsObjectHandle() && !(ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  7430. {
  7431. asCDataType to = ctx->type.dataType;
  7432. to.MakeHandle(true);
  7433. to.MakeReference(true);
  7434. to.MakeHandleToConst(ctx->type.dataType.IsReadOnly());
  7435. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV, true, false);
  7436. asASSERT( ctx->type.dataType.IsObjectHandle() );
  7437. }
  7438. else if( ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  7439. {
  7440. // For the ASHANDLE type we'll simply set the expression as a handle
  7441. ctx->type.dataType.MakeHandle(true);
  7442. }
  7443. }
  7444. // Mark the expression as an explicit handle to avoid implicit conversions to non-handle expressions
  7445. ctx->type.isExplicitHandle = true;
  7446. }
  7447. else if( (op == ttMinus || op == ttPlus || op == ttBitNot || op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  7448. {
  7449. // Look for the appropriate method
  7450. // There is no overloadable operator for unary plus
  7451. const char *opName = 0;
  7452. switch( op )
  7453. {
  7454. case ttMinus: opName = "opNeg"; break;
  7455. case ttBitNot: opName = "opCom"; break;
  7456. case ttInc: opName = "opPreInc"; break;
  7457. case ttDec: opName = "opPreDec"; break;
  7458. }
  7459. if( opName )
  7460. {
  7461. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  7462. ProcessPropertyGetAccessor(ctx, node);
  7463. // Is it a const value?
  7464. bool isConst = false;
  7465. if( ctx->type.dataType.IsObjectHandle() )
  7466. isConst = ctx->type.dataType.IsHandleToConst();
  7467. else
  7468. isConst = ctx->type.dataType.IsReadOnly();
  7469. // 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
  7470. // Find the correct method
  7471. asCArray<int> funcs;
  7472. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  7473. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7474. {
  7475. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  7476. if( func->name == opName &&
  7477. func->parameterTypes.GetLength() == 0 &&
  7478. (!isConst || func->isReadOnly) )
  7479. {
  7480. funcs.PushLast(func->id);
  7481. }
  7482. }
  7483. // Did we find the method?
  7484. if( funcs.GetLength() == 1 )
  7485. {
  7486. asCTypeInfo objType = ctx->type;
  7487. asCArray<asSExprContext *> args;
  7488. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  7489. ReleaseTemporaryVariable(objType, &ctx->bc);
  7490. return 0;
  7491. }
  7492. else if( funcs.GetLength() == 0 )
  7493. {
  7494. asCString str;
  7495. str = asCString(opName) + "()";
  7496. if( isConst )
  7497. str += " const";
  7498. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  7499. Error(str, node);
  7500. ctx->type.SetDummy();
  7501. return -1;
  7502. }
  7503. else if( funcs.GetLength() > 1 )
  7504. {
  7505. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  7506. PrintMatchingFuncs(funcs, node);
  7507. ctx->type.SetDummy();
  7508. return -1;
  7509. }
  7510. }
  7511. else if( op == ttPlus )
  7512. {
  7513. Error(TXT_ILLEGAL_OPERATION, node);
  7514. ctx->type.SetDummy();
  7515. return -1;
  7516. }
  7517. }
  7518. else if( op == ttPlus || op == ttMinus )
  7519. {
  7520. // This is only for primitives. Objects are treated in the above block
  7521. // Make sure the type is a math type
  7522. if( !(ctx->type.dataType.IsIntegerType() ||
  7523. ctx->type.dataType.IsUnsignedType() ||
  7524. ctx->type.dataType.IsFloatType() ||
  7525. ctx->type.dataType.IsDoubleType() ) )
  7526. {
  7527. Error(TXT_ILLEGAL_OPERATION, node);
  7528. return -1;
  7529. }
  7530. ProcessPropertyGetAccessor(ctx, node);
  7531. asCDataType to = ctx->type.dataType;
  7532. // TODO: The case -2147483648 gives an unecessary warning of changed sign for implicit conversion
  7533. if( ctx->type.dataType.IsUnsignedType() )
  7534. {
  7535. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  7536. to = asCDataType::CreatePrimitive(ttInt8, false);
  7537. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  7538. to = asCDataType::CreatePrimitive(ttInt16, false);
  7539. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  7540. to = asCDataType::CreatePrimitive(ttInt, false);
  7541. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  7542. to = asCDataType::CreatePrimitive(ttInt64, false);
  7543. else
  7544. {
  7545. Error(TXT_INVALID_TYPE, node);
  7546. return -1;
  7547. }
  7548. }
  7549. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  7550. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  7551. if( !ctx->type.isConstant )
  7552. {
  7553. ConvertToTempVariable(ctx);
  7554. asASSERT(!ctx->type.isLValue);
  7555. if( op == ttMinus )
  7556. {
  7557. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  7558. ctx->bc.InstrSHORT(asBC_NEGi, ctx->type.stackOffset);
  7559. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  7560. ctx->bc.InstrSHORT(asBC_NEGi64, ctx->type.stackOffset);
  7561. else if( ctx->type.dataType.IsFloatType() )
  7562. ctx->bc.InstrSHORT(asBC_NEGf, ctx->type.stackOffset);
  7563. else if( ctx->type.dataType.IsDoubleType() )
  7564. ctx->bc.InstrSHORT(asBC_NEGd, ctx->type.stackOffset);
  7565. else
  7566. {
  7567. Error(TXT_ILLEGAL_OPERATION, node);
  7568. return -1;
  7569. }
  7570. return 0;
  7571. }
  7572. }
  7573. else
  7574. {
  7575. if( op == ttMinus )
  7576. {
  7577. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  7578. ctx->type.intValue = -ctx->type.intValue;
  7579. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  7580. ctx->type.qwordValue = -(asINT64)ctx->type.qwordValue;
  7581. else if( ctx->type.dataType.IsFloatType() )
  7582. ctx->type.floatValue = -ctx->type.floatValue;
  7583. else if( ctx->type.dataType.IsDoubleType() )
  7584. ctx->type.doubleValue = -ctx->type.doubleValue;
  7585. else
  7586. {
  7587. Error(TXT_ILLEGAL_OPERATION, node);
  7588. return -1;
  7589. }
  7590. return 0;
  7591. }
  7592. }
  7593. }
  7594. else if( op == ttNot )
  7595. {
  7596. if( ctx->type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  7597. {
  7598. if( ctx->type.isConstant )
  7599. {
  7600. ctx->type.dwordValue = (ctx->type.dwordValue == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  7601. return 0;
  7602. }
  7603. ProcessPropertyGetAccessor(ctx, node);
  7604. ConvertToTempVariable(ctx);
  7605. asASSERT(!ctx->type.isLValue);
  7606. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  7607. }
  7608. else
  7609. {
  7610. Error(TXT_ILLEGAL_OPERATION, node);
  7611. return -1;
  7612. }
  7613. }
  7614. else if( op == ttBitNot )
  7615. {
  7616. ProcessPropertyGetAccessor(ctx, node);
  7617. asCDataType to = ctx->type.dataType;
  7618. if( ctx->type.dataType.IsIntegerType() )
  7619. {
  7620. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  7621. to = asCDataType::CreatePrimitive(ttUInt8, false);
  7622. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  7623. to = asCDataType::CreatePrimitive(ttUInt16, false);
  7624. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  7625. to = asCDataType::CreatePrimitive(ttUInt, false);
  7626. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  7627. to = asCDataType::CreatePrimitive(ttUInt64, false);
  7628. else
  7629. {
  7630. Error(TXT_INVALID_TYPE, node);
  7631. return -1;
  7632. }
  7633. }
  7634. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  7635. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  7636. if( ctx->type.dataType.IsUnsignedType() )
  7637. {
  7638. if( ctx->type.isConstant )
  7639. {
  7640. ctx->type.qwordValue = ~ctx->type.qwordValue;
  7641. return 0;
  7642. }
  7643. ConvertToTempVariable(ctx);
  7644. asASSERT(!ctx->type.isLValue);
  7645. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  7646. ctx->bc.InstrSHORT(asBC_BNOT, ctx->type.stackOffset);
  7647. else
  7648. ctx->bc.InstrSHORT(asBC_BNOT64, ctx->type.stackOffset);
  7649. }
  7650. else
  7651. {
  7652. Error(TXT_ILLEGAL_OPERATION, node);
  7653. return -1;
  7654. }
  7655. }
  7656. else if( op == ttInc || op == ttDec )
  7657. {
  7658. // Need a reference to the primitive that will be updated
  7659. // The result of this expression is the same reference as before
  7660. // Make sure the reference isn't a temporary variable
  7661. if( ctx->type.isTemporary )
  7662. {
  7663. Error(TXT_REF_IS_TEMP, node);
  7664. return -1;
  7665. }
  7666. if( ctx->type.dataType.IsReadOnly() )
  7667. {
  7668. Error(TXT_REF_IS_READ_ONLY, node);
  7669. return -1;
  7670. }
  7671. if( ctx->property_get || ctx->property_set )
  7672. {
  7673. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  7674. return -1;
  7675. }
  7676. if( !ctx->type.isLValue )
  7677. {
  7678. Error(TXT_NOT_LVALUE, node);
  7679. return -1;
  7680. }
  7681. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  7682. ConvertToReference(ctx);
  7683. else if( !ctx->type.dataType.IsReference() )
  7684. {
  7685. Error(TXT_NOT_VALID_REFERENCE, node);
  7686. return -1;
  7687. }
  7688. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  7689. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  7690. {
  7691. if( op == ttInc )
  7692. ctx->bc.Instr(asBC_INCi64);
  7693. else
  7694. ctx->bc.Instr(asBC_DECi64);
  7695. }
  7696. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt, false)) ||
  7697. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt, false)) )
  7698. {
  7699. if( op == ttInc )
  7700. ctx->bc.Instr(asBC_INCi);
  7701. else
  7702. ctx->bc.Instr(asBC_DECi);
  7703. }
  7704. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  7705. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  7706. {
  7707. if( op == ttInc )
  7708. ctx->bc.Instr(asBC_INCi16);
  7709. else
  7710. ctx->bc.Instr(asBC_DECi16);
  7711. }
  7712. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  7713. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  7714. {
  7715. if( op == ttInc )
  7716. ctx->bc.Instr(asBC_INCi8);
  7717. else
  7718. ctx->bc.Instr(asBC_DECi8);
  7719. }
  7720. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttFloat, false)) )
  7721. {
  7722. if( op == ttInc )
  7723. ctx->bc.Instr(asBC_INCf);
  7724. else
  7725. ctx->bc.Instr(asBC_DECf);
  7726. }
  7727. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttDouble, false)) )
  7728. {
  7729. if( op == ttInc )
  7730. ctx->bc.Instr(asBC_INCd);
  7731. else
  7732. ctx->bc.Instr(asBC_DECd);
  7733. }
  7734. else
  7735. {
  7736. Error(TXT_ILLEGAL_OPERATION, node);
  7737. return -1;
  7738. }
  7739. }
  7740. else
  7741. {
  7742. // Unknown operator
  7743. asASSERT(false);
  7744. return -1;
  7745. }
  7746. return 0;
  7747. }
  7748. void asCCompiler::ConvertToReference(asSExprContext *ctx)
  7749. {
  7750. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  7751. {
  7752. ctx->bc.InstrSHORT(asBC_LDV, ctx->type.stackOffset);
  7753. ctx->type.dataType.MakeReference(true);
  7754. ctx->type.SetVariable(ctx->type.dataType, ctx->type.stackOffset, ctx->type.isTemporary);
  7755. }
  7756. }
  7757. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asCScriptNode *node, asSNameSpace *ns, bool isThisAccess)
  7758. {
  7759. return FindPropertyAccessor(name, ctx, 0, node, ns, isThisAccess);
  7760. }
  7761. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node, asSNameSpace *ns, bool isThisAccess)
  7762. {
  7763. if( engine->ep.propertyAccessorMode == 0 )
  7764. {
  7765. // Property accessors have been disabled by the application
  7766. return 0;
  7767. }
  7768. int getId = 0, setId = 0;
  7769. asCString getName = "get_" + name;
  7770. asCString setName = "set_" + name;
  7771. asCArray<int> multipleGetFuncs, multipleSetFuncs;
  7772. if( ctx->type.dataType.IsObject() )
  7773. {
  7774. asASSERT( ns == 0 );
  7775. // Don't look for property accessors in script classes if the script
  7776. // property accessors have been disabled by the application
  7777. if( !(ctx->type.dataType.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) ||
  7778. engine->ep.propertyAccessorMode == 2 )
  7779. {
  7780. // Check if the object has any methods with the corresponding accessor name(s)
  7781. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  7782. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7783. {
  7784. asCScriptFunction *f = engine->scriptFunctions[ot->methods[n]];
  7785. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  7786. if( f->name == getName && (int)f->parameterTypes.GetLength() == (arg?1:0) )
  7787. {
  7788. if( getId == 0 )
  7789. getId = ot->methods[n];
  7790. else
  7791. {
  7792. if( multipleGetFuncs.GetLength() == 0 )
  7793. multipleGetFuncs.PushLast(getId);
  7794. multipleGetFuncs.PushLast(ot->methods[n]);
  7795. }
  7796. }
  7797. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  7798. if( f->name == setName && (int)f->parameterTypes.GetLength() == (arg?2:1) )
  7799. {
  7800. if( setId == 0 )
  7801. setId = ot->methods[n];
  7802. else
  7803. {
  7804. if( multipleSetFuncs.GetLength() == 0 )
  7805. multipleSetFuncs.PushLast(setId);
  7806. multipleSetFuncs.PushLast(ot->methods[n]);
  7807. }
  7808. }
  7809. }
  7810. }
  7811. }
  7812. else
  7813. {
  7814. asASSERT( ns != 0 );
  7815. // Look for appropriate global functions.
  7816. asCArray<int> funcs;
  7817. asUINT n;
  7818. builder->GetFunctionDescriptions(getName.AddressOf(), funcs, ns);
  7819. for( n = 0; n < funcs.GetLength(); n++ )
  7820. {
  7821. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  7822. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  7823. if( (int)f->parameterTypes.GetLength() == (arg?1:0) )
  7824. {
  7825. if( getId == 0 )
  7826. getId = funcs[n];
  7827. else
  7828. {
  7829. if( multipleGetFuncs.GetLength() == 0 )
  7830. multipleGetFuncs.PushLast(getId);
  7831. multipleGetFuncs.PushLast(funcs[n]);
  7832. }
  7833. }
  7834. }
  7835. funcs.SetLength(0);
  7836. builder->GetFunctionDescriptions(setName.AddressOf(), funcs, ns);
  7837. for( n = 0; n < funcs.GetLength(); n++ )
  7838. {
  7839. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  7840. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  7841. if( (int)f->parameterTypes.GetLength() == (arg?2:1) )
  7842. {
  7843. if( setId == 0 )
  7844. setId = funcs[n];
  7845. else
  7846. {
  7847. if( multipleSetFuncs.GetLength() == 0 )
  7848. multipleSetFuncs.PushLast(getId);
  7849. multipleSetFuncs.PushLast(funcs[n]);
  7850. }
  7851. }
  7852. }
  7853. }
  7854. bool isConst = false;
  7855. if( ctx->type.dataType.IsObjectHandle() )
  7856. isConst = ctx->type.dataType.IsHandleToConst();
  7857. else
  7858. isConst = ctx->type.dataType.IsReadOnly();
  7859. // Check for multiple matches
  7860. if( multipleGetFuncs.GetLength() > 0 )
  7861. {
  7862. // Filter the list by constness
  7863. FilterConst(multipleGetFuncs, !isConst);
  7864. if( multipleGetFuncs.GetLength() > 1 )
  7865. {
  7866. asCString str;
  7867. str.Format(TXT_MULTIPLE_PROP_GET_ACCESSOR_FOR_s, name.AddressOf());
  7868. Error(str, node);
  7869. PrintMatchingFuncs(multipleGetFuncs, node);
  7870. return -1;
  7871. }
  7872. else
  7873. {
  7874. // The id may have changed
  7875. getId = multipleGetFuncs[0];
  7876. }
  7877. }
  7878. if( multipleSetFuncs.GetLength() > 0 )
  7879. {
  7880. // Filter the list by constness
  7881. FilterConst(multipleSetFuncs, !isConst);
  7882. if( multipleSetFuncs.GetLength() > 1 )
  7883. {
  7884. asCString str;
  7885. str.Format(TXT_MULTIPLE_PROP_SET_ACCESSOR_FOR_s, name.AddressOf());
  7886. Error(str, node);
  7887. PrintMatchingFuncs(multipleSetFuncs, node);
  7888. return -1;
  7889. }
  7890. else
  7891. {
  7892. // The id may have changed
  7893. setId = multipleSetFuncs[0];
  7894. }
  7895. }
  7896. // Check for type compatibility between get and set accessor
  7897. if( getId && setId )
  7898. {
  7899. asCScriptFunction *getFunc = builder->GetFunctionDescription(getId);
  7900. asCScriptFunction *setFunc = builder->GetFunctionDescription(setId);
  7901. // It is permitted for a getter to return a handle and the setter to take a reference
  7902. int idx = (arg?1:0);
  7903. if( !getFunc->returnType.IsEqualExceptRefAndConst(setFunc->parameterTypes[idx]) &&
  7904. !((getFunc->returnType.IsObjectHandle() && !setFunc->parameterTypes[idx].IsObjectHandle()) &&
  7905. (getFunc->returnType.GetObjectType() == setFunc->parameterTypes[idx].GetObjectType())) )
  7906. {
  7907. asCString str;
  7908. str.Format(TXT_GET_SET_ACCESSOR_TYPE_MISMATCH_FOR_s, name.AddressOf());
  7909. Error(str, node);
  7910. asCArray<int> funcs;
  7911. funcs.PushLast(getId);
  7912. funcs.PushLast(setId);
  7913. PrintMatchingFuncs(funcs, node);
  7914. return -1;
  7915. }
  7916. }
  7917. // Check if we are within one of the accessors
  7918. int realGetId = getId;
  7919. int realSetId = setId;
  7920. if( outFunc->objectType && isThisAccess )
  7921. {
  7922. // The property accessors would be virtual functions, so we need to find the real implementation
  7923. asCScriptFunction *getFunc = getId ? builder->GetFunctionDescription(getId) : 0;
  7924. if( getFunc &&
  7925. getFunc->funcType == asFUNC_VIRTUAL &&
  7926. outFunc->objectType->DerivesFrom(getFunc->objectType) )
  7927. realGetId = outFunc->objectType->virtualFunctionTable[getFunc->vfTableIdx]->id;
  7928. asCScriptFunction *setFunc = setId ? builder->GetFunctionDescription(setId) : 0;
  7929. if( setFunc &&
  7930. setFunc->funcType == asFUNC_VIRTUAL &&
  7931. outFunc->objectType->DerivesFrom(setFunc->objectType) )
  7932. realSetId = outFunc->objectType->virtualFunctionTable[setFunc->vfTableIdx]->id;
  7933. }
  7934. // Avoid recursive call, by not treating this as a property accessor call.
  7935. // This will also allow having the real property with the same name as the accessors.
  7936. if( (isThisAccess || outFunc->objectType == 0) &&
  7937. ((realGetId && realGetId == outFunc->id) ||
  7938. (realSetId && realSetId == outFunc->id)) )
  7939. {
  7940. getId = 0;
  7941. setId = 0;
  7942. }
  7943. // Check if the application has disabled script written property accessors
  7944. if( engine->ep.propertyAccessorMode == 1 )
  7945. {
  7946. if( getId && builder->GetFunctionDescription(getId)->funcType != asFUNC_SYSTEM )
  7947. getId = 0;
  7948. if( setId && builder->GetFunctionDescription(setId)->funcType != asFUNC_SYSTEM )
  7949. setId = 0;
  7950. }
  7951. if( getId || setId )
  7952. {
  7953. // Property accessors were found, but we don't know which is to be used yet, so
  7954. // we just prepare the bytecode for the method call, and then store the function ids
  7955. // so that the right one can be used when we get there.
  7956. ctx->property_get = getId;
  7957. ctx->property_set = setId;
  7958. if( ctx->type.dataType.IsObject() )
  7959. {
  7960. // If the object is read-only then we need to remember that
  7961. if( (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) ||
  7962. (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) )
  7963. ctx->property_const = true;
  7964. else
  7965. ctx->property_const = false;
  7966. // If the object is a handle then we need to remember that
  7967. ctx->property_handle = ctx->type.dataType.IsObjectHandle();
  7968. ctx->property_ref = ctx->type.dataType.IsReference();
  7969. }
  7970. // The setter's parameter type is used as the property type,
  7971. // unless only the getter is available
  7972. asCDataType dt;
  7973. if( setId )
  7974. dt = builder->GetFunctionDescription(setId)->parameterTypes[(arg?1:0)];
  7975. else
  7976. dt = builder->GetFunctionDescription(getId)->returnType;
  7977. // Just change the type, the context must still maintain information
  7978. // about previous variable offset and the indicator of temporary variable.
  7979. int offset = ctx->type.stackOffset;
  7980. bool isTemp = ctx->type.isTemporary;
  7981. ctx->type.Set(dt);
  7982. ctx->type.stackOffset = (short)offset;
  7983. ctx->type.isTemporary = isTemp;
  7984. ctx->exprNode = node;
  7985. // Store the argument for later use
  7986. if( arg )
  7987. {
  7988. ctx->property_arg = asNEW(asSExprContext)(engine);
  7989. if( ctx->property_arg == 0 )
  7990. {
  7991. // Out of memory
  7992. return -1;
  7993. }
  7994. MergeExprBytecodeAndType(ctx->property_arg, arg);
  7995. }
  7996. return 1;
  7997. }
  7998. // No accessor was found
  7999. return 0;
  8000. }
  8001. int asCCompiler::ProcessPropertySetAccessor(asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node)
  8002. {
  8003. // TODO: A lot of this code is similar to ProcessPropertyGetAccessor. Can we unify them?
  8004. if( !ctx->property_set )
  8005. {
  8006. Error(TXT_PROPERTY_HAS_NO_SET_ACCESSOR, node);
  8007. return -1;
  8008. }
  8009. asCTypeInfo objType = ctx->type;
  8010. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_set);
  8011. // Make sure the arg match the property
  8012. asCArray<int> funcs;
  8013. funcs.PushLast(ctx->property_set);
  8014. asCArray<asSExprContext *> args;
  8015. if( ctx->property_arg )
  8016. args.PushLast(ctx->property_arg);
  8017. args.PushLast(arg);
  8018. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  8019. if( funcs.GetLength() == 0 )
  8020. {
  8021. // MatchFunctions already reported the error
  8022. if( ctx->property_arg )
  8023. {
  8024. asDELETE(ctx->property_arg, asSExprContext);
  8025. ctx->property_arg = 0;
  8026. }
  8027. return -1;
  8028. }
  8029. if( func->objectType )
  8030. {
  8031. // Setup the context with the original type so the method call gets built correctly
  8032. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  8033. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  8034. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  8035. // Don't allow the call if the object is read-only and the property accessor is not const
  8036. if( ctx->property_const && !func->isReadOnly )
  8037. {
  8038. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  8039. asCArray<int> funcs;
  8040. funcs.PushLast(ctx->property_set);
  8041. PrintMatchingFuncs(funcs, node);
  8042. }
  8043. }
  8044. // Call the accessor
  8045. MakeFunctionCall(ctx, ctx->property_set, func->objectType, args, node);
  8046. if( func->objectType )
  8047. {
  8048. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  8049. if( !objType.isTemporary ||
  8050. !ctx->type.dataType.IsReference() ||
  8051. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  8052. {
  8053. // As the method didn't return a reference to a member
  8054. // we can safely release the original object now
  8055. ReleaseTemporaryVariable(objType, &ctx->bc);
  8056. }
  8057. }
  8058. ctx->property_get = 0;
  8059. ctx->property_set = 0;
  8060. if( ctx->property_arg )
  8061. {
  8062. asDELETE(ctx->property_arg, asSExprContext);
  8063. ctx->property_arg = 0;
  8064. }
  8065. return 0;
  8066. }
  8067. void asCCompiler::ProcessPropertyGetAccessor(asSExprContext *ctx, asCScriptNode *node)
  8068. {
  8069. // If no property accessor has been prepared then don't do anything
  8070. if( !ctx->property_get && !ctx->property_set )
  8071. return;
  8072. if( !ctx->property_get )
  8073. {
  8074. // Raise error on missing accessor
  8075. Error(TXT_PROPERTY_HAS_NO_GET_ACCESSOR, node);
  8076. ctx->type.SetDummy();
  8077. return;
  8078. }
  8079. asCTypeInfo objType = ctx->type;
  8080. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_get);
  8081. // Make sure the arg match the property
  8082. asCArray<int> funcs;
  8083. funcs.PushLast(ctx->property_get);
  8084. asCArray<asSExprContext *> args;
  8085. if( ctx->property_arg )
  8086. args.PushLast(ctx->property_arg);
  8087. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  8088. if( funcs.GetLength() == 0 )
  8089. {
  8090. // MatchFunctions already reported the error
  8091. if( ctx->property_arg )
  8092. {
  8093. asDELETE(ctx->property_arg, asSExprContext);
  8094. ctx->property_arg = 0;
  8095. }
  8096. ctx->type.SetDummy();
  8097. return;
  8098. }
  8099. if( func->objectType )
  8100. {
  8101. // Setup the context with the original type so the method call gets built correctly
  8102. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  8103. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  8104. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  8105. // Don't allow the call if the object is read-only and the property accessor is not const
  8106. if( ctx->property_const && !func->isReadOnly )
  8107. {
  8108. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  8109. asCArray<int> funcs;
  8110. funcs.PushLast(ctx->property_get);
  8111. PrintMatchingFuncs(funcs, node);
  8112. }
  8113. }
  8114. // Call the accessor
  8115. MakeFunctionCall(ctx, ctx->property_get, func->objectType, args, node);
  8116. if( func->objectType )
  8117. {
  8118. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  8119. // If the method returned a reference, then we can't release the original
  8120. // object yet, because the reference may be to a member of it
  8121. if( !objType.isTemporary ||
  8122. !(ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) ||
  8123. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  8124. {
  8125. // As the method didn't return a reference to a member
  8126. // we can safely release the original object now
  8127. ReleaseTemporaryVariable(objType, &ctx->bc);
  8128. }
  8129. }
  8130. ctx->property_get = 0;
  8131. ctx->property_set = 0;
  8132. if( ctx->property_arg )
  8133. {
  8134. asDELETE(ctx->property_arg, asSExprContext);
  8135. ctx->property_arg = 0;
  8136. }
  8137. }
  8138. int asCCompiler::CompileExpressionPostOp(asCScriptNode *node, asSExprContext *ctx)
  8139. {
  8140. // Don't allow any postfix operators on expressions that take address of class method
  8141. if( ctx->methodName != "" )
  8142. {
  8143. Error(TXT_INVALID_OP_ON_METHOD, node);
  8144. return -1;
  8145. }
  8146. // Check if the variable is initialized (if it indeed is a variable)
  8147. IsVariableInitialized(&ctx->type, node);
  8148. int op = node->tokenType;
  8149. if( (op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  8150. {
  8151. const char *opName = 0;
  8152. switch( op )
  8153. {
  8154. case ttInc: opName = "opPostInc"; break;
  8155. case ttDec: opName = "opPostDec"; break;
  8156. }
  8157. if( opName )
  8158. {
  8159. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  8160. ProcessPropertyGetAccessor(ctx, node);
  8161. // Is it a const value?
  8162. bool isConst = false;
  8163. if( ctx->type.dataType.IsObjectHandle() )
  8164. isConst = ctx->type.dataType.IsHandleToConst();
  8165. else
  8166. isConst = ctx->type.dataType.IsReadOnly();
  8167. // 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
  8168. // Find the correct method
  8169. asCArray<int> funcs;
  8170. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  8171. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  8172. {
  8173. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  8174. if( func->name == opName &&
  8175. func->parameterTypes.GetLength() == 0 &&
  8176. (!isConst || func->isReadOnly) )
  8177. {
  8178. funcs.PushLast(func->id);
  8179. }
  8180. }
  8181. // Did we find the method?
  8182. if( funcs.GetLength() == 1 )
  8183. {
  8184. asCTypeInfo objType = ctx->type;
  8185. asCArray<asSExprContext *> args;
  8186. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  8187. ReleaseTemporaryVariable(objType, &ctx->bc);
  8188. return 0;
  8189. }
  8190. else if( funcs.GetLength() == 0 )
  8191. {
  8192. asCString str;
  8193. str = asCString(opName) + "()";
  8194. if( isConst )
  8195. str += " const";
  8196. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  8197. Error(str, node);
  8198. ctx->type.SetDummy();
  8199. return -1;
  8200. }
  8201. else if( funcs.GetLength() > 1 )
  8202. {
  8203. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  8204. PrintMatchingFuncs(funcs, node);
  8205. ctx->type.SetDummy();
  8206. return -1;
  8207. }
  8208. }
  8209. }
  8210. else if( op == ttInc || op == ttDec )
  8211. {
  8212. // Make sure the reference isn't a temporary variable
  8213. if( ctx->type.isTemporary )
  8214. {
  8215. Error(TXT_REF_IS_TEMP, node);
  8216. return -1;
  8217. }
  8218. if( ctx->type.dataType.IsReadOnly() )
  8219. {
  8220. Error(TXT_REF_IS_READ_ONLY, node);
  8221. return -1;
  8222. }
  8223. if( ctx->property_get || ctx->property_set )
  8224. {
  8225. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  8226. return -1;
  8227. }
  8228. if( !ctx->type.isLValue )
  8229. {
  8230. Error(TXT_NOT_LVALUE, node);
  8231. return -1;
  8232. }
  8233. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  8234. ConvertToReference(ctx);
  8235. else if( !ctx->type.dataType.IsReference() )
  8236. {
  8237. Error(TXT_NOT_VALID_REFERENCE, node);
  8238. return -1;
  8239. }
  8240. // Copy the value to a temp before changing it
  8241. ConvertToTempVariable(ctx);
  8242. asASSERT(!ctx->type.isLValue);
  8243. // Increment the value pointed to by the reference still in the register
  8244. asEBCInstr iInc = asBC_INCi, iDec = asBC_DECi;
  8245. if( ctx->type.dataType.IsDoubleType() )
  8246. {
  8247. iInc = asBC_INCd;
  8248. iDec = asBC_DECd;
  8249. }
  8250. else if( ctx->type.dataType.IsFloatType() )
  8251. {
  8252. iInc = asBC_INCf;
  8253. iDec = asBC_DECf;
  8254. }
  8255. else if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() )
  8256. {
  8257. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  8258. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  8259. {
  8260. iInc = asBC_INCi16;
  8261. iDec = asBC_DECi16;
  8262. }
  8263. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  8264. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  8265. {
  8266. iInc = asBC_INCi8;
  8267. iDec = asBC_DECi8;
  8268. }
  8269. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  8270. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  8271. {
  8272. iInc = asBC_INCi64;
  8273. iDec = asBC_DECi64;
  8274. }
  8275. }
  8276. else
  8277. {
  8278. Error(TXT_ILLEGAL_OPERATION, node);
  8279. return -1;
  8280. }
  8281. if( op == ttInc ) ctx->bc.Instr(iInc); else ctx->bc.Instr(iDec);
  8282. }
  8283. else if( op == ttDot )
  8284. {
  8285. if( node->firstChild->nodeType == snIdentifier )
  8286. {
  8287. ProcessPropertyGetAccessor(ctx, node);
  8288. // Get the property name
  8289. asCString name(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  8290. if( ctx->type.dataType.IsObject() )
  8291. {
  8292. // We need to look for get/set property accessors.
  8293. // If found, the context stores information on the get/set accessors
  8294. // until it is known which is to be used.
  8295. int r = 0;
  8296. if( node->next && node->next->tokenType == ttOpenBracket )
  8297. {
  8298. // The property accessor should take an index arg
  8299. asSExprContext dummyArg(engine);
  8300. r = FindPropertyAccessor(name, ctx, &dummyArg, node, 0);
  8301. }
  8302. if( r == 0 )
  8303. r = FindPropertyAccessor(name, ctx, node, 0);
  8304. if( r != 0 )
  8305. return r;
  8306. if( !ctx->type.dataType.IsPrimitive() )
  8307. Dereference(ctx, true);
  8308. if( ctx->type.dataType.IsObjectHandle() )
  8309. {
  8310. // Convert the handle to a normal object
  8311. asCDataType dt = ctx->type.dataType;
  8312. dt.MakeHandle(false);
  8313. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  8314. // The handle may not have been an lvalue, but the dereferenced object is
  8315. ctx->type.isLValue = true;
  8316. }
  8317. bool isConst = ctx->type.dataType.IsReadOnly();
  8318. asCObjectProperty *prop = builder->GetObjectProperty(ctx->type.dataType, name.AddressOf());
  8319. if( prop )
  8320. {
  8321. // Is the property access allowed?
  8322. if( prop->isPrivate && (!outFunc || outFunc->objectType != ctx->type.dataType.GetObjectType()) )
  8323. {
  8324. asCString msg;
  8325. msg.Format(TXT_PRIVATE_PROP_ACCESS_s, name.AddressOf());
  8326. Error(msg, node);
  8327. }
  8328. // Put the offset on the stack
  8329. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(ctx->type.dataType.GetObjectType(), false)));
  8330. if( prop->type.IsReference() )
  8331. ctx->bc.Instr(asBC_RDSPtr);
  8332. // Reference to primitive must be stored in the temp register
  8333. if( prop->type.IsPrimitive() )
  8334. {
  8335. ctx->bc.Instr(asBC_PopRPtr);
  8336. }
  8337. // Keep information about temporary variables as deferred expression
  8338. if( ctx->type.isTemporary )
  8339. {
  8340. // Add the release of this reference, as a deferred expression
  8341. asSDeferredParam deferred;
  8342. deferred.origExpr = 0;
  8343. deferred.argInOutFlags = asTM_INREF;
  8344. deferred.argNode = 0;
  8345. deferred.argType.SetVariable(ctx->type.dataType, ctx->type.stackOffset, true);
  8346. ctx->deferredParams.PushLast(deferred);
  8347. }
  8348. // Set the new type and make sure it is not treated as a variable anymore
  8349. ctx->type.dataType = prop->type;
  8350. ctx->type.dataType.MakeReference(true);
  8351. ctx->type.isVariable = false;
  8352. ctx->type.isTemporary = false;
  8353. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  8354. {
  8355. // Objects that are members are not references
  8356. ctx->type.dataType.MakeReference(false);
  8357. }
  8358. ctx->type.dataType.MakeReadOnly(isConst ? true : prop->type.IsReadOnly());
  8359. }
  8360. else
  8361. {
  8362. // If the name is not a property, the compiler must check if the name matches
  8363. // a method, which can be used for constructing delegates
  8364. asIScriptFunction *func = 0;
  8365. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  8366. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  8367. {
  8368. if( engine->scriptFunctions[ot->methods[n]]->name == name )
  8369. {
  8370. func = engine->scriptFunctions[ot->methods[n]];
  8371. break;
  8372. }
  8373. }
  8374. if( func )
  8375. {
  8376. // An object method was found. Keep the name of the method in the expression, but
  8377. // don't actually modify the bytecode at this point since it is not yet known what
  8378. // the method will be used for, or even what overloaded method should be used.
  8379. ctx->methodName = name;
  8380. }
  8381. else
  8382. {
  8383. asCString str;
  8384. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  8385. Error(str, node);
  8386. return -1;
  8387. }
  8388. }
  8389. }
  8390. else
  8391. {
  8392. asCString str;
  8393. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  8394. Error(str, node);
  8395. return -1;
  8396. }
  8397. }
  8398. else
  8399. {
  8400. // Make sure it is an object we are accessing
  8401. if( !ctx->type.dataType.IsObject() )
  8402. {
  8403. asCString str;
  8404. str.Format(TXT_ILLEGAL_OPERATION_ON_s, ctx->type.dataType.Format().AddressOf());
  8405. Error(str, node);
  8406. return -1;
  8407. }
  8408. // Process the get property accessor
  8409. ProcessPropertyGetAccessor(ctx, node);
  8410. bool isConst = false;
  8411. if( ctx->type.dataType.IsObjectHandle() )
  8412. isConst = ctx->type.dataType.IsHandleToConst();
  8413. else
  8414. isConst = ctx->type.dataType.IsReadOnly();
  8415. asCObjectType *trueObj = ctx->type.dataType.GetObjectType();
  8416. asCTypeInfo objType = ctx->type;
  8417. // Compile function call
  8418. int r = CompileFunctionCall(node->firstChild, ctx, trueObj, isConst);
  8419. if( r < 0 ) return r;
  8420. // If the method returned a reference, then we can't release the original
  8421. // object yet, because the reference may be to a member of it
  8422. if( !objType.isTemporary ||
  8423. !(ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) ||
  8424. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  8425. {
  8426. // As the method didn't return a reference to a member
  8427. // we can safely release the original object now
  8428. ReleaseTemporaryVariable(objType, &ctx->bc);
  8429. }
  8430. }
  8431. }
  8432. else if( op == ttOpenBracket )
  8433. {
  8434. // If the property access takes an index arg and the argument hasn't been evaluated yet,
  8435. // then we should use that instead of processing it now. If the argument has already been
  8436. // evaluated, then we should process the property accessor as a get access now as the new
  8437. // index operator is on the result of that accessor.
  8438. asCString propertyName;
  8439. asSNameSpace *ns = 0;
  8440. if( ((ctx->property_get && builder->GetFunctionDescription(ctx->property_get)->GetParamCount() == 1) ||
  8441. (ctx->property_set && builder->GetFunctionDescription(ctx->property_set)->GetParamCount() == 2)) &&
  8442. (ctx->property_arg && ctx->property_arg->type.dataType.GetTokenType() == ttUnrecognizedToken) )
  8443. {
  8444. // Determine the name of the property accessor
  8445. asCScriptFunction *func = 0;
  8446. if( ctx->property_get )
  8447. func = builder->GetFunctionDescription(ctx->property_get);
  8448. else
  8449. func = builder->GetFunctionDescription(ctx->property_set);
  8450. propertyName = func->GetName();
  8451. propertyName = propertyName.SubString(4);
  8452. // Set the original type of the expression so we can re-evaluate the property accessor
  8453. if( func->objectType )
  8454. {
  8455. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  8456. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  8457. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  8458. }
  8459. else
  8460. {
  8461. // Store the namespace where the function is declared
  8462. // so the same function can be found later
  8463. ctx->type.SetDummy();
  8464. ns = func->nameSpace;
  8465. }
  8466. ctx->property_get = ctx->property_set = 0;
  8467. if( ctx->property_arg )
  8468. {
  8469. asDELETE(ctx->property_arg, asSExprContext);
  8470. ctx->property_arg = 0;
  8471. }
  8472. }
  8473. else
  8474. {
  8475. if( !ctx->type.dataType.IsObject() )
  8476. {
  8477. asCString str;
  8478. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  8479. Error(str, node);
  8480. return -1;
  8481. }
  8482. ProcessPropertyGetAccessor(ctx, node);
  8483. }
  8484. Dereference(ctx, true);
  8485. // Compile the expression
  8486. asSExprContext expr(engine);
  8487. CompileAssignment(node->firstChild, &expr);
  8488. // Check for the existence of the opIndex method
  8489. asSExprContext lctx(engine);
  8490. MergeExprBytecodeAndType(&lctx, ctx);
  8491. int r = 0;
  8492. if( propertyName == "" )
  8493. r = CompileOverloadedDualOperator2(node, "opIndex", &lctx, &expr, ctx);
  8494. if( r == 0 )
  8495. {
  8496. // Check for accessors methods for the opIndex
  8497. r = FindPropertyAccessor(propertyName == "" ? "opIndex" : propertyName.AddressOf(), &lctx, &expr, node, ns);
  8498. if( r == 0 )
  8499. {
  8500. asCString str;
  8501. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  8502. Error(str, node);
  8503. return -1;
  8504. }
  8505. else if( r < 0 )
  8506. return -1;
  8507. MergeExprBytecodeAndType(ctx, &lctx);
  8508. }
  8509. }
  8510. else if( op == ttOpenParanthesis )
  8511. {
  8512. // TODO: Most of this is already done by CompileFunctionCall(). Can we share the code?
  8513. // Make sure the expression is a funcdef
  8514. if( !ctx->type.dataType.GetFuncDef() )
  8515. {
  8516. Error(TXT_EXPR_DOESNT_EVAL_TO_FUNC, node);
  8517. return -1;
  8518. }
  8519. // Compile arguments
  8520. asCArray<asSExprContext *> args;
  8521. if( CompileArgumentList(node->lastChild, args) >= 0 )
  8522. {
  8523. // Match arguments with the funcdef
  8524. asCArray<int> funcs;
  8525. funcs.PushLast(ctx->type.dataType.GetFuncDef()->id);
  8526. MatchFunctions(funcs, args, node, ctx->type.dataType.GetFuncDef()->name.AddressOf());
  8527. if( funcs.GetLength() != 1 )
  8528. {
  8529. // The error was reported by MatchFunctions()
  8530. // Dummy value
  8531. ctx->type.SetDummy();
  8532. }
  8533. else
  8534. {
  8535. int r = asSUCCESS;
  8536. // Add the default values for arguments not explicitly supplied
  8537. asCScriptFunction *func = (funcs[0] & FUNC_IMPORTED) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  8538. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  8539. r = CompileDefaultArgs(node, args, func);
  8540. // TODO: funcdef: Do we have to make sure the handle is stored in a temporary variable, or
  8541. // is it enough to make sure it is in a local variable?
  8542. // For function pointer we must guarantee that the function is safe, i.e.
  8543. // by first storing the function pointer in a local variable (if it isn't already in one)
  8544. if( r == asSUCCESS )
  8545. {
  8546. Dereference(ctx, true);
  8547. if( !ctx->type.isVariable )
  8548. ConvertToVariable(ctx);
  8549. else
  8550. {
  8551. // Remove the reference from the stack as the asBC_CALLPTR instruction takes the variable as argument
  8552. ctx->bc.Instr(asBC_PopPtr);
  8553. }
  8554. asCTypeInfo t = ctx->type;
  8555. MakeFunctionCall(ctx, funcs[0], 0, args, node, false, 0, ctx->type.stackOffset);
  8556. ReleaseTemporaryVariable(t, &ctx->bc);
  8557. }
  8558. }
  8559. }
  8560. else
  8561. ctx->type.SetDummy();
  8562. // Cleanup
  8563. for( asUINT n = 0; n < args.GetLength(); n++ )
  8564. if( args[n] )
  8565. {
  8566. asDELETE(args[n],asSExprContext);
  8567. }
  8568. }
  8569. return 0;
  8570. }
  8571. int asCCompiler::GetPrecedence(asCScriptNode *op)
  8572. {
  8573. // x * y, x / y, x % y
  8574. // x + y, x - y
  8575. // x <= y, x < y, x >= y, x > y
  8576. // x = =y, x != y, x xor y, x is y, x !is y
  8577. // x and y
  8578. // x or y
  8579. // The following are not used in this function,
  8580. // but should have lower precedence than the above
  8581. // x ? y : z
  8582. // x = y
  8583. // The expression term have the highest precedence
  8584. if( op->nodeType == snExprTerm )
  8585. return 1;
  8586. // Evaluate operators by token
  8587. int tokenType = op->tokenType;
  8588. if( tokenType == ttStar || tokenType == ttSlash || tokenType == ttPercent )
  8589. return 0;
  8590. if( tokenType == ttPlus || tokenType == ttMinus )
  8591. return -1;
  8592. if( tokenType == ttBitShiftLeft ||
  8593. tokenType == ttBitShiftRight ||
  8594. tokenType == ttBitShiftRightArith )
  8595. return -2;
  8596. if( tokenType == ttAmp )
  8597. return -3;
  8598. if( tokenType == ttBitXor )
  8599. return -4;
  8600. if( tokenType == ttBitOr )
  8601. return -5;
  8602. if( tokenType == ttLessThanOrEqual ||
  8603. tokenType == ttLessThan ||
  8604. tokenType == ttGreaterThanOrEqual ||
  8605. tokenType == ttGreaterThan )
  8606. return -6;
  8607. if( tokenType == ttEqual || tokenType == ttNotEqual || tokenType == ttXor || tokenType == ttIs || tokenType == ttNotIs )
  8608. return -7;
  8609. if( tokenType == ttAnd )
  8610. return -8;
  8611. if( tokenType == ttOr )
  8612. return -9;
  8613. // Unknown operator
  8614. asASSERT(false);
  8615. return 0;
  8616. }
  8617. asUINT asCCompiler::MatchArgument(asCArray<int> &funcs, asCArray<asSOverloadCandidate> &matches, const asSExprContext *argExpr, int paramNum, bool allowObjectConstruct)
  8618. {
  8619. matches.SetLength(0);
  8620. for( asUINT n = 0; n < funcs.GetLength(); n++ )
  8621. {
  8622. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  8623. // Does the function have arguments enough?
  8624. if( (int)desc->parameterTypes.GetLength() <= paramNum )
  8625. continue;
  8626. // Can we make the match by implicit conversion?
  8627. asSExprContext ti(engine);
  8628. ti.type = argExpr->type;
  8629. ti.methodName = argExpr->methodName;
  8630. if( argExpr->type.dataType.IsPrimitive() ) ti.type.dataType.MakeReference(false);
  8631. asUINT cost = ImplicitConversion(&ti, desc->parameterTypes[paramNum], 0, asIC_IMPLICIT_CONV, false, allowObjectConstruct);
  8632. // If the function parameter is an inout-reference then it must not be possible to call the
  8633. // function with an incorrect argument type, even though the type can normally be converted.
  8634. if( desc->parameterTypes[paramNum].IsReference() &&
  8635. desc->inOutFlags[paramNum] == asTM_INOUTREF &&
  8636. desc->parameterTypes[paramNum].GetTokenType() != ttQuestion )
  8637. {
  8638. // Observe, that the below checks are only necessary for when unsafe references have been
  8639. // enabled by the application. Without this the &inout reference form wouldn't be allowed
  8640. // for these value types.
  8641. // Don't allow a primitive to be converted to a reference of another primitive type
  8642. if( desc->parameterTypes[paramNum].IsPrimitive() &&
  8643. desc->parameterTypes[paramNum].GetTokenType() != argExpr->type.dataType.GetTokenType() )
  8644. {
  8645. asASSERT( engine->ep.allowUnsafeReferences );
  8646. continue;
  8647. }
  8648. // Don't allow an enum to be converted to a reference of another enum type
  8649. if( desc->parameterTypes[paramNum].IsEnumType() &&
  8650. desc->parameterTypes[paramNum].GetObjectType() != argExpr->type.dataType.GetObjectType() )
  8651. {
  8652. asASSERT( engine->ep.allowUnsafeReferences );
  8653. continue;
  8654. }
  8655. // Don't allow a non-handle expression to be converted to a reference to a handle
  8656. if( desc->parameterTypes[paramNum].IsObjectHandle() &&
  8657. !argExpr->type.dataType.IsObjectHandle() )
  8658. {
  8659. asASSERT( engine->ep.allowUnsafeReferences );
  8660. continue;
  8661. }
  8662. // Don't allow a value type to be converted
  8663. if( (desc->parameterTypes[paramNum].GetObjectType() && (desc->parameterTypes[paramNum].GetObjectType()->GetFlags() & asOBJ_VALUE)) &&
  8664. (desc->parameterTypes[paramNum].GetObjectType() != argExpr->type.dataType.GetObjectType()) )
  8665. {
  8666. asASSERT( engine->ep.allowUnsafeReferences );
  8667. continue;
  8668. }
  8669. }
  8670. // How well does the argument match the function parameter?
  8671. if( desc->parameterTypes[paramNum].IsEqualExceptRef(ti.type.dataType) )
  8672. matches.PushLast(asSOverloadCandidate(funcs[n], cost));
  8673. }
  8674. return (asUINT)matches.GetLength();
  8675. }
  8676. void asCCompiler::PrepareArgument2(asSExprContext *ctx, asSExprContext *arg, asCDataType *paramType, bool isFunction, int refType, bool isMakingCopy)
  8677. {
  8678. // Reference parameters whose value won't be used don't evaluate the expression
  8679. if( paramType->IsReference() && !(refType & asTM_INREF) )
  8680. {
  8681. // Store the original bytecode so that it can be reused when processing the deferred output parameter
  8682. asSExprContext *orig = asNEW(asSExprContext)(engine);
  8683. if( orig == 0 )
  8684. {
  8685. // Out of memory
  8686. return;
  8687. }
  8688. MergeExprBytecodeAndType(orig, arg);
  8689. arg->origExpr = orig;
  8690. }
  8691. PrepareArgument(paramType, arg, arg->exprNode, isFunction, refType, isMakingCopy);
  8692. // arg still holds the original expression for output parameters
  8693. ctx->bc.AddCode(&arg->bc);
  8694. }
  8695. bool asCCompiler::CompileOverloadedDualOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8696. {
  8697. DetermineSingleFunc(lctx, node);
  8698. DetermineSingleFunc(rctx, node);
  8699. ctx->exprNode = node;
  8700. // What type of operator is it?
  8701. int token = node->tokenType;
  8702. if( token == ttUnrecognizedToken )
  8703. {
  8704. // This happens when the compiler is inferring an assignment
  8705. // operation from another action, for example in preparing a value
  8706. // as a function argument
  8707. token = ttAssignment;
  8708. }
  8709. // boolean operators are not overloadable
  8710. if( token == ttAnd ||
  8711. token == ttOr ||
  8712. token == ttXor )
  8713. return false;
  8714. // Dual operators can also be implemented as class methods
  8715. if( token == ttEqual ||
  8716. token == ttNotEqual )
  8717. {
  8718. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  8719. // Find the matching opEquals method
  8720. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  8721. if( r == 0 )
  8722. {
  8723. // Try again by switching the order of the operands
  8724. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  8725. }
  8726. if( r == 1 )
  8727. {
  8728. if( token == ttNotEqual )
  8729. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  8730. // Success, don't continue
  8731. return true;
  8732. }
  8733. else if( r < 0 )
  8734. {
  8735. // Compiler error, don't continue
  8736. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  8737. return true;
  8738. }
  8739. }
  8740. if( token == ttEqual ||
  8741. token == ttNotEqual ||
  8742. token == ttLessThan ||
  8743. token == ttLessThanOrEqual ||
  8744. token == ttGreaterThan ||
  8745. token == ttGreaterThanOrEqual )
  8746. {
  8747. bool swappedOrder = false;
  8748. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  8749. // Find the matching opCmp method
  8750. int r = CompileOverloadedDualOperator2(node, "opCmp", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  8751. if( r == 0 )
  8752. {
  8753. // Try again by switching the order of the operands
  8754. swappedOrder = true;
  8755. r = CompileOverloadedDualOperator2(node, "opCmp", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  8756. }
  8757. if( r == 1 )
  8758. {
  8759. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  8760. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  8761. ctx->bc.InstrW_DW(asBC_CMPIi, ctx->type.stackOffset, 0);
  8762. if( token == ttEqual )
  8763. ctx->bc.Instr(asBC_TZ);
  8764. else if( token == ttNotEqual )
  8765. ctx->bc.Instr(asBC_TNZ);
  8766. else if( (token == ttLessThan && !swappedOrder) ||
  8767. (token == ttGreaterThan && swappedOrder) )
  8768. ctx->bc.Instr(asBC_TS);
  8769. else if( (token == ttLessThanOrEqual && !swappedOrder) ||
  8770. (token == ttGreaterThanOrEqual && swappedOrder) )
  8771. ctx->bc.Instr(asBC_TNP);
  8772. else if( (token == ttGreaterThan && !swappedOrder) ||
  8773. (token == ttLessThan && swappedOrder) )
  8774. ctx->bc.Instr(asBC_TP);
  8775. else if( (token == ttGreaterThanOrEqual && !swappedOrder) ||
  8776. (token == ttLessThanOrEqual && swappedOrder) )
  8777. ctx->bc.Instr(asBC_TNS);
  8778. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8779. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), a, true);
  8780. // Success, don't continue
  8781. return true;
  8782. }
  8783. else if( r < 0 )
  8784. {
  8785. // Compiler error, don't continue
  8786. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  8787. return true;
  8788. }
  8789. }
  8790. // The rest of the operators are not commutative, and doesn't require specific return type
  8791. const char *op = 0, *op_r = 0;
  8792. switch( token )
  8793. {
  8794. case ttPlus: op = "opAdd"; op_r = "opAdd_r"; break;
  8795. case ttMinus: op = "opSub"; op_r = "opSub_r"; break;
  8796. case ttStar: op = "opMul"; op_r = "opMul_r"; break;
  8797. case ttSlash: op = "opDiv"; op_r = "opDiv_r"; break;
  8798. case ttPercent: op = "opMod"; op_r = "opMod_r"; break;
  8799. case ttBitOr: op = "opOr"; op_r = "opOr_r"; break;
  8800. case ttAmp: op = "opAnd"; op_r = "opAnd_r"; break;
  8801. case ttBitXor: op = "opXor"; op_r = "opXor_r"; break;
  8802. case ttBitShiftLeft: op = "opShl"; op_r = "opShl_r"; break;
  8803. case ttBitShiftRight: op = "opShr"; op_r = "opShr_r"; break;
  8804. case ttBitShiftRightArith: op = "opUShr"; op_r = "opUShr_r"; break;
  8805. }
  8806. // TODO: Might be interesting to support a concatenation operator, e.g. ~
  8807. if( op && op_r )
  8808. {
  8809. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  8810. // Find the matching operator method
  8811. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  8812. if( r == 0 )
  8813. {
  8814. // Try again by switching the order of the operands, and using the reversed operator
  8815. r = CompileOverloadedDualOperator2(node, op_r, rctx, lctx, ctx);
  8816. }
  8817. if( r == 1 )
  8818. {
  8819. // Success, don't continue
  8820. return true;
  8821. }
  8822. else if( r < 0 )
  8823. {
  8824. // Compiler error, don't continue
  8825. ctx->type.SetDummy();
  8826. return true;
  8827. }
  8828. }
  8829. // Assignment operators
  8830. op = 0;
  8831. switch( token )
  8832. {
  8833. case ttAssignment: op = "opAssign"; break;
  8834. case ttAddAssign: op = "opAddAssign"; break;
  8835. case ttSubAssign: op = "opSubAssign"; break;
  8836. case ttMulAssign: op = "opMulAssign"; break;
  8837. case ttDivAssign: op = "opDivAssign"; break;
  8838. case ttModAssign: op = "opModAssign"; break;
  8839. case ttOrAssign: op = "opOrAssign"; break;
  8840. case ttAndAssign: op = "opAndAssign"; break;
  8841. case ttXorAssign: op = "opXorAssign"; break;
  8842. case ttShiftLeftAssign: op = "opShlAssign"; break;
  8843. case ttShiftRightLAssign: op = "opShrAssign"; break;
  8844. case ttShiftRightAAssign: op = "opUShrAssign"; break;
  8845. }
  8846. if( op )
  8847. {
  8848. if( builder->engine->ep.disallowValueAssignForRefType &&
  8849. lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_REF) && !(lctx->type.dataType.GetObjectType()->flags & asOBJ_SCOPED) )
  8850. {
  8851. if( token == ttAssignment )
  8852. Error(TXT_DISALLOW_ASSIGN_ON_REF_TYPE, node);
  8853. else
  8854. Error(TXT_DISALLOW_COMPOUND_ASSIGN_ON_REF_TYPE, node);
  8855. // Set a dummy output
  8856. ctx->type.Set(lctx->type.dataType);
  8857. return true;
  8858. }
  8859. // TODO: Shouldn't accept const lvalue with the assignment operators
  8860. // Find the matching operator method
  8861. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  8862. if( r == 1 )
  8863. {
  8864. // Success, don't continue
  8865. return true;
  8866. }
  8867. else if( r < 0 )
  8868. {
  8869. // Compiler error, don't continue
  8870. ctx->type.SetDummy();
  8871. return true;
  8872. }
  8873. }
  8874. // No suitable operator was found
  8875. return false;
  8876. }
  8877. // Returns negative on compile error
  8878. // zero on no matching operator
  8879. // one on matching operator
  8880. int asCCompiler::CompileOverloadedDualOperator2(asCScriptNode *node, const char *methodName, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx, bool specificReturn, const asCDataType &returnType)
  8881. {
  8882. // Find the matching method
  8883. if( lctx->type.dataType.IsObject() &&
  8884. (!lctx->type.isExplicitHandle ||
  8885. lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  8886. {
  8887. asUINT n;
  8888. // Is the left value a const?
  8889. bool isConst = false;
  8890. if( lctx->type.dataType.IsObjectHandle() )
  8891. isConst = lctx->type.dataType.IsHandleToConst();
  8892. else
  8893. isConst = lctx->type.dataType.IsReadOnly();
  8894. asCArray<int> funcs;
  8895. asCObjectType *ot = lctx->type.dataType.GetObjectType();
  8896. for( n = 0; n < ot->methods.GetLength(); n++ )
  8897. {
  8898. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  8899. if( func->name == methodName &&
  8900. (!specificReturn || func->returnType == returnType) &&
  8901. func->parameterTypes.GetLength() == 1 &&
  8902. (!isConst || func->isReadOnly) )
  8903. {
  8904. // Make sure the method is accessible by the module
  8905. if( builder->module->accessMask & func->accessMask )
  8906. {
  8907. funcs.PushLast(func->id);
  8908. }
  8909. }
  8910. }
  8911. // Which is the best matching function?
  8912. asCArray<asSOverloadCandidate> tempFuncs;
  8913. MatchArgument(funcs, tempFuncs, rctx, 0);
  8914. // Find the lowest cost operator(s)
  8915. asCArray<int> ops;
  8916. asUINT bestCost = asUINT(-1);
  8917. for( n = 0; n < tempFuncs.GetLength(); ++n )
  8918. {
  8919. asUINT cost = tempFuncs[n].cost;
  8920. if( cost < bestCost )
  8921. {
  8922. ops.SetLength(0);
  8923. bestCost = cost;
  8924. }
  8925. if( cost == bestCost )
  8926. ops.PushLast(tempFuncs[n].funcId);
  8927. }
  8928. // If the object is not const, then we need to prioritize non-const methods
  8929. if( !isConst )
  8930. FilterConst(ops);
  8931. // Did we find an operator?
  8932. if( ops.GetLength() == 1 )
  8933. {
  8934. // Process the lctx expression as get accessor
  8935. ProcessPropertyGetAccessor(lctx, node);
  8936. // Merge the bytecode so that it forms lvalue.methodName(rvalue)
  8937. asCTypeInfo objType = lctx->type;
  8938. asCArray<asSExprContext *> args;
  8939. args.PushLast(rctx);
  8940. MergeExprBytecode(ctx, lctx);
  8941. ctx->type = lctx->type;
  8942. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  8943. // If the method returned a reference, then we can't release the original
  8944. // object yet, because the reference may be to a member of it
  8945. if( !objType.isTemporary ||
  8946. !(ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) ||
  8947. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not to a member
  8948. {
  8949. // As the index operator didn't return a reference to a
  8950. // member we can release the original object now
  8951. ReleaseTemporaryVariable(objType, &ctx->bc);
  8952. }
  8953. // Found matching operator
  8954. return 1;
  8955. }
  8956. else if( ops.GetLength() > 1 )
  8957. {
  8958. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  8959. PrintMatchingFuncs(ops, node);
  8960. ctx->type.SetDummy();
  8961. // Compiler error
  8962. return -1;
  8963. }
  8964. }
  8965. // No matching operator
  8966. return 0;
  8967. }
  8968. void asCCompiler::MakeFunctionCall(asSExprContext *ctx, int funcId, asCObjectType *objectType, asCArray<asSExprContext*> &args, asCScriptNode * /*node*/, bool useVariable, int stackOffset, int funcPtrVar)
  8969. {
  8970. if( objectType )
  8971. {
  8972. Dereference(ctx, true);
  8973. // This following warning was removed as there may be valid reasons
  8974. // for calling non-const methods on temporary objects, and we shouldn't
  8975. // warn when there is no way of removing the warning.
  8976. /*
  8977. // Warn if the method is non-const and the object is temporary
  8978. // since the changes will be lost when the object is destroyed.
  8979. // If the object is accessed through a handle, then it is assumed
  8980. // the object is not temporary, even though the handle is.
  8981. if( ctx->type.isTemporary &&
  8982. !ctx->type.dataType.IsObjectHandle() &&
  8983. !engine->scriptFunctions[funcId]->isReadOnly )
  8984. {
  8985. Warning("A non-const method is called on temporary object. Changes to the object may be lost.", node);
  8986. Information(engine->scriptFunctions[funcId]->GetDeclaration(), node);
  8987. }
  8988. */ }
  8989. asCByteCode objBC(engine);
  8990. objBC.AddCode(&ctx->bc);
  8991. PrepareFunctionCall(funcId, &ctx->bc, args);
  8992. // Verify if any of the args variable offsets are used in the other code.
  8993. // If they are exchange the offset for a new one
  8994. asUINT n;
  8995. for( n = 0; n < args.GetLength(); n++ )
  8996. {
  8997. if( args[n]->type.isTemporary && objBC.IsVarUsed(args[n]->type.stackOffset) )
  8998. {
  8999. // Release the current temporary variable
  9000. ReleaseTemporaryVariable(args[n]->type, 0);
  9001. asCDataType dt = args[n]->type.dataType;
  9002. dt.MakeReference(false);
  9003. int l = int(reservedVariables.GetLength());
  9004. objBC.GetVarsUsed(reservedVariables);
  9005. ctx->bc.GetVarsUsed(reservedVariables);
  9006. int newOffset = AllocateVariable(dt, true, IsVariableOnHeap(args[n]->type.stackOffset));
  9007. reservedVariables.SetLength(l);
  9008. asASSERT( IsVariableOnHeap(args[n]->type.stackOffset) == IsVariableOnHeap(newOffset) );
  9009. ctx->bc.ExchangeVar(args[n]->type.stackOffset, newOffset);
  9010. args[n]->type.stackOffset = (short)newOffset;
  9011. args[n]->type.isTemporary = true;
  9012. args[n]->type.isVariable = true;
  9013. }
  9014. }
  9015. // If the function will return a value type on the stack, then we must allocate space
  9016. // for that here and push the address on the stack as a hidden argument to the function
  9017. asCScriptFunction *func = builder->GetFunctionDescription(funcId);
  9018. if( func->DoesReturnOnStack() )
  9019. {
  9020. asASSERT(!useVariable);
  9021. useVariable = true;
  9022. stackOffset = AllocateVariable(func->returnType, true);
  9023. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  9024. }
  9025. ctx->bc.AddCode(&objBC);
  9026. MoveArgsToStack(funcId, &ctx->bc, args, objectType ? true : false);
  9027. PerformFunctionCall(funcId, ctx, false, &args, 0, useVariable, stackOffset, funcPtrVar);
  9028. }
  9029. int asCCompiler::CompileOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9030. {
  9031. // Don't allow any operators on expressions that take address of class method, but allow it on global functions
  9032. if( (lctx->methodName != "" && lctx->type.dataType.GetObjectType()) || (rctx->methodName != "" && rctx->type.dataType.GetObjectType()) )
  9033. {
  9034. Error(TXT_INVALID_OP_ON_METHOD, node);
  9035. return -1;
  9036. }
  9037. IsVariableInitialized(&lctx->type, node);
  9038. IsVariableInitialized(&rctx->type, node);
  9039. if( lctx->type.isExplicitHandle || rctx->type.isExplicitHandle ||
  9040. node->tokenType == ttIs || node->tokenType == ttNotIs )
  9041. {
  9042. CompileOperatorOnHandles(node, lctx, rctx, ctx);
  9043. return 0;
  9044. }
  9045. else
  9046. {
  9047. // Compile an overloaded operator for the two operands
  9048. if( CompileOverloadedDualOperator(node, lctx, rctx, ctx) )
  9049. return 0;
  9050. // If both operands are objects, then we shouldn't continue
  9051. if( lctx->type.dataType.IsObject() && rctx->type.dataType.IsObject() )
  9052. {
  9053. asCString str;
  9054. str.Format(TXT_NO_MATCHING_OP_FOUND_FOR_TYPES_s_AND_s, lctx->type.dataType.Format().AddressOf(), rctx->type.dataType.Format().AddressOf());
  9055. Error(str, node);
  9056. ctx->type.SetDummy();
  9057. return -1;
  9058. }
  9059. // Process the property get accessors (if any)
  9060. ProcessPropertyGetAccessor(lctx, node);
  9061. ProcessPropertyGetAccessor(rctx, node);
  9062. // Make sure we have two variables or constants
  9063. if( lctx->type.dataType.IsReference() ) ConvertToVariableNotIn(lctx, rctx);
  9064. if( rctx->type.dataType.IsReference() ) ConvertToVariableNotIn(rctx, lctx);
  9065. // Make sure lctx doesn't end up with a variable used in rctx
  9066. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  9067. {
  9068. int offset = AllocateVariableNotIn(lctx->type.dataType, true, false, rctx);
  9069. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  9070. ReleaseTemporaryVariable(offset, 0);
  9071. }
  9072. // Math operators
  9073. // + - * / % += -= *= /= %=
  9074. int op = node->tokenType;
  9075. if( op == ttPlus || op == ttAddAssign ||
  9076. op == ttMinus || op == ttSubAssign ||
  9077. op == ttStar || op == ttMulAssign ||
  9078. op == ttSlash || op == ttDivAssign ||
  9079. op == ttPercent || op == ttModAssign )
  9080. {
  9081. CompileMathOperator(node, lctx, rctx, ctx);
  9082. return 0;
  9083. }
  9084. // Bitwise operators
  9085. // << >> >>> & | ^ <<= >>= >>>= &= |= ^=
  9086. if( op == ttAmp || op == ttAndAssign ||
  9087. op == ttBitOr || op == ttOrAssign ||
  9088. op == ttBitXor || op == ttXorAssign ||
  9089. op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  9090. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  9091. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  9092. {
  9093. CompileBitwiseOperator(node, lctx, rctx, ctx);
  9094. return 0;
  9095. }
  9096. // Comparison operators
  9097. // == != < > <= >=
  9098. if( op == ttEqual || op == ttNotEqual ||
  9099. op == ttLessThan || op == ttLessThanOrEqual ||
  9100. op == ttGreaterThan || op == ttGreaterThanOrEqual )
  9101. {
  9102. CompileComparisonOperator(node, lctx, rctx, ctx);
  9103. return 0;
  9104. }
  9105. // Boolean operators
  9106. // && || ^^
  9107. if( op == ttAnd || op == ttOr || op == ttXor )
  9108. {
  9109. CompileBooleanOperator(node, lctx, rctx, ctx);
  9110. return 0;
  9111. }
  9112. }
  9113. asASSERT(false);
  9114. return -1;
  9115. }
  9116. void asCCompiler::ConvertToTempVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  9117. {
  9118. int l = int(reservedVariables.GetLength());
  9119. if( exclude ) exclude->bc.GetVarsUsed(reservedVariables);
  9120. ConvertToTempVariable(ctx);
  9121. reservedVariables.SetLength(l);
  9122. }
  9123. void asCCompiler::ConvertToTempVariable(asSExprContext *ctx)
  9124. {
  9125. // This is only used for primitive types and null handles
  9126. asASSERT( ctx->type.dataType.IsPrimitive() || ctx->type.dataType.IsNullHandle() );
  9127. ConvertToVariable(ctx);
  9128. if( !ctx->type.isTemporary )
  9129. {
  9130. if( ctx->type.dataType.IsPrimitive() )
  9131. {
  9132. // Copy the variable to a temporary variable
  9133. int offset = AllocateVariable(ctx->type.dataType, true);
  9134. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9135. ctx->bc.InstrW_W(asBC_CpyVtoV4, offset, ctx->type.stackOffset);
  9136. else
  9137. ctx->bc.InstrW_W(asBC_CpyVtoV8, offset, ctx->type.stackOffset);
  9138. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  9139. }
  9140. else
  9141. {
  9142. // We should never get here
  9143. asASSERT(false);
  9144. }
  9145. }
  9146. }
  9147. void asCCompiler::ConvertToVariable(asSExprContext *ctx)
  9148. {
  9149. // We should never get here while the context is still an unprocessed property accessor
  9150. asASSERT(ctx->property_get == 0 && ctx->property_set == 0);
  9151. int offset;
  9152. if( !ctx->type.isVariable &&
  9153. (ctx->type.dataType.IsObjectHandle() ||
  9154. (ctx->type.dataType.IsObject() && ctx->type.dataType.SupportHandles())) )
  9155. {
  9156. offset = AllocateVariable(ctx->type.dataType, true);
  9157. if( ctx->type.IsNullConstant() )
  9158. {
  9159. if( ctx->bc.GetLastInstr() == asBC_PshNull )
  9160. ctx->bc.Instr(asBC_PopPtr); // Pop the null constant pushed onto the stack
  9161. ctx->bc.InstrSHORT(asBC_ClrVPtr, (short)offset);
  9162. }
  9163. else
  9164. {
  9165. // Copy the object handle to a variable
  9166. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  9167. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  9168. ctx->bc.Instr(asBC_PopPtr);
  9169. }
  9170. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  9171. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  9172. ctx->type.dataType.MakeHandle(true);
  9173. }
  9174. else if( (!ctx->type.isVariable || ctx->type.dataType.IsReference()) &&
  9175. ctx->type.dataType.IsPrimitive() )
  9176. {
  9177. if( ctx->type.isConstant )
  9178. {
  9179. offset = AllocateVariable(ctx->type.dataType, true);
  9180. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  9181. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, ctx->type.byteValue);
  9182. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  9183. ctx->bc.InstrSHORT_W(asBC_SetV2, (short)offset, ctx->type.wordValue);
  9184. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  9185. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, ctx->type.dwordValue);
  9186. else
  9187. ctx->bc.InstrSHORT_QW(asBC_SetV8, (short)offset, ctx->type.qwordValue);
  9188. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  9189. return;
  9190. }
  9191. else
  9192. {
  9193. asASSERT(ctx->type.dataType.IsPrimitive());
  9194. asASSERT(ctx->type.dataType.IsReference());
  9195. ctx->type.dataType.MakeReference(false);
  9196. offset = AllocateVariable(ctx->type.dataType, true);
  9197. // Read the value from the address in the register directly into the variable
  9198. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  9199. ctx->bc.InstrSHORT(asBC_RDR1, (short)offset);
  9200. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  9201. ctx->bc.InstrSHORT(asBC_RDR2, (short)offset);
  9202. else if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9203. ctx->bc.InstrSHORT(asBC_RDR4, (short)offset);
  9204. else
  9205. ctx->bc.InstrSHORT(asBC_RDR8, (short)offset);
  9206. }
  9207. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  9208. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  9209. }
  9210. }
  9211. void asCCompiler::ConvertToVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  9212. {
  9213. int l = int(reservedVariables.GetLength());
  9214. if( exclude ) exclude->bc.GetVarsUsed(reservedVariables);
  9215. ConvertToVariable(ctx);
  9216. reservedVariables.SetLength(l);
  9217. }
  9218. void asCCompiler::CompileMathOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9219. {
  9220. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  9221. // TODO: clean up: This initial part is identical to CompileComparisonOperator. Make a common function out of it
  9222. // Implicitly convert the operands to a number type
  9223. asCDataType to;
  9224. // If either operand is a non-primitive then use the primitive type
  9225. if( !lctx->type.dataType.IsPrimitive() )
  9226. to.SetTokenType(rctx->type.dataType.GetTokenType());
  9227. else if( !rctx->type.dataType.IsPrimitive() )
  9228. to.SetTokenType(lctx->type.dataType.GetTokenType());
  9229. else if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  9230. to.SetTokenType(ttDouble);
  9231. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  9232. to.SetTokenType(ttFloat);
  9233. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9234. {
  9235. // Convert to int64 if both are signed or if one is non-constant and signed
  9236. if( (lctx->type.dataType.IsIntegerType() && rctx->type.dataType.IsIntegerType()) ||
  9237. (lctx->type.dataType.IsIntegerType() && !lctx->type.isConstant) ||
  9238. (rctx->type.dataType.IsIntegerType() && !rctx->type.isConstant) )
  9239. to.SetTokenType(ttInt64);
  9240. else
  9241. to.SetTokenType(ttUInt64);
  9242. }
  9243. else
  9244. {
  9245. // Convert to int32 if both are signed or if one is non-constant and signed
  9246. if( (lctx->type.dataType.IsIntegerType() && rctx->type.dataType.IsIntegerType()) ||
  9247. (lctx->type.dataType.IsIntegerType() && !lctx->type.isConstant) ||
  9248. (rctx->type.dataType.IsIntegerType() && !rctx->type.isConstant) )
  9249. to.SetTokenType(ttInt);
  9250. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  9251. to.SetTokenType(ttUInt);
  9252. else if( lctx->type.dataType.IsBooleanType() || rctx->type.dataType.IsBooleanType() )
  9253. to.SetTokenType(ttBool);
  9254. }
  9255. // If doing an operation with double constant and float variable, the constant should be converted to float
  9256. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  9257. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  9258. to.SetTokenType(ttFloat);
  9259. // Do the actual conversion
  9260. int l = int(reservedVariables.GetLength());
  9261. rctx->bc.GetVarsUsed(reservedVariables);
  9262. lctx->bc.GetVarsUsed(reservedVariables);
  9263. if( lctx->type.dataType.IsReference() )
  9264. ConvertToVariable(lctx);
  9265. if( rctx->type.dataType.IsReference() )
  9266. ConvertToVariable(rctx);
  9267. if( to.IsPrimitive() )
  9268. {
  9269. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  9270. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true);
  9271. }
  9272. reservedVariables.SetLength(l);
  9273. // Verify that the conversion was successful
  9274. if( !lctx->type.dataType.IsIntegerType() &&
  9275. !lctx->type.dataType.IsUnsignedType() &&
  9276. !lctx->type.dataType.IsFloatType() &&
  9277. !lctx->type.dataType.IsDoubleType() )
  9278. {
  9279. asCString str;
  9280. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, lctx->type.dataType.Format().AddressOf());
  9281. Error(str, node);
  9282. ctx->type.SetDummy();
  9283. return;
  9284. }
  9285. if( !rctx->type.dataType.IsIntegerType() &&
  9286. !rctx->type.dataType.IsUnsignedType() &&
  9287. !rctx->type.dataType.IsFloatType() &&
  9288. !rctx->type.dataType.IsDoubleType() )
  9289. {
  9290. asCString str;
  9291. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, rctx->type.dataType.Format().AddressOf());
  9292. Error(str, node);
  9293. ctx->type.SetDummy();
  9294. return;
  9295. }
  9296. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  9297. // Verify if we are dividing with a constant zero
  9298. int op = node->tokenType;
  9299. if( rctx->type.isConstant && rctx->type.qwordValue == 0 &&
  9300. (op == ttSlash || op == ttDivAssign ||
  9301. op == ttPercent || op == ttModAssign) )
  9302. {
  9303. Error(TXT_DIVIDE_BY_ZERO, node);
  9304. }
  9305. if( !isConstant )
  9306. {
  9307. ConvertToVariableNotIn(lctx, rctx);
  9308. ConvertToVariableNotIn(rctx, lctx);
  9309. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9310. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9311. if( op == ttAddAssign || op == ttSubAssign ||
  9312. op == ttMulAssign || op == ttDivAssign ||
  9313. op == ttModAssign )
  9314. {
  9315. // Merge the operands in the different order so that they are evaluated correctly
  9316. MergeExprBytecode(ctx, rctx);
  9317. MergeExprBytecode(ctx, lctx);
  9318. // We must not process the deferred parameters yet, as
  9319. // it may overwrite the lvalue kept in the register
  9320. }
  9321. else
  9322. {
  9323. MergeExprBytecode(ctx, lctx);
  9324. MergeExprBytecode(ctx, rctx);
  9325. ProcessDeferredParams(ctx);
  9326. }
  9327. asEBCInstr instruction = asBC_ADDi;
  9328. if( lctx->type.dataType.IsIntegerType() ||
  9329. lctx->type.dataType.IsUnsignedType() )
  9330. {
  9331. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9332. {
  9333. if( op == ttPlus || op == ttAddAssign )
  9334. instruction = asBC_ADDi;
  9335. else if( op == ttMinus || op == ttSubAssign )
  9336. instruction = asBC_SUBi;
  9337. else if( op == ttStar || op == ttMulAssign )
  9338. instruction = asBC_MULi;
  9339. else if( op == ttSlash || op == ttDivAssign )
  9340. {
  9341. if( lctx->type.dataType.IsIntegerType() )
  9342. instruction = asBC_DIVi;
  9343. else
  9344. instruction = asBC_DIVu;
  9345. }
  9346. else if( op == ttPercent || op == ttModAssign )
  9347. {
  9348. if( lctx->type.dataType.IsIntegerType() )
  9349. instruction = asBC_MODi;
  9350. else
  9351. instruction = asBC_MODu;
  9352. }
  9353. }
  9354. else
  9355. {
  9356. if( op == ttPlus || op == ttAddAssign )
  9357. instruction = asBC_ADDi64;
  9358. else if( op == ttMinus || op == ttSubAssign )
  9359. instruction = asBC_SUBi64;
  9360. else if( op == ttStar || op == ttMulAssign )
  9361. instruction = asBC_MULi64;
  9362. else if( op == ttSlash || op == ttDivAssign )
  9363. {
  9364. if( lctx->type.dataType.IsIntegerType() )
  9365. instruction = asBC_DIVi64;
  9366. else
  9367. instruction = asBC_DIVu64;
  9368. }
  9369. else if( op == ttPercent || op == ttModAssign )
  9370. {
  9371. if( lctx->type.dataType.IsIntegerType() )
  9372. instruction = asBC_MODi64;
  9373. else
  9374. instruction = asBC_MODu64;
  9375. }
  9376. }
  9377. }
  9378. else if( lctx->type.dataType.IsFloatType() )
  9379. {
  9380. if( op == ttPlus || op == ttAddAssign )
  9381. instruction = asBC_ADDf;
  9382. else if( op == ttMinus || op == ttSubAssign )
  9383. instruction = asBC_SUBf;
  9384. else if( op == ttStar || op == ttMulAssign )
  9385. instruction = asBC_MULf;
  9386. else if( op == ttSlash || op == ttDivAssign )
  9387. instruction = asBC_DIVf;
  9388. else if( op == ttPercent || op == ttModAssign )
  9389. instruction = asBC_MODf;
  9390. }
  9391. else if( lctx->type.dataType.IsDoubleType() )
  9392. {
  9393. if( op == ttPlus || op == ttAddAssign )
  9394. instruction = asBC_ADDd;
  9395. else if( op == ttMinus || op == ttSubAssign )
  9396. instruction = asBC_SUBd;
  9397. else if( op == ttStar || op == ttMulAssign )
  9398. instruction = asBC_MULd;
  9399. else if( op == ttSlash || op == ttDivAssign )
  9400. instruction = asBC_DIVd;
  9401. else if( op == ttPercent || op == ttModAssign )
  9402. instruction = asBC_MODd;
  9403. }
  9404. else
  9405. {
  9406. // Shouldn't be possible
  9407. asASSERT(false);
  9408. }
  9409. // Do the operation
  9410. int a = AllocateVariable(lctx->type.dataType, true);
  9411. int b = lctx->type.stackOffset;
  9412. int c = rctx->type.stackOffset;
  9413. ctx->bc.InstrW_W_W(instruction, a, b, c);
  9414. ctx->type.SetVariable(lctx->type.dataType, a, true);
  9415. }
  9416. else
  9417. {
  9418. // Both values are constants
  9419. if( lctx->type.dataType.IsIntegerType() ||
  9420. lctx->type.dataType.IsUnsignedType() )
  9421. {
  9422. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9423. {
  9424. int v = 0;
  9425. if( op == ttPlus )
  9426. v = lctx->type.intValue + rctx->type.intValue;
  9427. else if( op == ttMinus )
  9428. v = lctx->type.intValue - rctx->type.intValue;
  9429. else if( op == ttStar )
  9430. v = lctx->type.intValue * rctx->type.intValue;
  9431. else if( op == ttSlash )
  9432. {
  9433. // TODO: Should probably report an error, rather than silently convert the value to 0
  9434. if( rctx->type.intValue == 0 || (rctx->type.intValue == -1 && lctx->type.dwordValue == 0x80000000) )
  9435. v = 0;
  9436. else
  9437. if( lctx->type.dataType.IsIntegerType() )
  9438. v = lctx->type.intValue / rctx->type.intValue;
  9439. else
  9440. v = lctx->type.dwordValue / rctx->type.dwordValue;
  9441. }
  9442. else if( op == ttPercent )
  9443. {
  9444. // TODO: Should probably report an error, rather than silently convert the value to 0
  9445. if( rctx->type.intValue == 0 || (rctx->type.intValue == -1 && lctx->type.dwordValue == 0x80000000) )
  9446. v = 0;
  9447. else
  9448. if( lctx->type.dataType.IsIntegerType() )
  9449. v = lctx->type.intValue % rctx->type.intValue;
  9450. else
  9451. v = lctx->type.dwordValue % rctx->type.dwordValue;
  9452. }
  9453. ctx->type.SetConstantDW(lctx->type.dataType, v);
  9454. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  9455. if( lctx->type.dataType.GetTokenType() == ttUInt && op == ttMinus && lctx->type.intValue < rctx->type.intValue )
  9456. ctx->type.dataType.SetTokenType(ttInt);
  9457. }
  9458. else
  9459. {
  9460. asQWORD v = 0;
  9461. if( op == ttPlus )
  9462. v = lctx->type.qwordValue + rctx->type.qwordValue;
  9463. else if( op == ttMinus )
  9464. v = lctx->type.qwordValue - rctx->type.qwordValue;
  9465. else if( op == ttStar )
  9466. v = lctx->type.qwordValue * rctx->type.qwordValue;
  9467. else if( op == ttSlash )
  9468. {
  9469. // TODO: Should probably report an error, rather than silently convert the value to 0
  9470. if( rctx->type.qwordValue == 0 || (rctx->type.qwordValue == asQWORD(-1) && lctx->type.qwordValue == (asQWORD(1)<<63)) )
  9471. v = 0;
  9472. else
  9473. if( lctx->type.dataType.IsIntegerType() )
  9474. v = asINT64(lctx->type.qwordValue) / asINT64(rctx->type.qwordValue);
  9475. else
  9476. v = lctx->type.qwordValue / rctx->type.qwordValue;
  9477. }
  9478. else if( op == ttPercent )
  9479. {
  9480. // TODO: Should probably report an error, rather than silently convert the value to 0
  9481. if( rctx->type.qwordValue == 0 || (rctx->type.qwordValue == asQWORD(-1) && lctx->type.qwordValue == (asQWORD(1)<<63)) )
  9482. v = 0;
  9483. else
  9484. if( lctx->type.dataType.IsIntegerType() )
  9485. v = asINT64(lctx->type.qwordValue) % asINT64(rctx->type.qwordValue);
  9486. else
  9487. v = lctx->type.qwordValue % rctx->type.qwordValue;
  9488. }
  9489. ctx->type.SetConstantQW(lctx->type.dataType, v);
  9490. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  9491. if( lctx->type.dataType.GetTokenType() == ttUInt64 && op == ttMinus && lctx->type.qwordValue < rctx->type.qwordValue )
  9492. ctx->type.dataType.SetTokenType(ttInt64);
  9493. }
  9494. }
  9495. else if( lctx->type.dataType.IsFloatType() )
  9496. {
  9497. float v = 0.0f;
  9498. if( op == ttPlus )
  9499. v = lctx->type.floatValue + rctx->type.floatValue;
  9500. else if( op == ttMinus )
  9501. v = lctx->type.floatValue - rctx->type.floatValue;
  9502. else if( op == ttStar )
  9503. v = lctx->type.floatValue * rctx->type.floatValue;
  9504. else if( op == ttSlash )
  9505. {
  9506. if( rctx->type.floatValue == 0 )
  9507. v = 0;
  9508. else
  9509. v = lctx->type.floatValue / rctx->type.floatValue;
  9510. }
  9511. else if( op == ttPercent )
  9512. {
  9513. if( rctx->type.floatValue == 0 )
  9514. v = 0;
  9515. else
  9516. v = fmodf(lctx->type.floatValue, rctx->type.floatValue);
  9517. }
  9518. ctx->type.SetConstantF(lctx->type.dataType, v);
  9519. }
  9520. else if( lctx->type.dataType.IsDoubleType() )
  9521. {
  9522. double v = 0.0;
  9523. if( op == ttPlus )
  9524. v = lctx->type.doubleValue + rctx->type.doubleValue;
  9525. else if( op == ttMinus )
  9526. v = lctx->type.doubleValue - rctx->type.doubleValue;
  9527. else if( op == ttStar )
  9528. v = lctx->type.doubleValue * rctx->type.doubleValue;
  9529. else if( op == ttSlash )
  9530. {
  9531. if( rctx->type.doubleValue == 0 )
  9532. v = 0;
  9533. else
  9534. v = lctx->type.doubleValue / rctx->type.doubleValue;
  9535. }
  9536. else if( op == ttPercent )
  9537. {
  9538. if( rctx->type.doubleValue == 0 )
  9539. v = 0;
  9540. else
  9541. v = fmod(lctx->type.doubleValue, rctx->type.doubleValue);
  9542. }
  9543. ctx->type.SetConstantD(lctx->type.dataType, v);
  9544. }
  9545. else
  9546. {
  9547. // Shouldn't be possible
  9548. asASSERT(false);
  9549. }
  9550. }
  9551. }
  9552. void asCCompiler::CompileBitwiseOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9553. {
  9554. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  9555. int op = node->tokenType;
  9556. if( op == ttAmp || op == ttAndAssign ||
  9557. op == ttBitOr || op == ttOrAssign ||
  9558. op == ttBitXor || op == ttXorAssign )
  9559. {
  9560. // Convert left hand operand to integer if it's not already one
  9561. asCDataType to;
  9562. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 ||
  9563. rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9564. to.SetTokenType(ttUInt64);
  9565. else
  9566. to.SetTokenType(ttUInt);
  9567. // Do the actual conversion
  9568. int l = int(reservedVariables.GetLength());
  9569. rctx->bc.GetVarsUsed(reservedVariables);
  9570. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  9571. reservedVariables.SetLength(l);
  9572. // Verify that the conversion was successful
  9573. if( !lctx->type.dataType.IsUnsignedType() )
  9574. {
  9575. asCString str;
  9576. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9577. Error(str, node);
  9578. }
  9579. // Convert right hand operand to same type as left hand operand
  9580. l = int(reservedVariables.GetLength());
  9581. lctx->bc.GetVarsUsed(reservedVariables);
  9582. ImplicitConversion(rctx, lctx->type.dataType, node, asIC_IMPLICIT_CONV, true);
  9583. reservedVariables.SetLength(l);
  9584. if( !rctx->type.dataType.IsEqualExceptRef(lctx->type.dataType) )
  9585. {
  9586. asCString str;
  9587. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  9588. Error(str, node);
  9589. }
  9590. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  9591. if( !isConstant )
  9592. {
  9593. ConvertToVariableNotIn(lctx, rctx);
  9594. ConvertToVariableNotIn(rctx, lctx);
  9595. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9596. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9597. if( op == ttAndAssign || op == ttOrAssign || op == ttXorAssign )
  9598. {
  9599. // Compound assignments execute the right hand value first
  9600. MergeExprBytecode(ctx, rctx);
  9601. MergeExprBytecode(ctx, lctx);
  9602. }
  9603. else
  9604. {
  9605. MergeExprBytecode(ctx, lctx);
  9606. MergeExprBytecode(ctx, rctx);
  9607. }
  9608. ProcessDeferredParams(ctx);
  9609. asEBCInstr instruction = asBC_BAND;
  9610. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9611. {
  9612. if( op == ttAmp || op == ttAndAssign )
  9613. instruction = asBC_BAND;
  9614. else if( op == ttBitOr || op == ttOrAssign )
  9615. instruction = asBC_BOR;
  9616. else if( op == ttBitXor || op == ttXorAssign )
  9617. instruction = asBC_BXOR;
  9618. }
  9619. else
  9620. {
  9621. if( op == ttAmp || op == ttAndAssign )
  9622. instruction = asBC_BAND64;
  9623. else if( op == ttBitOr || op == ttOrAssign )
  9624. instruction = asBC_BOR64;
  9625. else if( op == ttBitXor || op == ttXorAssign )
  9626. instruction = asBC_BXOR64;
  9627. }
  9628. // Do the operation
  9629. int a = AllocateVariable(lctx->type.dataType, true);
  9630. int b = lctx->type.stackOffset;
  9631. int c = rctx->type.stackOffset;
  9632. ctx->bc.InstrW_W_W(instruction, a, b, c);
  9633. ctx->type.SetVariable(lctx->type.dataType, a, true);
  9634. }
  9635. else
  9636. {
  9637. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9638. {
  9639. asQWORD v = 0;
  9640. if( op == ttAmp )
  9641. v = lctx->type.qwordValue & rctx->type.qwordValue;
  9642. else if( op == ttBitOr )
  9643. v = lctx->type.qwordValue | rctx->type.qwordValue;
  9644. else if( op == ttBitXor )
  9645. v = lctx->type.qwordValue ^ rctx->type.qwordValue;
  9646. // Remember the result
  9647. ctx->type.SetConstantQW(lctx->type.dataType, v);
  9648. }
  9649. else
  9650. {
  9651. asDWORD v = 0;
  9652. if( op == ttAmp )
  9653. v = lctx->type.dwordValue & rctx->type.dwordValue;
  9654. else if( op == ttBitOr )
  9655. v = lctx->type.dwordValue | rctx->type.dwordValue;
  9656. else if( op == ttBitXor )
  9657. v = lctx->type.dwordValue ^ rctx->type.dwordValue;
  9658. // Remember the result
  9659. ctx->type.SetConstantDW(lctx->type.dataType, v);
  9660. }
  9661. }
  9662. }
  9663. else if( op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  9664. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  9665. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  9666. {
  9667. // Don't permit object to primitive conversion, since we don't know which integer type is the correct one
  9668. if( lctx->type.dataType.IsObject() )
  9669. {
  9670. asCString str;
  9671. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  9672. Error(str, node);
  9673. // Set an integer value and allow the compiler to continue
  9674. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttInt, true), 0);
  9675. return;
  9676. }
  9677. // Convert left hand operand to integer if it's not already one
  9678. asCDataType to = lctx->type.dataType;
  9679. if( lctx->type.dataType.IsUnsignedType() &&
  9680. lctx->type.dataType.GetSizeInMemoryBytes() < 4 )
  9681. {
  9682. to = asCDataType::CreatePrimitive(ttUInt, false);
  9683. }
  9684. else if( !lctx->type.dataType.IsUnsignedType() )
  9685. {
  9686. asCDataType to;
  9687. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9688. to.SetTokenType(ttInt64);
  9689. else
  9690. to.SetTokenType(ttInt);
  9691. }
  9692. // Do the actual conversion
  9693. int l = int(reservedVariables.GetLength());
  9694. rctx->bc.GetVarsUsed(reservedVariables);
  9695. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  9696. reservedVariables.SetLength(l);
  9697. // Verify that the conversion was successful
  9698. if( lctx->type.dataType != to )
  9699. {
  9700. asCString str;
  9701. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9702. Error(str, node);
  9703. }
  9704. // Right operand must be 32bit uint
  9705. l = int(reservedVariables.GetLength());
  9706. lctx->bc.GetVarsUsed(reservedVariables);
  9707. ImplicitConversion(rctx, asCDataType::CreatePrimitive(ttUInt, true), node, asIC_IMPLICIT_CONV, true);
  9708. reservedVariables.SetLength(l);
  9709. if( !rctx->type.dataType.IsUnsignedType() )
  9710. {
  9711. asCString str;
  9712. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "uint");
  9713. Error(str, node);
  9714. }
  9715. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  9716. if( !isConstant )
  9717. {
  9718. ConvertToVariableNotIn(lctx, rctx);
  9719. ConvertToVariableNotIn(rctx, lctx);
  9720. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9721. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9722. if( op == ttShiftLeftAssign || op == ttShiftRightLAssign || op == ttShiftRightAAssign )
  9723. {
  9724. // Compound assignments execute the right hand value first
  9725. MergeExprBytecode(ctx, rctx);
  9726. MergeExprBytecode(ctx, lctx);
  9727. }
  9728. else
  9729. {
  9730. MergeExprBytecode(ctx, lctx);
  9731. MergeExprBytecode(ctx, rctx);
  9732. }
  9733. ProcessDeferredParams(ctx);
  9734. asEBCInstr instruction = asBC_BSLL;
  9735. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9736. {
  9737. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  9738. instruction = asBC_BSLL;
  9739. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  9740. instruction = asBC_BSRL;
  9741. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  9742. instruction = asBC_BSRA;
  9743. }
  9744. else
  9745. {
  9746. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  9747. instruction = asBC_BSLL64;
  9748. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  9749. instruction = asBC_BSRL64;
  9750. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  9751. instruction = asBC_BSRA64;
  9752. }
  9753. // Do the operation
  9754. int a = AllocateVariable(lctx->type.dataType, true);
  9755. int b = lctx->type.stackOffset;
  9756. int c = rctx->type.stackOffset;
  9757. ctx->bc.InstrW_W_W(instruction, a, b, c);
  9758. ctx->type.SetVariable(lctx->type.dataType, a, true);
  9759. }
  9760. else
  9761. {
  9762. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9763. {
  9764. asDWORD v = 0;
  9765. if( op == ttBitShiftLeft )
  9766. v = lctx->type.dwordValue << rctx->type.dwordValue;
  9767. else if( op == ttBitShiftRight )
  9768. v = lctx->type.dwordValue >> rctx->type.dwordValue;
  9769. else if( op == ttBitShiftRightArith )
  9770. v = lctx->type.intValue >> rctx->type.dwordValue;
  9771. ctx->type.SetConstantDW(lctx->type.dataType, v);
  9772. }
  9773. else
  9774. {
  9775. asQWORD v = 0;
  9776. if( op == ttBitShiftLeft )
  9777. v = lctx->type.qwordValue << rctx->type.dwordValue;
  9778. else if( op == ttBitShiftRight )
  9779. v = lctx->type.qwordValue >> rctx->type.dwordValue;
  9780. else if( op == ttBitShiftRightArith )
  9781. v = asINT64(lctx->type.qwordValue) >> rctx->type.dwordValue;
  9782. ctx->type.SetConstantQW(lctx->type.dataType, v);
  9783. }
  9784. }
  9785. }
  9786. }
  9787. void asCCompiler::CompileComparisonOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9788. {
  9789. // Both operands must be of the same type
  9790. // Implicitly convert the operands to a number type
  9791. asCDataType to;
  9792. // If either operand is a non-primitive then use the primitive type
  9793. if( !lctx->type.dataType.IsPrimitive() )
  9794. to.SetTokenType(rctx->type.dataType.GetTokenType());
  9795. else if( !rctx->type.dataType.IsPrimitive() )
  9796. to.SetTokenType(lctx->type.dataType.GetTokenType());
  9797. else if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  9798. to.SetTokenType(ttDouble);
  9799. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  9800. to.SetTokenType(ttFloat);
  9801. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9802. {
  9803. // Convert to int64 if both are signed or if one is non-constant and signed
  9804. if( (lctx->type.dataType.IsIntegerType() && rctx->type.dataType.IsIntegerType()) ||
  9805. (lctx->type.dataType.IsIntegerType() && !lctx->type.isConstant) ||
  9806. (rctx->type.dataType.IsIntegerType() && !rctx->type.isConstant) )
  9807. to.SetTokenType(ttInt64);
  9808. else
  9809. to.SetTokenType(ttUInt64);
  9810. }
  9811. else
  9812. {
  9813. // Convert to int32 if both are signed or if one is non-constant and signed
  9814. if( (lctx->type.dataType.IsIntegerType() && rctx->type.dataType.IsIntegerType()) ||
  9815. (lctx->type.dataType.IsIntegerType() && !lctx->type.isConstant) ||
  9816. (rctx->type.dataType.IsIntegerType() && !rctx->type.isConstant) )
  9817. to.SetTokenType(ttInt);
  9818. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  9819. to.SetTokenType(ttUInt);
  9820. else if( lctx->type.dataType.IsBooleanType() || rctx->type.dataType.IsBooleanType() )
  9821. to.SetTokenType(ttBool);
  9822. }
  9823. // If doing an operation with double constant and float variable, the constant should be converted to float
  9824. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  9825. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  9826. to.SetTokenType(ttFloat);
  9827. asASSERT( to.GetTokenType() != ttUnrecognizedToken );
  9828. // Do we have a mismatch between the sign of the operand?
  9829. bool signMismatch = false;
  9830. for( int n = 0; !signMismatch && n < 2; n++ )
  9831. {
  9832. asSExprContext *op = n ? rctx : lctx;
  9833. if( op->type.dataType.IsUnsignedType() != to.IsUnsignedType() )
  9834. {
  9835. // We have a mismatch, unless the value is a literal constant and the conversion won't affect its value
  9836. signMismatch = true;
  9837. if( op->type.isConstant )
  9838. {
  9839. if( op->type.dataType.GetTokenType() == ttUInt64 || op->type.dataType.GetTokenType() == ttInt64 )
  9840. {
  9841. if( !(op->type.qwordValue & (asQWORD(1)<<63)) )
  9842. signMismatch = false;
  9843. }
  9844. else
  9845. {
  9846. if( !(op->type.dwordValue & (1<<31)) )
  9847. signMismatch = false;
  9848. }
  9849. // It's not necessary to check for floats or double, because if
  9850. // it was then the types for the conversion will never be unsigned
  9851. }
  9852. }
  9853. }
  9854. // Check for signed/unsigned mismatch
  9855. if( signMismatch )
  9856. Warning(TXT_SIGNED_UNSIGNED_MISMATCH, node);
  9857. // Do the actual conversion
  9858. int l = int(reservedVariables.GetLength());
  9859. rctx->bc.GetVarsUsed(reservedVariables);
  9860. if( lctx->type.dataType.IsReference() )
  9861. ConvertToVariable(lctx);
  9862. if( rctx->type.dataType.IsReference() )
  9863. ConvertToVariable(rctx);
  9864. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  9865. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  9866. reservedVariables.SetLength(l);
  9867. // Verify that the conversion was successful
  9868. bool ok = true;
  9869. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  9870. {
  9871. asCString str;
  9872. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9873. Error(str, node);
  9874. ok = false;
  9875. }
  9876. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  9877. {
  9878. asCString str;
  9879. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9880. Error(str, node);
  9881. ok = false;
  9882. }
  9883. if( !ok )
  9884. {
  9885. // It wasn't possible to get two valid operands, so we just return
  9886. // a boolean result and let the compiler continue.
  9887. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  9888. return;
  9889. }
  9890. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  9891. int op = node->tokenType;
  9892. if( !isConstant )
  9893. {
  9894. if( to.IsBooleanType() )
  9895. {
  9896. int op = node->tokenType;
  9897. if( op == ttEqual || op == ttNotEqual )
  9898. {
  9899. // Must convert to temporary variable, because we are changing the value before comparison
  9900. ConvertToTempVariableNotIn(lctx, rctx);
  9901. ConvertToTempVariableNotIn(rctx, lctx);
  9902. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9903. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9904. // Make sure they are equal if not false
  9905. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  9906. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  9907. MergeExprBytecode(ctx, lctx);
  9908. MergeExprBytecode(ctx, rctx);
  9909. ProcessDeferredParams(ctx);
  9910. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  9911. int b = lctx->type.stackOffset;
  9912. int c = rctx->type.stackOffset;
  9913. if( op == ttEqual )
  9914. {
  9915. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  9916. ctx->bc.Instr(asBC_TZ);
  9917. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9918. }
  9919. else if( op == ttNotEqual )
  9920. {
  9921. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  9922. ctx->bc.Instr(asBC_TNZ);
  9923. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9924. }
  9925. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9926. }
  9927. else
  9928. {
  9929. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  9930. Error(TXT_ILLEGAL_OPERATION, node);
  9931. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 0);
  9932. }
  9933. }
  9934. else
  9935. {
  9936. ConvertToVariableNotIn(lctx, rctx);
  9937. ConvertToVariableNotIn(rctx, lctx);
  9938. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9939. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9940. MergeExprBytecode(ctx, lctx);
  9941. MergeExprBytecode(ctx, rctx);
  9942. ProcessDeferredParams(ctx);
  9943. asEBCInstr iCmp = asBC_CMPi, iT = asBC_TZ;
  9944. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9945. iCmp = asBC_CMPi;
  9946. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9947. iCmp = asBC_CMPu;
  9948. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9949. iCmp = asBC_CMPi64;
  9950. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9951. iCmp = asBC_CMPu64;
  9952. else if( lctx->type.dataType.IsFloatType() )
  9953. iCmp = asBC_CMPf;
  9954. else if( lctx->type.dataType.IsDoubleType() )
  9955. iCmp = asBC_CMPd;
  9956. else
  9957. asASSERT(false);
  9958. if( op == ttEqual )
  9959. iT = asBC_TZ;
  9960. else if( op == ttNotEqual )
  9961. iT = asBC_TNZ;
  9962. else if( op == ttLessThan )
  9963. iT = asBC_TS;
  9964. else if( op == ttLessThanOrEqual )
  9965. iT = asBC_TNP;
  9966. else if( op == ttGreaterThan )
  9967. iT = asBC_TP;
  9968. else if( op == ttGreaterThanOrEqual )
  9969. iT = asBC_TNS;
  9970. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  9971. int b = lctx->type.stackOffset;
  9972. int c = rctx->type.stackOffset;
  9973. ctx->bc.InstrW_W(iCmp, b, c);
  9974. ctx->bc.Instr(iT);
  9975. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9976. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9977. }
  9978. }
  9979. else
  9980. {
  9981. if( to.IsBooleanType() )
  9982. {
  9983. int op = node->tokenType;
  9984. if( op == ttEqual || op == ttNotEqual )
  9985. {
  9986. // Make sure they are equal if not false
  9987. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9988. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9989. asDWORD v = 0;
  9990. if( op == ttEqual )
  9991. {
  9992. v = lctx->type.intValue - rctx->type.intValue;
  9993. if( v == 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9994. }
  9995. else if( op == ttNotEqual )
  9996. {
  9997. v = lctx->type.intValue - rctx->type.intValue;
  9998. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9999. }
  10000. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), v);
  10001. }
  10002. else
  10003. {
  10004. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  10005. Error(TXT_ILLEGAL_OPERATION, node);
  10006. }
  10007. }
  10008. else
  10009. {
  10010. int i = 0;
  10011. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10012. {
  10013. int v = lctx->type.intValue - rctx->type.intValue;
  10014. if( v < 0 ) i = -1;
  10015. if( v > 0 ) i = 1;
  10016. }
  10017. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10018. {
  10019. asDWORD v1 = lctx->type.dwordValue;
  10020. asDWORD v2 = rctx->type.dwordValue;
  10021. if( v1 < v2 ) i = -1;
  10022. if( v1 > v2 ) i = 1;
  10023. }
  10024. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  10025. {
  10026. asINT64 v = asINT64(lctx->type.qwordValue) - asINT64(rctx->type.qwordValue);
  10027. if( v < 0 ) i = -1;
  10028. if( v > 0 ) i = 1;
  10029. }
  10030. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  10031. {
  10032. asQWORD v1 = lctx->type.qwordValue;
  10033. asQWORD v2 = rctx->type.qwordValue;
  10034. if( v1 < v2 ) i = -1;
  10035. if( v1 > v2 ) i = 1;
  10036. }
  10037. else if( lctx->type.dataType.IsFloatType() )
  10038. {
  10039. float v = lctx->type.floatValue - rctx->type.floatValue;
  10040. if( v < 0 ) i = -1;
  10041. if( v > 0 ) i = 1;
  10042. }
  10043. else if( lctx->type.dataType.IsDoubleType() )
  10044. {
  10045. double v = lctx->type.doubleValue - rctx->type.doubleValue;
  10046. if( v < 0 ) i = -1;
  10047. if( v > 0 ) i = 1;
  10048. }
  10049. if( op == ttEqual )
  10050. i = (i == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  10051. else if( op == ttNotEqual )
  10052. i = (i != 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  10053. else if( op == ttLessThan )
  10054. i = (i < 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  10055. else if( op == ttLessThanOrEqual )
  10056. i = (i <= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  10057. else if( op == ttGreaterThan )
  10058. i = (i > 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  10059. else if( op == ttGreaterThanOrEqual )
  10060. i = (i >= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  10061. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), i);
  10062. }
  10063. }
  10064. }
  10065. void asCCompiler::PushVariableOnStack(asSExprContext *ctx, bool asReference)
  10066. {
  10067. // Put the result on the stack
  10068. if( asReference )
  10069. {
  10070. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  10071. ctx->type.dataType.MakeReference(true);
  10072. }
  10073. else
  10074. {
  10075. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10076. ctx->bc.InstrSHORT(asBC_PshV4, ctx->type.stackOffset);
  10077. else
  10078. ctx->bc.InstrSHORT(asBC_PshV8, ctx->type.stackOffset);
  10079. }
  10080. }
  10081. void asCCompiler::CompileBooleanOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  10082. {
  10083. // Both operands must be booleans
  10084. asCDataType to;
  10085. to.SetTokenType(ttBool);
  10086. // Do the actual conversion
  10087. int l = int(reservedVariables.GetLength());
  10088. rctx->bc.GetVarsUsed(reservedVariables);
  10089. lctx->bc.GetVarsUsed(reservedVariables);
  10090. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  10091. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  10092. reservedVariables.SetLength(l);
  10093. // Verify that the conversion was successful
  10094. if( !lctx->type.dataType.IsBooleanType() )
  10095. {
  10096. asCString str;
  10097. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), "bool");
  10098. Error(str, node);
  10099. // Force the conversion to allow compilation to proceed
  10100. lctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  10101. }
  10102. if( !rctx->type.dataType.IsBooleanType() )
  10103. {
  10104. asCString str;
  10105. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "bool");
  10106. Error(str, node);
  10107. // Force the conversion to allow compilation to proceed
  10108. rctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  10109. }
  10110. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  10111. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  10112. // What kind of operator is it?
  10113. int op = node->tokenType;
  10114. if( op == ttXor )
  10115. {
  10116. if( !isConstant )
  10117. {
  10118. // Must convert to temporary variable, because we are changing the value before comparison
  10119. ConvertToTempVariableNotIn(lctx, rctx);
  10120. ConvertToTempVariableNotIn(rctx, lctx);
  10121. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  10122. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  10123. // Make sure they are equal if not false
  10124. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  10125. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  10126. MergeExprBytecode(ctx, lctx);
  10127. MergeExprBytecode(ctx, rctx);
  10128. ProcessDeferredParams(ctx);
  10129. int a = AllocateVariable(ctx->type.dataType, true);
  10130. int b = lctx->type.stackOffset;
  10131. int c = rctx->type.stackOffset;
  10132. ctx->bc.InstrW_W_W(asBC_BXOR,a,b,c);
  10133. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  10134. }
  10135. else
  10136. {
  10137. // Make sure they are equal if not false
  10138. #if AS_SIZEOF_BOOL == 1
  10139. if( lctx->type.byteValue != 0 ) lctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  10140. if( rctx->type.byteValue != 0 ) rctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  10141. asBYTE v = 0;
  10142. v = lctx->type.byteValue - rctx->type.byteValue;
  10143. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  10144. ctx->type.isConstant = true;
  10145. ctx->type.byteValue = v;
  10146. #else
  10147. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  10148. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  10149. asDWORD v = 0;
  10150. v = lctx->type.intValue - rctx->type.intValue;
  10151. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  10152. ctx->type.isConstant = true;
  10153. ctx->type.dwordValue = v;
  10154. #endif
  10155. }
  10156. }
  10157. else if( op == ttAnd ||
  10158. op == ttOr )
  10159. {
  10160. if( !isConstant )
  10161. {
  10162. // If or-operator and first value is 1 the second value shouldn't be calculated
  10163. // if and-operator and first value is 0 the second value shouldn't be calculated
  10164. ConvertToVariable(lctx);
  10165. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  10166. MergeExprBytecode(ctx, lctx);
  10167. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  10168. int label1 = nextLabel++;
  10169. int label2 = nextLabel++;
  10170. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  10171. ctx->bc.Instr(asBC_ClrHi);
  10172. if( op == ttAnd )
  10173. {
  10174. ctx->bc.InstrDWORD(asBC_JNZ, label1);
  10175. ctx->bc.InstrW_DW(asBC_SetV4, (asWORD)offset, 0);
  10176. ctx->bc.InstrINT(asBC_JMP, label2);
  10177. }
  10178. else if( op == ttOr )
  10179. {
  10180. ctx->bc.InstrDWORD(asBC_JZ, label1);
  10181. #if AS_SIZEOF_BOOL == 1
  10182. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  10183. #else
  10184. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  10185. #endif
  10186. ctx->bc.InstrINT(asBC_JMP, label2);
  10187. }
  10188. ctx->bc.Label((short)label1);
  10189. ConvertToVariable(rctx);
  10190. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  10191. rctx->bc.InstrW_W(asBC_CpyVtoV4, offset, rctx->type.stackOffset);
  10192. MergeExprBytecode(ctx, rctx);
  10193. ctx->bc.Label((short)label2);
  10194. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), offset, true);
  10195. }
  10196. else
  10197. {
  10198. #if AS_SIZEOF_BOOL == 1
  10199. asBYTE v = 0;
  10200. if( op == ttAnd )
  10201. v = lctx->type.byteValue && rctx->type.byteValue;
  10202. else if( op == ttOr )
  10203. v = lctx->type.byteValue || rctx->type.byteValue;
  10204. // Remember the result
  10205. ctx->type.isConstant = true;
  10206. ctx->type.byteValue = v;
  10207. #else
  10208. asDWORD v = 0;
  10209. if( op == ttAnd )
  10210. v = lctx->type.dwordValue && rctx->type.dwordValue;
  10211. else if( op == ttOr )
  10212. v = lctx->type.dwordValue || rctx->type.dwordValue;
  10213. // Remember the result
  10214. ctx->type.isConstant = true;
  10215. ctx->type.dwordValue = v;
  10216. #endif
  10217. }
  10218. }
  10219. }
  10220. void asCCompiler::CompileOperatorOnHandles(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  10221. {
  10222. // Process the property accessor as get
  10223. ProcessPropertyGetAccessor(lctx, node);
  10224. ProcessPropertyGetAccessor(rctx, node);
  10225. DetermineSingleFunc(lctx, node);
  10226. DetermineSingleFunc(rctx, node);
  10227. // Make sure lctx doesn't end up with a variable used in rctx
  10228. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  10229. {
  10230. asCArray<int> vars;
  10231. rctx->bc.GetVarsUsed(vars);
  10232. int offset = AllocateVariable(lctx->type.dataType, true);
  10233. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  10234. ReleaseTemporaryVariable(offset, 0);
  10235. }
  10236. // Warn if not both operands are explicit handles
  10237. if( (node->tokenType == ttEqual || node->tokenType == ttNotEqual) &&
  10238. ((!lctx->type.isExplicitHandle && !(lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE))) ||
  10239. (!rctx->type.isExplicitHandle && !(rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE)))) )
  10240. {
  10241. Warning(TXT_HANDLE_COMPARISON, node);
  10242. }
  10243. // If one of the operands is a value type used as handle, we should look for the opEquals method
  10244. if( ((lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) ||
  10245. (rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE))) &&
  10246. (node->tokenType == ttEqual || node->tokenType == ttIs ||
  10247. node->tokenType == ttNotEqual || node->tokenType == ttNotIs) )
  10248. {
  10249. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  10250. // Find the matching opEquals method
  10251. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  10252. if( r == 0 )
  10253. {
  10254. // Try again by switching the order of the operands
  10255. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  10256. }
  10257. if( r == 1 )
  10258. {
  10259. if( node->tokenType == ttNotEqual || node->tokenType == ttNotIs )
  10260. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  10261. // Success, don't continue
  10262. return;
  10263. }
  10264. else if( r == 0 )
  10265. {
  10266. // Couldn't find opEquals method
  10267. Error(TXT_NO_APPROPRIATE_OPEQUALS, node);
  10268. }
  10269. // Compiler error, don't continue
  10270. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  10271. return;
  10272. }
  10273. // Implicitly convert null to the other type
  10274. asCDataType to;
  10275. if( lctx->type.IsNullConstant() )
  10276. to = rctx->type.dataType;
  10277. else if( rctx->type.IsNullConstant() )
  10278. to = lctx->type.dataType;
  10279. else
  10280. {
  10281. // TODO: Use the common base type
  10282. to = lctx->type.dataType;
  10283. }
  10284. // Need to pop the value if it is a null constant
  10285. if( lctx->type.IsNullConstant() )
  10286. lctx->bc.Instr(asBC_PopPtr);
  10287. if( rctx->type.IsNullConstant() )
  10288. rctx->bc.Instr(asBC_PopPtr);
  10289. // Convert both sides to explicit handles
  10290. to.MakeHandle(true);
  10291. to.MakeReference(false);
  10292. if( !to.IsObjectHandle() )
  10293. {
  10294. // Compiler error, don't continue
  10295. Error(TXT_OPERANDS_MUST_BE_HANDLES, node);
  10296. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  10297. return;
  10298. }
  10299. // Do the conversion
  10300. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  10301. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  10302. // Both operands must be of the same type
  10303. // Verify that the conversion was successful
  10304. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  10305. {
  10306. asCString str;
  10307. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  10308. Error(str, node);
  10309. }
  10310. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  10311. {
  10312. asCString str;
  10313. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  10314. Error(str, node);
  10315. }
  10316. // Make sure it really is handles that are being compared
  10317. if( !lctx->type.dataType.IsObjectHandle() )
  10318. {
  10319. Error(TXT_OPERANDS_MUST_BE_HANDLES, node);
  10320. }
  10321. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  10322. int op = node->tokenType;
  10323. if( op == ttEqual || op == ttNotEqual || op == ttIs || op == ttNotIs )
  10324. {
  10325. // If the object handle already is in a variable we must manually pop it from the stack
  10326. if( lctx->type.isVariable )
  10327. lctx->bc.Instr(asBC_PopPtr);
  10328. if( rctx->type.isVariable )
  10329. rctx->bc.Instr(asBC_PopPtr);
  10330. // TODO: runtime optimize: don't do REFCPY
  10331. ConvertToVariableNotIn(lctx, rctx);
  10332. ConvertToVariable(rctx);
  10333. MergeExprBytecode(ctx, lctx);
  10334. MergeExprBytecode(ctx, rctx);
  10335. int a = AllocateVariable(ctx->type.dataType, true);
  10336. int b = lctx->type.stackOffset;
  10337. int c = rctx->type.stackOffset;
  10338. ctx->bc.InstrW_W(asBC_CmpPtr, b, c);
  10339. if( op == ttEqual || op == ttIs )
  10340. ctx->bc.Instr(asBC_TZ);
  10341. else if( op == ttNotEqual || op == ttNotIs )
  10342. ctx->bc.Instr(asBC_TNZ);
  10343. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  10344. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  10345. ReleaseTemporaryVariable(lctx->type, &ctx->bc);
  10346. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  10347. ProcessDeferredParams(ctx);
  10348. }
  10349. else
  10350. {
  10351. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  10352. Error(TXT_ILLEGAL_OPERATION, node);
  10353. }
  10354. }
  10355. void asCCompiler::PerformFunctionCall(int funcId, asSExprContext *ctx, bool isConstructor, asCArray<asSExprContext*> *args, asCObjectType *objType, bool useVariable, int varOffset, int funcPtrVar)
  10356. {
  10357. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  10358. // A shared object may not call non-shared functions
  10359. if( outFunc->IsShared() && !descr->IsShared() )
  10360. {
  10361. asCString msg;
  10362. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, descr->GetDeclarationStr().AddressOf());
  10363. Error(msg, ctx->exprNode);
  10364. }
  10365. // Check if the function is private
  10366. if( descr->isPrivate && descr->GetObjectType() != outFunc->GetObjectType() )
  10367. {
  10368. asCString msg;
  10369. msg.Format(TXT_PRIVATE_METHOD_CALL_s, descr->GetDeclarationStr().AddressOf());
  10370. Error(msg, ctx->exprNode);
  10371. }
  10372. int argSize = descr->GetSpaceNeededForArguments();
  10373. if( descr->objectType && descr->returnType.IsReference() &&
  10374. !(ctx->type.isVariable || ctx->type.isTemporary) &&
  10375. (ctx->type.dataType.IsObjectHandle() || ctx->type.dataType.SupportHandles()) &&
  10376. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_SCOPED) &&
  10377. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_ASHANDLE) )
  10378. {
  10379. // The class method we're calling is returning a reference, which may be to a member of the object.
  10380. // In order to guarantee the lifetime of the reference, we must hold a local reference to the object.
  10381. // TODO: runtime optimize: This can be avoided for local variables (non-handles) as they have a well defined life time
  10382. int tempRef = AllocateVariable(ctx->type.dataType, true);
  10383. ctx->bc.InstrSHORT(asBC_PSF, (short)tempRef);
  10384. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  10385. // Add the release of this reference, as a deferred expression
  10386. asSDeferredParam deferred;
  10387. deferred.origExpr = 0;
  10388. deferred.argInOutFlags = asTM_INREF;
  10389. deferred.argNode = 0;
  10390. deferred.argType.SetVariable(ctx->type.dataType, tempRef, true);
  10391. ctx->deferredParams.PushLast(deferred);
  10392. // Forget the current type
  10393. ctx->type.SetDummy();
  10394. }
  10395. if( isConstructor )
  10396. {
  10397. // Sometimes the value types are allocated on the heap,
  10398. // which is when this way of constructing them is used.
  10399. asASSERT(useVariable == false);
  10400. ctx->bc.Alloc(asBC_ALLOC, objType, descr->id, argSize+AS_PTR_SIZE);
  10401. // The instruction has already moved the returned object to the variable
  10402. ctx->type.Set(asCDataType::CreatePrimitive(ttVoid, false));
  10403. ctx->type.isLValue = false;
  10404. // Clean up arguments
  10405. if( args )
  10406. AfterFunctionCall(funcId, *args, ctx, false);
  10407. ProcessDeferredParams(ctx);
  10408. return;
  10409. }
  10410. else
  10411. {
  10412. if( descr->objectType )
  10413. argSize += AS_PTR_SIZE;
  10414. // If the function returns an object by value the address of the location
  10415. // where the value should be stored is passed as an argument too
  10416. if( descr->DoesReturnOnStack() )
  10417. {
  10418. argSize += AS_PTR_SIZE;
  10419. }
  10420. // TODO: runtime optimize: If it is known that a class method cannot be overridden the call
  10421. // should be made with asBC_CALL as it is faster. Examples where this
  10422. // is known is for example finalled methods where the class doesn't derive
  10423. // from any other, or even non-finalled methods but where it is known
  10424. // at compile time the true type of the object. The first should be
  10425. // quite easy to determine, but the latter will be quite complex and possibly
  10426. // not worth it.
  10427. if( descr->funcType == asFUNC_IMPORTED )
  10428. ctx->bc.Call(asBC_CALLBND , descr->id, argSize);
  10429. // TODO: Maybe we need two different byte codes
  10430. else if( descr->funcType == asFUNC_INTERFACE || descr->funcType == asFUNC_VIRTUAL )
  10431. ctx->bc.Call(asBC_CALLINTF, descr->id, argSize);
  10432. else if( descr->funcType == asFUNC_SCRIPT )
  10433. ctx->bc.Call(asBC_CALL , descr->id, argSize);
  10434. else if( descr->funcType == asFUNC_SYSTEM )
  10435. ctx->bc.Call(asBC_CALLSYS , descr->id, argSize);
  10436. else if( descr->funcType == asFUNC_FUNCDEF )
  10437. ctx->bc.CallPtr(asBC_CallPtr, funcPtrVar, argSize);
  10438. }
  10439. if( descr->returnType.IsObject() && !descr->returnType.IsReference() )
  10440. {
  10441. int returnOffset = 0;
  10442. if( descr->DoesReturnOnStack() )
  10443. {
  10444. asASSERT( useVariable );
  10445. // The variable was allocated before the function was called
  10446. returnOffset = varOffset;
  10447. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  10448. // The variable was initialized by the function, so we need to mark it as initialized here
  10449. ctx->bc.ObjInfo(varOffset, asOBJ_INIT);
  10450. }
  10451. else
  10452. {
  10453. if( useVariable )
  10454. {
  10455. // Use the given variable
  10456. returnOffset = varOffset;
  10457. ctx->type.SetVariable(descr->returnType, returnOffset, false);
  10458. }
  10459. else
  10460. {
  10461. // Allocate a temporary variable for the returned object
  10462. // The returned object will actually be allocated on the heap, so
  10463. // we must force the allocation of the variable to do the same
  10464. returnOffset = AllocateVariable(descr->returnType, true, !descr->returnType.IsObjectHandle());
  10465. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  10466. }
  10467. // Move the pointer from the object register to the temporary variable
  10468. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  10469. }
  10470. ctx->type.dataType.MakeReference(IsVariableOnHeap(returnOffset));
  10471. ctx->type.isLValue = false; // It is a reference, but not an lvalue
  10472. // Clean up arguments
  10473. if( args )
  10474. AfterFunctionCall(funcId, *args, ctx, false);
  10475. ProcessDeferredParams(ctx);
  10476. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  10477. }
  10478. else if( descr->returnType.IsReference() )
  10479. {
  10480. asASSERT(useVariable == false);
  10481. // We cannot clean up the arguments yet, because the
  10482. // reference might be pointing to one of them.
  10483. if( args )
  10484. AfterFunctionCall(funcId, *args, ctx, true);
  10485. // Do not process the output parameters yet, because it
  10486. // might invalidate the returned reference
  10487. // If the context holds a variable that needs cleanup
  10488. // store it as a deferred parameter so it will be cleaned up
  10489. // afterwards.
  10490. if( ctx->type.isTemporary )
  10491. {
  10492. asSDeferredParam defer;
  10493. defer.argNode = 0;
  10494. defer.argType = ctx->type;
  10495. defer.argInOutFlags = asTM_INOUTREF;
  10496. defer.origExpr = 0;
  10497. ctx->deferredParams.PushLast(defer);
  10498. }
  10499. ctx->type.Set(descr->returnType);
  10500. if( !descr->returnType.IsPrimitive() )
  10501. {
  10502. ctx->bc.Instr(asBC_PshRPtr);
  10503. if( descr->returnType.IsObject() &&
  10504. !descr->returnType.IsObjectHandle() )
  10505. {
  10506. // We are getting the pointer to the object
  10507. // not a pointer to a object variable
  10508. ctx->type.dataType.MakeReference(false);
  10509. }
  10510. }
  10511. // A returned reference can be used as lvalue
  10512. ctx->type.isLValue = true;
  10513. }
  10514. else
  10515. {
  10516. asASSERT(useVariable == false);
  10517. if( descr->returnType.GetSizeInMemoryBytes() )
  10518. {
  10519. // Allocate a temporary variable to hold the value, but make sure
  10520. // the temporary variable isn't used in any of the deferred arguments
  10521. int l = int(reservedVariables.GetLength());
  10522. for( asUINT n = 0; args && n < args->GetLength(); n++ )
  10523. {
  10524. asSExprContext *expr = (*args)[n]->origExpr;
  10525. if( expr )
  10526. expr->bc.GetVarsUsed(reservedVariables);
  10527. }
  10528. int offset = AllocateVariable(descr->returnType, true);
  10529. reservedVariables.SetLength(l);
  10530. ctx->type.SetVariable(descr->returnType, offset, true);
  10531. // Move the value from the return register to the variable
  10532. if( descr->returnType.GetSizeOnStackDWords() == 1 )
  10533. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)offset);
  10534. else if( descr->returnType.GetSizeOnStackDWords() == 2 )
  10535. ctx->bc.InstrSHORT(asBC_CpyRtoV8, (short)offset);
  10536. }
  10537. else
  10538. ctx->type.Set(descr->returnType);
  10539. ctx->type.isLValue = false;
  10540. // Clean up arguments
  10541. if( args )
  10542. AfterFunctionCall(funcId, *args, ctx, false);
  10543. ProcessDeferredParams(ctx);
  10544. }
  10545. }
  10546. // This only merges the bytecode, but doesn't modify the type of the final context
  10547. void asCCompiler::MergeExprBytecode(asSExprContext *before, asSExprContext *after)
  10548. {
  10549. before->bc.AddCode(&after->bc);
  10550. for( asUINT n = 0; n < after->deferredParams.GetLength(); n++ )
  10551. {
  10552. before->deferredParams.PushLast(after->deferredParams[n]);
  10553. after->deferredParams[n].origExpr = 0;
  10554. }
  10555. after->deferredParams.SetLength(0);
  10556. }
  10557. // This merges both bytecode and the type of the final context
  10558. void asCCompiler::MergeExprBytecodeAndType(asSExprContext *before, asSExprContext *after)
  10559. {
  10560. MergeExprBytecode(before, after);
  10561. before->type = after->type;
  10562. before->property_get = after->property_get;
  10563. before->property_set = after->property_set;
  10564. before->property_const = after->property_const;
  10565. before->property_handle = after->property_handle;
  10566. before->property_ref = after->property_ref;
  10567. before->property_arg = after->property_arg;
  10568. before->exprNode = after->exprNode;
  10569. before->methodName = after->methodName;
  10570. after->property_arg = 0;
  10571. // Do not copy the origExpr member
  10572. }
  10573. void asCCompiler::FilterConst(asCArray<int> &funcs, bool removeConst)
  10574. {
  10575. if( funcs.GetLength() == 0 ) return;
  10576. // This is only done for object methods
  10577. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[0]);
  10578. if( desc->objectType == 0 ) return;
  10579. // Check if there are any non-const matches
  10580. asUINT n;
  10581. bool foundNonConst = false;
  10582. for( n = 0; n < funcs.GetLength(); n++ )
  10583. {
  10584. desc = builder->GetFunctionDescription(funcs[n]);
  10585. if( desc->isReadOnly != removeConst )
  10586. {
  10587. foundNonConst = true;
  10588. break;
  10589. }
  10590. }
  10591. if( foundNonConst )
  10592. {
  10593. // Remove all const methods
  10594. for( n = 0; n < funcs.GetLength(); n++ )
  10595. {
  10596. desc = builder->GetFunctionDescription(funcs[n]);
  10597. if( desc->isReadOnly == removeConst )
  10598. {
  10599. if( n == funcs.GetLength() - 1 )
  10600. funcs.PopLast();
  10601. else
  10602. funcs[n] = funcs.PopLast();
  10603. n--;
  10604. }
  10605. }
  10606. }
  10607. }
  10608. END_AS_NAMESPACE
  10609. #endif // AS_NO_COMPILER