as_compiler.cpp 354 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2012 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. // Modified by Lasse Öörni for Urho3D
  24. //
  25. // as_compiler.cpp
  26. //
  27. // The class that does the actual compilation of the functions
  28. //
  29. #include <math.h> // fmodf()
  30. #include "as_config.h"
  31. #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. BEGIN_AS_NAMESPACE
  39. //
  40. // The calling convention rules for script functions:
  41. // - 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
  42. // - 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
  43. // - The object pointer is always passed as the first argument, position 0
  44. // - 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
  45. //
  46. // TODO: I must correct the interpretation of a references to objects in the compiler.
  47. // A reference should mean that a pointer to the object is on the stack.
  48. // No expression should end up as non-references to objects, as the actual object is
  49. // never put on the stack.
  50. // Local variables are declared as non-references, but the expression should be a reference to the variable.
  51. // Function parameters of called functions can also be non-references, but in that case it means the
  52. // object will be passed by value (currently on the heap, which will be moved to the application stack).
  53. //
  54. // The compiler shouldn't use the asCDataType::IsReference. The datatype should always be stored as non-references.
  55. // Instead the compiler should keep track of references in TypeInfo, where it should also state how the reference
  56. // is currently stored, i.e. in variable, in register, on stack, etc.
  57. asCCompiler::asCCompiler(asCScriptEngine *engine) : byteCode(engine)
  58. {
  59. builder = 0;
  60. script = 0;
  61. variables = 0;
  62. isProcessingDeferredParams = false;
  63. isCompilingDefaultArg = false;
  64. noCodeOutput = 0;
  65. }
  66. asCCompiler::~asCCompiler()
  67. {
  68. while( variables )
  69. {
  70. asCVariableScope *var = variables;
  71. variables = variables->parent;
  72. asDELETE(var,asCVariableScope);
  73. }
  74. }
  75. void asCCompiler::Reset(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  76. {
  77. this->builder = builder;
  78. this->engine = builder->engine;
  79. this->script = script;
  80. this->outFunc = outFunc;
  81. hasCompileErrors = false;
  82. m_isConstructor = false;
  83. m_isConstructorCalled = false;
  84. nextLabel = 0;
  85. breakLabels.SetLength(0);
  86. continueLabels.SetLength(0);
  87. byteCode.ClearAll();
  88. }
  89. int asCCompiler::CompileDefaultConstructor(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, asCScriptFunction *outFunc)
  90. {
  91. Reset(builder, script, outFunc);
  92. // Make sure all the class members can be initialized with default constructors
  93. for( asUINT n = 0; n < outFunc->objectType->properties.GetLength(); n++ )
  94. {
  95. asCDataType &dt = outFunc->objectType->properties[n]->type;
  96. if( dt.IsObject() && !dt.IsObjectHandle() &&
  97. (((dt.GetObjectType()->flags & asOBJ_REF) && dt.GetObjectType()->beh.factory == 0) ||
  98. ((dt.GetObjectType()->flags & asOBJ_VALUE) && !(dt.GetObjectType()->flags & asOBJ_POD) && dt.GetObjectType()->beh.construct == 0)) )
  99. {
  100. asCString str;
  101. if( dt.GetFuncDef() )
  102. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetFuncDef()->GetName());
  103. else
  104. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetObjectType()->GetName());
  105. Error(str.AddressOf(), node);
  106. }
  107. }
  108. // If the class is derived from another, then the base class' default constructor must be called
  109. if( outFunc->objectType->derivedFrom )
  110. {
  111. // Call the base class' default constructor
  112. byteCode.InstrSHORT(asBC_PSF, 0);
  113. byteCode.Instr(asBC_RDSPtr);
  114. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  115. }
  116. // Pop the object pointer from the stack
  117. byteCode.Ret(AS_PTR_SIZE);
  118. FinalizeFunction();
  119. #ifdef AS_DEBUG
  120. // DEBUG: output byte code
  121. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + "__dc.txt").AddressOf(), engine, outFunc);
  122. #endif
  123. return 0;
  124. }
  125. int asCCompiler::CompileFactory(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  126. {
  127. Reset(builder, script, outFunc);
  128. unsigned int n;
  129. // Find the corresponding constructor
  130. asCDataType dt = asCDataType::CreateObject(outFunc->returnType.GetObjectType(), false);
  131. int constructor = 0;
  132. for( n = 0; n < dt.GetBehaviour()->factories.GetLength(); n++ )
  133. {
  134. if( dt.GetBehaviour()->factories[n] == outFunc->id )
  135. {
  136. constructor = dt.GetBehaviour()->constructors[n];
  137. break;
  138. }
  139. }
  140. // Allocate the class and instanciate it with the constructor
  141. int varOffset = AllocateVariable(dt, true);
  142. outFunc->variableSpace = AS_PTR_SIZE;
  143. byteCode.InstrSHORT(asBC_PSF, (short)varOffset);
  144. // Copy all arguments to the top of the stack
  145. // TODO: runtime optimize: Might be interesting to have a specific instruction for copying all arguments
  146. int offset = (int)outFunc->GetSpaceNeededForArguments();
  147. for( int a = int(outFunc->parameterTypes.GetLength()) - 1; a >= 0; a-- )
  148. {
  149. if( !outFunc->parameterTypes[a].IsPrimitive() ||
  150. outFunc->parameterTypes[a].IsReference() )
  151. {
  152. offset -= AS_PTR_SIZE;
  153. byteCode.InstrSHORT(asBC_PshVPtr, short(-offset));
  154. }
  155. else
  156. {
  157. if( outFunc->parameterTypes[a].GetSizeOnStackDWords() == 2 )
  158. {
  159. offset -= 2;
  160. byteCode.InstrSHORT(asBC_PshV8, short(-offset));
  161. }
  162. else
  163. {
  164. offset -= 1;
  165. byteCode.InstrSHORT(asBC_PshV4, short(-offset));
  166. }
  167. }
  168. }
  169. int argDwords = (int)outFunc->GetSpaceNeededForArguments();
  170. byteCode.Alloc(asBC_ALLOC, dt.GetObjectType(), constructor, argDwords + AS_PTR_SIZE);
  171. // Return a handle to the newly created object
  172. byteCode.InstrSHORT(asBC_LOADOBJ, (short)varOffset);
  173. byteCode.Ret(argDwords);
  174. FinalizeFunction();
  175. // Tell the virtual machine not to clean up parameters on exception
  176. outFunc->dontCleanUpOnException = true;
  177. /*
  178. #ifdef AS_DEBUG
  179. // DEBUG: output byte code
  180. asCString args;
  181. args.Format("%d", outFunc->parameterTypes.GetLength());
  182. byteCode.DebugOutput(("__" + outFunc->name + "__factory" + args + ".txt").AddressOf(), engine);
  183. #endif
  184. */
  185. return 0;
  186. }
  187. void asCCompiler::FinalizeFunction()
  188. {
  189. asUINT n;
  190. // Tell the bytecode which variables are temporary
  191. for( n = 0; n < variableIsTemporary.GetLength(); n++ )
  192. {
  193. if( variableIsTemporary[n] )
  194. byteCode.DefineTemporaryVariable(GetVariableOffset(n));
  195. }
  196. // Finalize the bytecode
  197. byteCode.Finalize();
  198. byteCode.ExtractObjectVariableInfo(outFunc);
  199. // Compile the list of object variables for the exception handler
  200. // Start with the variables allocated on the heap, and then the ones allocated on the stack
  201. for( n = 0; n < variableAllocations.GetLength(); n++ )
  202. {
  203. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  204. {
  205. if( variableIsOnHeap[n] )
  206. {
  207. outFunc->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  208. outFunc->funcVariableTypes.PushLast(variableAllocations[n].GetFuncDef());
  209. outFunc->objVariablePos.PushLast(GetVariableOffset(n));
  210. }
  211. }
  212. }
  213. outFunc->objVariablesOnHeap = outFunc->objVariablePos.GetLength();
  214. for( n = 0; n < variableAllocations.GetLength(); n++ )
  215. {
  216. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  217. {
  218. if( !variableIsOnHeap[n] )
  219. {
  220. outFunc->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  221. outFunc->funcVariableTypes.PushLast(variableAllocations[n].GetFuncDef());
  222. outFunc->objVariablePos.PushLast(GetVariableOffset(n));
  223. }
  224. }
  225. }
  226. // Copy byte code to the function
  227. outFunc->byteCode.SetLength(byteCode.GetSize());
  228. byteCode.Output(outFunc->byteCode.AddressOf());
  229. outFunc->AddReferences();
  230. outFunc->stackNeeded = byteCode.largestStackUsed + outFunc->variableSpace;
  231. outFunc->lineNumbers = byteCode.lineNumbers;
  232. }
  233. // Entry
  234. int asCCompiler::CompileFunction(asCBuilder *builder, asCScriptCode *script, sExplicitSignature *signature, asCScriptNode *func, asCScriptFunction *outFunc)
  235. {
  236. // TODO: The compiler should take the return type and parameter types from the
  237. // outFunc, instead of interpreting the script nodes again. The builder
  238. // must pass the list of parameter names. Making this change we can
  239. // eliminate large parts of this function and the sExplicitSignature structure
  240. Reset(builder, script, outFunc);
  241. int buildErrors = builder->numErrors;
  242. int stackPos = 0;
  243. if( outFunc->objectType )
  244. stackPos = -AS_PTR_SIZE; // The first parameter is the pointer to the object
  245. // Reserve a label for the cleanup code
  246. nextLabel++;
  247. // Add the first variable scope, which the parameters and
  248. // variables declared in the outermost statement block is
  249. // part of.
  250. AddVariableScope();
  251. asCScriptNode *node;
  252. bool isDestructor = false;
  253. asCDataType returnType;
  254. if( !signature )
  255. {
  256. node = func->firstChild;
  257. if( outFunc->objectType )
  258. {
  259. // Skip the private keyword if it is there
  260. if( node->nodeType == snUndefined && node->tokenType == ttPrivate )
  261. node = node->next;
  262. }
  263. else if( outFunc->IsShared() )
  264. {
  265. // Skip the shared keyword
  266. asASSERT( node->nodeType == snIdentifier );
  267. node = node->next;
  268. }
  269. //----------------------------------------------
  270. // Examine return type
  271. if( node->nodeType == snDataType )
  272. {
  273. // TODO: namespace: Use correct implicit namespace from function
  274. returnType = builder->CreateDataTypeFromNode(node, script, "");
  275. returnType = builder->ModifyDataTypeFromNode(returnType, node->next, script, 0, 0);
  276. // Make sure the return type is instanciable or is void
  277. if( !returnType.CanBeInstanciated() &&
  278. returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  279. {
  280. asCString str;
  281. str.Format(TXT_DATA_TYPE_CANT_BE_s, returnType.Format().AddressOf());
  282. Error(str.AddressOf(), func->firstChild);
  283. }
  284. }
  285. else
  286. {
  287. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  288. if( node->tokenType == ttBitNot )
  289. isDestructor = true;
  290. else
  291. m_isConstructor = true;
  292. }
  293. }
  294. else
  295. {
  296. node = func;
  297. returnType = signature->returnType;
  298. }
  299. // If the return type is a value type returned by value the address of the
  300. // location where the value will be stored is pushed on the stack before
  301. // the arguments
  302. if( !(isDestructor || m_isConstructor) && outFunc->DoesReturnOnStack() )
  303. stackPos -= AS_PTR_SIZE;
  304. asCVariableScope vs(0);
  305. if( !signature )
  306. {
  307. //----------------------------------------------
  308. // Declare parameters
  309. // Find first parameter
  310. while( node && node->nodeType != snParameterList )
  311. node = node->next;
  312. // Register parameters from last to first, otherwise they will be destroyed in the wrong order
  313. if( node ) node = node->firstChild;
  314. while( node )
  315. {
  316. // Get the parameter type
  317. // TODO: namespace: Use correct implicit namespace from function
  318. asCDataType type = builder->CreateDataTypeFromNode(node, script, "");
  319. asETypeModifiers inoutFlag = asTM_NONE;
  320. type = builder->ModifyDataTypeFromNode(type, node->next, script, &inoutFlag, 0);
  321. // Is the data type allowed?
  322. if( (type.IsReference() && inoutFlag != asTM_INOUTREF && !type.CanBeInstanciated()) ||
  323. (!type.IsReference() && !type.CanBeInstanciated()) )
  324. {
  325. asCString parm = type.Format();
  326. if( inoutFlag == asTM_INREF )
  327. parm += "in";
  328. else if( inoutFlag == asTM_OUTREF )
  329. parm += "out";
  330. asCString str;
  331. str.Format(TXT_PARAMETER_CANT_BE_s, parm.AddressOf());
  332. Error(str.AddressOf(), node);
  333. }
  334. // If the parameter has a name then declare it as variable
  335. node = node->next->next;
  336. if( node && node->nodeType == snIdentifier )
  337. {
  338. asCString name(&script->code[node->tokenPos], node->tokenLength);
  339. if( vs.DeclareVariable(name.AddressOf(), type, stackPos, true) < 0 )
  340. Error(TXT_PARAMETER_ALREADY_DECLARED, node);
  341. // Add marker for variable declaration
  342. byteCode.VarDecl((int)outFunc->variables.GetLength());
  343. outFunc->AddVariable(name, type, stackPos);
  344. node = node->next;
  345. // Skip the default arg
  346. if( node && node->nodeType == snExpression )
  347. node = node->next;
  348. }
  349. else
  350. vs.DeclareVariable("", type, stackPos, true);
  351. // Move to next parameter
  352. stackPos -= type.GetSizeOnStackDWords();
  353. }
  354. }
  355. else
  356. {
  357. asCArray<asCDataType> &args = signature->argTypes;
  358. asCArray<asETypeModifiers> &inoutFlags = signature->argModifiers;
  359. asCArray<asCString> &argNames = signature->argNames;
  360. asASSERT(args.GetLength() == argNames.GetLength());
  361. for( int k = 0; k < (int)args.GetLength(); k++ )
  362. {
  363. asCDataType type = args[k];
  364. asETypeModifiers inoutFlag = inoutFlags[k];
  365. if( (type.IsReference() && inoutFlag != asTM_INOUTREF && !type.CanBeInstanciated()) ||
  366. (!type.IsReference() && !type.CanBeInstanciated()) )
  367. {
  368. asCString str;
  369. str.Format(TXT_PARAMETER_CANT_BE_s, type.Format().AddressOf());
  370. Error(str.AddressOf(), node);
  371. }
  372. if( 0 != argNames[k].Compare("") )
  373. {
  374. if( vs.DeclareVariable(argNames[k].AddressOf(), type, stackPos, true) < 0 )
  375. Error(TXT_PARAMETER_ALREADY_DECLARED, node);
  376. // Add marker for variable declaration
  377. byteCode.VarDecl((int)outFunc->variables.GetLength());
  378. outFunc->AddVariable(argNames[k], type, stackPos);
  379. }
  380. else
  381. vs.DeclareVariable("", type, stackPos, true);
  382. // Move to next parameter
  383. stackPos -= type.GetSizeOnStackDWords();
  384. }
  385. }
  386. int n;
  387. for( n = (int)vs.variables.GetLength() - 1; n >= 0; n-- )
  388. {
  389. variables->DeclareVariable(vs.variables[n]->name.AddressOf(), vs.variables[n]->type, vs.variables[n]->stackOffset, vs.variables[n]->onHeap);
  390. }
  391. // Is the return type allowed?
  392. if( (returnType.GetSizeOnStackDWords() == 0 && returnType != asCDataType::CreatePrimitive(ttVoid, false)) ||
  393. (returnType.IsReference() && !returnType.CanBeInstanciated()) )
  394. {
  395. asCString str;
  396. str.Format(TXT_RETURN_CANT_BE_s, returnType.Format().AddressOf());
  397. Error(str.AddressOf(), func);
  398. }
  399. variables->DeclareVariable("return", returnType, stackPos, true);
  400. //--------------------------------------------
  401. // Compile the statement block
  402. // We need to parse the statement block now
  403. asCScriptNode *blockBegin;
  404. if( !signature )
  405. blockBegin = func->lastChild;
  406. else
  407. blockBegin = func;
  408. // TODO: memory: We can parse the statement block one statement at a time, thus save even more memory
  409. asCParser parser(builder);
  410. int r = parser.ParseStatementBlock(script, blockBegin);
  411. if( r < 0 ) return -1;
  412. asCScriptNode *block = parser.GetScriptNode();
  413. bool hasReturn;
  414. asCByteCode bc(engine);
  415. LineInstr(&bc, blockBegin->tokenPos);
  416. CompileStatementBlock(block, false, &hasReturn, &bc);
  417. LineInstr(&bc, blockBegin->tokenPos + blockBegin->tokenLength);
  418. // Make sure there is a return in all paths (if not return type is void)
  419. if( returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  420. {
  421. if( hasReturn == false )
  422. Error(TXT_NOT_ALL_PATHS_RETURN, blockBegin);
  423. }
  424. //------------------------------------------------
  425. // Concatenate the bytecode
  426. // Insert a JitEntry at the start of the function for JIT compilers
  427. byteCode.InstrPTR(asBC_JitEntry, 0);
  428. // Count total variable size
  429. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  430. outFunc->variableSpace = varSize;
  431. if( outFunc->objectType )
  432. {
  433. // Call the base class' default constructor unless called manually in the code
  434. if( m_isConstructor && !m_isConstructorCalled && outFunc->objectType->derivedFrom )
  435. {
  436. if( outFunc->objectType->derivedFrom->beh.construct )
  437. {
  438. byteCode.InstrSHORT(asBC_PSF, 0);
  439. byteCode.Instr(asBC_RDSPtr);
  440. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  441. }
  442. else
  443. {
  444. Error(TEXT_BASE_DOESNT_HAVE_DEF_CONSTR, blockBegin);
  445. }
  446. }
  447. // Increase the reference for the object pointer, so that it is guaranteed to live during the entire call
  448. if( !m_isConstructor && !outFunc->returnType.IsReference() )
  449. {
  450. // TODO: runtime optimize: If the function is trivial, i.e. doesn't access any outside functions,
  451. // then this is not necessary. If I implement this, then the function needs
  452. // to set a flag so the exception handler doesn't try to release the handle.
  453. // It is not necessary to do this for constructors, as they have no outside references that can be released anyway
  454. // It is not necessary to do this for methods that return references, as the caller is guaranteed to hold a reference to the object
  455. byteCode.InstrSHORT(asBC_PSF, 0);
  456. byteCode.Instr(asBC_RDSPtr);
  457. byteCode.Call(asBC_CALLSYS, outFunc->objectType->beh.addref, AS_PTR_SIZE);
  458. }
  459. }
  460. // Add the code for the statement block
  461. byteCode.AddCode(&bc);
  462. // Deallocate all local variables
  463. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  464. {
  465. sVariable *v = variables->variables[n];
  466. if( v->stackOffset > 0 )
  467. {
  468. // Call variables destructors
  469. if( v->name != "return" && v->name != "return address" )
  470. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  471. DeallocateVariable(v->stackOffset);
  472. }
  473. }
  474. // This is the label that return statements jump to
  475. // in order to exit the function
  476. byteCode.Label(0);
  477. // Call destructors for function parameters
  478. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  479. {
  480. sVariable *v = variables->variables[n];
  481. if( v->stackOffset <= 0 )
  482. {
  483. // Call variable destructors here, for variables not yet destroyed
  484. if( v->name != "return" && v->name != "return address" )
  485. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  486. }
  487. // Do not deallocate parameters
  488. }
  489. // Release the object pointer again
  490. if( outFunc->objectType && !m_isConstructor && !outFunc->returnType.IsReference() )
  491. {
  492. byteCode.InstrW_PTR(asBC_FREE, 0, outFunc->objectType);
  493. }
  494. // If there are compile errors, there is no reason to build the final code
  495. if( hasCompileErrors || builder->numErrors != buildErrors )
  496. return -1;
  497. // At this point there should be no variables allocated
  498. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  499. // Remove the variable scope
  500. RemoveVariableScope();
  501. // This POP is not necessary as the return will clean up the stack frame anyway.
  502. // The bytecode optimizer would remove this POP, however by not including it here
  503. // it is guaranteed it doesn't have to be adjusted by the asCRestore class when
  504. // a types are of a different size than originally compiled for.
  505. // byteCode.Pop(varSize);
  506. byteCode.Ret(-stackPos);
  507. FinalizeFunction();
  508. #ifdef AS_DEBUG
  509. // DEBUG: output byte code
  510. if( outFunc->objectType )
  511. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  512. else
  513. byteCode.DebugOutput(("__" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  514. #endif
  515. return 0;
  516. }
  517. int asCCompiler::CallCopyConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asSExprContext *arg, asCScriptNode *node, bool isGlobalVar, bool derefDest)
  518. {
  519. if( !type.IsObject() )
  520. return 0;
  521. // CallCopyConstructor should not be called for object handles.
  522. asASSERT( !type.IsObjectHandle() );
  523. asCArray<asSExprContext*> args;
  524. args.PushLast(arg);
  525. // The reference parameter must be pushed on the stack
  526. asASSERT( arg->type.dataType.GetObjectType() == type.GetObjectType() );
  527. // Since we're calling the copy constructor, we have to trust the function to not do
  528. // anything stupid otherwise we will just enter a loop, as we try to make temporary
  529. // copies of the argument in order to guarantee safety.
  530. if( type.GetObjectType()->flags & asOBJ_REF )
  531. {
  532. asSExprContext ctx(engine);
  533. int func = 0;
  534. asSTypeBehaviour *beh = type.GetBehaviour();
  535. if( beh ) func = beh->copyfactory;
  536. if( func > 0 )
  537. {
  538. if( !isGlobalVar )
  539. {
  540. // Call factory and store the handle in the given variable
  541. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType(), true, offset);
  542. // Pop the reference left by the function call
  543. ctx.bc.Instr(asBC_PopPtr);
  544. }
  545. else
  546. {
  547. // Call factory
  548. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType());
  549. // Store the returned handle in the global variable
  550. ctx.bc.Instr(asBC_RDSPtr);
  551. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  552. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  553. ctx.bc.Instr(asBC_PopPtr);
  554. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  555. }
  556. bc->AddCode(&ctx.bc);
  557. return 0;
  558. }
  559. }
  560. else
  561. {
  562. asSTypeBehaviour *beh = type.GetBehaviour();
  563. int func = beh ? beh->copyconstruct : 0;
  564. if( func > 0 )
  565. {
  566. // Push the address where the object will be stored on the stack, before the argument
  567. // TODO: When the context is serializable this probably has to be changed, since this
  568. // pointer can remain on the stack while the context is suspended. There is no
  569. // risk the pointer becomes invalid though, there is just no easy way to serialize it.
  570. asCByteCode tmp(engine);
  571. if( isGlobalVar )
  572. tmp.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  573. else if( isObjectOnHeap )
  574. tmp.InstrSHORT(asBC_PSF, (short)offset);
  575. tmp.AddCode(bc);
  576. bc->AddCode(&tmp);
  577. // When the object is allocated on the stack the object pointer
  578. // must be pushed on the stack after the arguments
  579. if( !isObjectOnHeap )
  580. {
  581. asASSERT( !isGlobalVar );
  582. bc->InstrSHORT(asBC_PSF, (short)offset);
  583. if( derefDest )
  584. {
  585. // The variable is a reference to the real location, so we need to dereference it
  586. bc->Instr(asBC_RDSPtr);
  587. }
  588. }
  589. asSExprContext ctx(engine);
  590. PerformFunctionCall(func, &ctx, isObjectOnHeap, &args, type.GetObjectType());
  591. bc->AddCode(&ctx.bc);
  592. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  593. // Mark the object as initialized
  594. if( !isObjectOnHeap )
  595. bc->ObjInfo(offset, asOBJ_INIT);
  596. return 0;
  597. }
  598. }
  599. // Class has no copy constructor/factory.
  600. asCString str;
  601. str.Format(TXT_NO_COPY_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  602. Error(str.AddressOf(), node);
  603. return -1;
  604. }
  605. int asCCompiler::CallDefaultConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asCScriptNode *node, bool isGlobalVar, bool deferDest)
  606. {
  607. if( !type.IsObject() || type.IsObjectHandle() )
  608. return 0;
  609. if( type.GetObjectType()->flags & asOBJ_REF )
  610. {
  611. asSExprContext ctx(engine);
  612. ctx.exprNode = node;
  613. int func = 0;
  614. asSTypeBehaviour *beh = type.GetBehaviour();
  615. if( beh ) func = beh->factory;
  616. if( func > 0 )
  617. {
  618. if( !isGlobalVar )
  619. {
  620. // Call factory and store the handle in the given variable
  621. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType(), true, offset);
  622. // Pop the reference left by the function call
  623. ctx.bc.Instr(asBC_PopPtr);
  624. }
  625. else
  626. {
  627. // Call factory
  628. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  629. // Store the returned handle in the global variable
  630. ctx.bc.Instr(asBC_RDSPtr);
  631. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  632. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  633. ctx.bc.Instr(asBC_PopPtr);
  634. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  635. }
  636. bc->AddCode(&ctx.bc);
  637. return 0;
  638. }
  639. }
  640. else
  641. {
  642. asSTypeBehaviour *beh = type.GetBehaviour();
  643. int func = 0;
  644. if( beh ) func = beh->construct;
  645. // Allocate and initialize with the default constructor
  646. if( func != 0 || (type.GetObjectType()->flags & asOBJ_POD) )
  647. {
  648. if( !isObjectOnHeap )
  649. {
  650. asASSERT( !isGlobalVar );
  651. // There is nothing to do if there is no function,
  652. // as the memory is already allocated on the stack
  653. if( func )
  654. {
  655. // Call the constructor as a normal function
  656. bc->InstrSHORT(asBC_PSF, (short)offset);
  657. if( deferDest )
  658. bc->Instr(asBC_RDSPtr);
  659. asSExprContext ctx(engine);
  660. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  661. bc->AddCode(&ctx.bc);
  662. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  663. // Mark the object as initialized
  664. bc->ObjInfo(offset, asOBJ_INIT);
  665. }
  666. }
  667. else
  668. {
  669. if( isGlobalVar )
  670. bc->InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  671. else
  672. bc->InstrSHORT(asBC_PSF, (short)offset);
  673. bc->Alloc(asBC_ALLOC, type.GetObjectType(), func, AS_PTR_SIZE);
  674. }
  675. return 0;
  676. }
  677. }
  678. // Class has no default factory/constructor.
  679. asCString str;
  680. // TODO: funcdef: asCDataType should have a GetTypeName()
  681. if( type.GetFuncDef() )
  682. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetFuncDef()->GetName());
  683. else
  684. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  685. Error(str.AddressOf(), node);
  686. return -1;
  687. }
  688. void asCCompiler::CallDestructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc)
  689. {
  690. if( !type.IsReference() )
  691. {
  692. // Call destructor for the data type
  693. if( type.IsObject() )
  694. {
  695. if( isObjectOnHeap || type.IsObjectHandle() )
  696. {
  697. // Free the memory
  698. bc->InstrW_PTR(asBC_FREE, (short)offset, type.GetObjectType());
  699. }
  700. else
  701. {
  702. asASSERT( type.GetObjectType()->GetFlags() & asOBJ_VALUE );
  703. if( type.GetBehaviour()->destruct )
  704. {
  705. // Call the destructor as a regular function
  706. bc->InstrSHORT(asBC_PSF, (short)offset);
  707. asSExprContext ctx(engine);
  708. PerformFunctionCall(type.GetBehaviour()->destruct, &ctx);
  709. bc->AddCode(&ctx.bc);
  710. }
  711. // TODO: Value on stack: This probably needs to be done in PerformFunctionCall
  712. // Mark the object as destroyed
  713. bc->ObjInfo(offset, asOBJ_UNINIT);
  714. }
  715. }
  716. }
  717. }
  718. void asCCompiler::LineInstr(asCByteCode *bc, size_t pos)
  719. {
  720. int r, c;
  721. script->ConvertPosToRowCol(pos, &r, &c);
  722. bc->Line(r, c);
  723. }
  724. void asCCompiler::CompileStatementBlock(asCScriptNode *block, bool ownVariableScope, bool *hasReturn, asCByteCode *bc)
  725. {
  726. *hasReturn = false;
  727. bool isFinished = false;
  728. bool hasWarned = false;
  729. if( ownVariableScope )
  730. {
  731. bc->Block(true);
  732. AddVariableScope();
  733. }
  734. asCScriptNode *node = block->firstChild;
  735. while( node )
  736. {
  737. if( !hasWarned && (*hasReturn || isFinished) )
  738. {
  739. hasWarned = true;
  740. Warning(TXT_UNREACHABLE_CODE, node);
  741. }
  742. if( node->nodeType == snBreak || node->nodeType == snContinue )
  743. isFinished = true;
  744. asCByteCode statement(engine);
  745. if( node->nodeType == snDeclaration )
  746. CompileDeclaration(node, &statement);
  747. else
  748. CompileStatement(node, hasReturn, &statement);
  749. LineInstr(bc, node->tokenPos);
  750. bc->AddCode(&statement);
  751. if( !hasCompileErrors )
  752. {
  753. asASSERT( tempVariables.GetLength() == 0 );
  754. asASSERT( reservedVariables.GetLength() == 0 );
  755. }
  756. node = node->next;
  757. }
  758. if( ownVariableScope )
  759. {
  760. // Deallocate variables in this block, in reverse order
  761. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  762. {
  763. sVariable *v = variables->variables[n];
  764. // Call variable destructors here, for variables not yet destroyed
  765. // If the block is terminated with a break, continue, or
  766. // return the variables are already destroyed
  767. if( !isFinished && !*hasReturn )
  768. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  769. // Don't deallocate function parameters
  770. if( v->stackOffset > 0 )
  771. DeallocateVariable(v->stackOffset);
  772. }
  773. RemoveVariableScope();
  774. bc->Block(false);
  775. }
  776. }
  777. // Entry
  778. int asCCompiler::CompileGlobalVariable(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, sGlobalVariableDescription *gvar, asCScriptFunction *outFunc)
  779. {
  780. Reset(builder, script, outFunc);
  781. // Add a variable scope (even though variables can't be declared)
  782. AddVariableScope();
  783. asSExprContext ctx(engine);
  784. gvar->isPureConstant = false;
  785. // Parse the initialization nodes
  786. asCParser parser(builder);
  787. if( node )
  788. {
  789. int r = parser.ParseGlobalVarInit(script, node);
  790. if( r < 0 )
  791. return r;
  792. node = parser.GetScriptNode();
  793. }
  794. // Compile the expression
  795. if( node && node->nodeType == snArgList )
  796. {
  797. // Make sure that it is a registered type, and that it isn't a pointer
  798. if( gvar->datatype.GetObjectType() == 0 || gvar->datatype.IsObjectHandle() )
  799. {
  800. Error(TXT_MUST_BE_OBJECT, node);
  801. }
  802. else
  803. {
  804. // Compile the arguments
  805. asCArray<asSExprContext *> args;
  806. if( CompileArgumentList(node, args) >= 0 )
  807. {
  808. // Find all constructors
  809. asCArray<int> funcs;
  810. asSTypeBehaviour *beh = gvar->datatype.GetBehaviour();
  811. if( beh )
  812. {
  813. if( gvar->datatype.GetObjectType()->flags & asOBJ_REF )
  814. funcs = beh->factories;
  815. else
  816. funcs = beh->constructors;
  817. }
  818. asCString str = gvar->datatype.Format();
  819. MatchFunctions(funcs, args, node, str.AddressOf());
  820. if( funcs.GetLength() == 1 )
  821. {
  822. int r = asSUCCESS;
  823. // Add the default values for arguments not explicitly supplied
  824. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  825. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  826. r = CompileDefaultArgs(node, args, func);
  827. if( r == asSUCCESS )
  828. {
  829. if( gvar->datatype.GetObjectType()->flags & asOBJ_REF )
  830. {
  831. MakeFunctionCall(&ctx, funcs[0], 0, args, node);
  832. // Store the returned handle in the global variable
  833. ctx.bc.Instr(asBC_RDSPtr);
  834. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  835. ctx.bc.InstrPTR(asBC_REFCPY, gvar->datatype.GetObjectType());
  836. ctx.bc.Instr(asBC_PopPtr);
  837. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  838. }
  839. else
  840. {
  841. // Push the address of the location where the variable will be stored on the stack.
  842. // This reference is safe, because the addresses of the global variables cannot change.
  843. // TODO: When serialization of the context is implemented this will probably have to change,
  844. // because this pointer may be on the stack while the context is suspended, and may
  845. // be difficult to serialize as the context doesn't know that the value represents a
  846. // pointer.
  847. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  848. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  849. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  850. PerformFunctionCall(funcs[0], &ctx, true, &args, gvar->datatype.GetObjectType());
  851. }
  852. }
  853. }
  854. }
  855. // Cleanup
  856. for( asUINT n = 0; n < args.GetLength(); n++ )
  857. if( args[n] )
  858. {
  859. asDELETE(args[n],asSExprContext);
  860. }
  861. }
  862. }
  863. else if( node && node->nodeType == snInitList )
  864. {
  865. asCTypeInfo ti;
  866. ti.Set(gvar->datatype);
  867. ti.isVariable = false;
  868. ti.isTemporary = false;
  869. ti.stackOffset = (short)gvar->index;
  870. ti.isLValue = true;
  871. CompileInitList(&ti, node, &ctx.bc);
  872. node = node->next;
  873. }
  874. else if( node )
  875. {
  876. // Compile the right hand expression
  877. asSExprContext expr(engine);
  878. int r = CompileAssignment(node, &expr); if( r < 0 ) return r;
  879. // Assign the value to the variable
  880. if( gvar->datatype.IsPrimitive() )
  881. {
  882. if( gvar->datatype.IsReadOnly() && expr.type.isConstant )
  883. {
  884. ImplicitConversion(&expr, gvar->datatype, node, asIC_IMPLICIT_CONV);
  885. gvar->isPureConstant = true;
  886. gvar->constantValue = expr.type.qwordValue;
  887. }
  888. asSExprContext lctx(engine);
  889. lctx.type.Set(gvar->datatype);
  890. lctx.type.dataType.MakeReference(true);
  891. lctx.type.dataType.MakeReadOnly(false);
  892. lctx.type.isLValue = true;
  893. // If it is an enum value that is being compiled, then
  894. // we skip this, as the bytecode won't be used anyway
  895. if( !gvar->isEnumValue )
  896. lctx.bc.InstrPTR(asBC_LDG, engine->globalProperties[gvar->index]->GetAddressOfValue());
  897. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  898. }
  899. else
  900. {
  901. // TODO: runtime optimize: Here we should look for the best matching constructor, instead of
  902. // just the copy constructor. Only if no appropriate constructor is
  903. // available should the assignment operator be used.
  904. if( !gvar->datatype.IsObjectHandle() )
  905. {
  906. // Call the default constructor to have a valid object for the assignment
  907. CallDefaultConstructor(gvar->datatype, gvar->index, true, &ctx.bc, gvar->idNode, true);
  908. }
  909. asSExprContext lexpr(engine);
  910. lexpr.type.Set(gvar->datatype);
  911. lexpr.type.dataType.MakeReference(true);
  912. lexpr.type.dataType.MakeReadOnly(false);
  913. lexpr.type.stackOffset = -1;
  914. lexpr.type.isLValue = true;
  915. if( gvar->datatype.IsObjectHandle() )
  916. lexpr.type.isExplicitHandle = true;
  917. lexpr.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  918. // If left expression resolves into a registered type
  919. // check if the assignment operator is overloaded, and check
  920. // the type of the right hand expression. If none is found
  921. // the default action is a direct copy if it is the same type
  922. // and a simple assignment.
  923. bool assigned = false;
  924. // Even though an ASHANDLE can be an explicit handle the assignment needs to be treated by the overloaded operator
  925. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  926. {
  927. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  928. if( assigned )
  929. {
  930. // Pop the resulting value
  931. ctx.bc.Instr(asBC_PopPtr);
  932. // Release the argument
  933. ProcessDeferredParams(&ctx);
  934. }
  935. }
  936. if( !assigned )
  937. {
  938. PrepareForAssignment(&lexpr.type.dataType, &expr, node, false);
  939. // If the expression is constant and the variable also is constant
  940. // then mark the variable as pure constant. This will allow the compiler
  941. // to optimize expressions with this variable.
  942. if( gvar->datatype.IsReadOnly() && expr.type.isConstant )
  943. {
  944. gvar->isPureConstant = true;
  945. gvar->constantValue = expr.type.qwordValue;
  946. }
  947. // Add expression code to bytecode
  948. MergeExprBytecode(&ctx, &expr);
  949. // Add byte code for storing value of expression in variable
  950. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  951. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, node);
  952. // Release temporary variables used by expression
  953. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  954. ctx.bc.Instr(asBC_PopPtr);
  955. }
  956. }
  957. }
  958. else if( gvar->datatype.IsObject() && !gvar->datatype.IsObjectHandle() )
  959. {
  960. // Call the default constructor in case no explicit initialization is given
  961. CallDefaultConstructor(gvar->datatype, gvar->index, true, &ctx.bc, gvar->idNode, true);
  962. }
  963. // Concatenate the bytecode
  964. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  965. // Add information on the line number for the global variable
  966. size_t pos = 0;
  967. if( gvar->idNode )
  968. pos = gvar->idNode->tokenPos;
  969. else if( gvar->nextNode )
  970. pos = gvar->nextNode->tokenPos;
  971. LineInstr(&byteCode, pos);
  972. // Reserve space for all local variables
  973. outFunc->variableSpace = varSize;
  974. byteCode.AddCode(&ctx.bc);
  975. // Deallocate variables in this block, in reverse order
  976. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; --n )
  977. {
  978. sVariable *v = variables->variables[n];
  979. // Call variable destructors here, for variables not yet destroyed
  980. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  981. DeallocateVariable(v->stackOffset);
  982. }
  983. if( hasCompileErrors ) return -1;
  984. // At this point there should be no variables allocated
  985. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  986. // Remove the variable scope again
  987. RemoveVariableScope();
  988. byteCode.Ret(0);
  989. FinalizeFunction();
  990. #ifdef AS_DEBUG
  991. // DEBUG: output byte code
  992. byteCode.DebugOutput(("___init_" + gvar->name + ".txt").AddressOf(), engine, outFunc);
  993. #endif
  994. return 0;
  995. }
  996. void asCCompiler::PrepareArgument(asCDataType *paramType, asSExprContext *ctx, asCScriptNode *node, bool isFunction, int refType, bool isMakingCopy)
  997. {
  998. asCDataType param = *paramType;
  999. if( paramType->GetTokenType() == ttQuestion )
  1000. {
  1001. // Since the function is expecting a var type ?, then we don't want to convert the argument to anything else
  1002. param = ctx->type.dataType;
  1003. param.MakeHandle(ctx->type.isExplicitHandle);
  1004. param.MakeReference(paramType->IsReference());
  1005. param.MakeReadOnly(paramType->IsReadOnly());
  1006. }
  1007. else
  1008. param = *paramType;
  1009. asCDataType dt = param;
  1010. // Need to protect arguments by reference
  1011. if( isFunction && dt.IsReference() )
  1012. {
  1013. if( paramType->GetTokenType() == ttQuestion )
  1014. {
  1015. asCByteCode tmpBC(engine);
  1016. // Place the type id on the stack as a hidden parameter
  1017. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  1018. // Insert the code before the expression code
  1019. tmpBC.AddCode(&ctx->bc);
  1020. ctx->bc.AddCode(&tmpBC);
  1021. }
  1022. // Allocate a temporary variable of the same type as the argument
  1023. dt.MakeReference(false);
  1024. dt.MakeReadOnly(false);
  1025. int offset;
  1026. if( refType == 1 ) // &in
  1027. {
  1028. ProcessPropertyGetAccessor(ctx, node);
  1029. // If the reference is const, then it is not necessary to make a copy if the value already is a variable
  1030. // Even if the same variable is passed in another argument as non-const then there is no problem
  1031. if( dt.IsPrimitive() || dt.IsNullHandle() )
  1032. {
  1033. IsVariableInitialized(&ctx->type, node);
  1034. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  1035. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true);
  1036. if( !(param.IsReadOnly() && ctx->type.isVariable) )
  1037. ConvertToTempVariable(ctx);
  1038. PushVariableOnStack(ctx, true);
  1039. ctx->type.dataType.MakeReadOnly(param.IsReadOnly());
  1040. }
  1041. else
  1042. {
  1043. IsVariableInitialized(&ctx->type, node);
  1044. if( !isMakingCopy )
  1045. {
  1046. ImplicitConversion(ctx, param, node, asIC_IMPLICIT_CONV, true);
  1047. if( !ctx->type.dataType.IsEqualExceptRef(param) )
  1048. {
  1049. asCString str;
  1050. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), param.Format().AddressOf());
  1051. Error(str.AddressOf(), node);
  1052. ctx->type.Set(param);
  1053. }
  1054. }
  1055. // If the argument already is a temporary
  1056. // variable we don't need to allocate another
  1057. // If the parameter is read-only and the object already is a local
  1058. // variable then it is not necessary to make a copy either
  1059. if( !ctx->type.isTemporary && !(param.IsReadOnly() && ctx->type.isVariable) && !isMakingCopy )
  1060. {
  1061. // Make sure the variable is not used in the expression
  1062. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1063. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  1064. // Allocate and construct the temporary object
  1065. asCByteCode tmpBC(engine);
  1066. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  1067. // Insert the code before the expression code
  1068. tmpBC.AddCode(&ctx->bc);
  1069. ctx->bc.AddCode(&tmpBC);
  1070. // Assign the evaluated expression to the temporary variable
  1071. PrepareForAssignment(&dt, ctx, node, true);
  1072. dt.MakeReference(IsVariableOnHeap(offset));
  1073. asCTypeInfo type;
  1074. type.Set(dt);
  1075. type.isTemporary = true;
  1076. type.stackOffset = (short)offset;
  1077. if( dt.IsObjectHandle() )
  1078. type.isExplicitHandle = true;
  1079. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1080. PerformAssignment(&type, &ctx->type, &ctx->bc, node);
  1081. ctx->bc.Instr(asBC_PopPtr);
  1082. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  1083. ctx->type = type;
  1084. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1085. if( dt.IsObject() && !dt.IsObjectHandle() )
  1086. ctx->bc.Instr(asBC_RDSPtr);
  1087. if( paramType->IsReadOnly() )
  1088. ctx->type.dataType.MakeReadOnly(true);
  1089. }
  1090. else if( isMakingCopy )
  1091. {
  1092. // We must guarantee that the address to the value is on the stack
  1093. if( ctx->type.dataType.IsObject() &&
  1094. !ctx->type.dataType.IsObjectHandle() &&
  1095. ctx->type.dataType.IsReference() )
  1096. Dereference(ctx, true);
  1097. }
  1098. }
  1099. }
  1100. else if( refType == 2 ) // &out
  1101. {
  1102. // Make sure the variable is not used in the expression
  1103. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1104. if( dt.IsPrimitive() )
  1105. {
  1106. ctx->type.SetVariable(dt, offset, true);
  1107. PushVariableOnStack(ctx, true);
  1108. }
  1109. else
  1110. {
  1111. // Allocate and construct the temporary object
  1112. asCByteCode tmpBC(engine);
  1113. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  1114. // Insert the code before the expression code
  1115. tmpBC.AddCode(&ctx->bc);
  1116. ctx->bc.AddCode(&tmpBC);
  1117. dt.MakeReference((!dt.IsObject() || dt.IsObjectHandle()));
  1118. asCTypeInfo type;
  1119. type.Set(dt);
  1120. type.isTemporary = true;
  1121. type.stackOffset = (short)offset;
  1122. ctx->type = type;
  1123. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1124. if( dt.IsObject() && !dt.IsObjectHandle() )
  1125. ctx->bc.Instr(asBC_RDSPtr);
  1126. }
  1127. // After the function returns the temporary variable will
  1128. // be assigned to the expression, if it is a valid lvalue
  1129. }
  1130. else if( refType == asTM_INOUTREF )
  1131. {
  1132. ProcessPropertyGetAccessor(ctx, node);
  1133. // Literal constants cannot be passed to inout ref arguments
  1134. if( !ctx->type.isVariable && ctx->type.isConstant )
  1135. {
  1136. Error(TXT_NOT_VALID_REFERENCE, node);
  1137. }
  1138. // Only objects that support object handles
  1139. // can be guaranteed to be safe. Local variables are
  1140. // already safe, so there is no need to add an extra
  1141. // references
  1142. if( !engine->ep.allowUnsafeReferences &&
  1143. !ctx->type.isVariable &&
  1144. ctx->type.dataType.IsObject() &&
  1145. !ctx->type.dataType.IsObjectHandle() &&
  1146. ((ctx->type.dataType.GetBehaviour()->addref &&
  1147. ctx->type.dataType.GetBehaviour()->release) ||
  1148. (ctx->type.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) )
  1149. {
  1150. // Store a handle to the object as local variable
  1151. asSExprContext tmp(engine);
  1152. asCDataType dt = ctx->type.dataType;
  1153. dt.MakeHandle(true);
  1154. dt.MakeReference(false);
  1155. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1156. // Copy the handle
  1157. if( !ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReference() )
  1158. ctx->bc.Instr(asBC_RDSPtr);
  1159. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1160. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  1161. ctx->bc.Instr(asBC_PopPtr);
  1162. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1163. dt.MakeHandle(false);
  1164. dt.MakeReference(true);
  1165. // Release previous temporary variable stored in the context (if any)
  1166. if( ctx->type.isTemporary )
  1167. {
  1168. ReleaseTemporaryVariable(ctx->type.stackOffset, &ctx->bc);
  1169. }
  1170. ctx->type.SetVariable(dt, offset, true);
  1171. }
  1172. // Make sure the reference to the value is on the stack
  1173. // For objects, the reference needs to be dereferenced so the pointer on the stack is to the actual object
  1174. // For handles, the reference shouldn't be changed because the pointer on the stack should be to the handle
  1175. if( ctx->type.dataType.IsObject() && ctx->type.dataType.IsReference() && !paramType->IsObjectHandle() )
  1176. Dereference(ctx, true);
  1177. else if( ctx->type.isVariable && !ctx->type.dataType.IsObject() )
  1178. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  1179. else if( ctx->type.dataType.IsPrimitive() )
  1180. ctx->bc.Instr(asBC_PshRPtr);
  1181. }
  1182. }
  1183. else
  1184. {
  1185. ProcessPropertyGetAccessor(ctx, node);
  1186. if( dt.IsPrimitive() )
  1187. {
  1188. IsVariableInitialized(&ctx->type, node);
  1189. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  1190. // Implicitly convert primitives to the parameter type
  1191. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  1192. if( ctx->type.isVariable )
  1193. {
  1194. PushVariableOnStack(ctx, dt.IsReference());
  1195. }
  1196. else if( ctx->type.isConstant )
  1197. {
  1198. ConvertToVariable(ctx);
  1199. PushVariableOnStack(ctx, dt.IsReference());
  1200. }
  1201. }
  1202. else
  1203. {
  1204. IsVariableInitialized(&ctx->type, node);
  1205. // Implicitly convert primitives to the parameter type
  1206. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  1207. // Was the conversion successful?
  1208. if( !ctx->type.dataType.IsEqualExceptRef(dt) )
  1209. {
  1210. asCString str;
  1211. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), dt.Format().AddressOf());
  1212. Error(str.AddressOf(), node);
  1213. ctx->type.Set(dt);
  1214. }
  1215. if( dt.IsObjectHandle() )
  1216. ctx->type.isExplicitHandle = true;
  1217. if( dt.IsObject() )
  1218. {
  1219. if( !dt.IsReference() )
  1220. {
  1221. // Objects passed by value must be placed in temporary variables
  1222. // so that they are guaranteed to not be referenced anywhere else.
  1223. // The object must also be allocated on the heap, as the memory will
  1224. // be deleted by in as_callfunc_xxx.
  1225. // TODO: value on stack: How can we avoid this unnecessary allocation?
  1226. PrepareTemporaryObject(node, ctx, true);
  1227. // The implicit conversion shouldn't convert the object to
  1228. // non-reference yet. It will be dereferenced just before the call.
  1229. // Otherwise the object might be missed by the exception handler.
  1230. dt.MakeReference(true);
  1231. }
  1232. else
  1233. {
  1234. // An object passed by reference should place the pointer to
  1235. // the object on the stack.
  1236. dt.MakeReference(false);
  1237. }
  1238. }
  1239. }
  1240. }
  1241. // Don't put any pointer on the stack yet
  1242. if( param.IsReference() || param.IsObject() )
  1243. {
  1244. // &inout parameter may leave the reference on the stack already
  1245. if( refType != 3 )
  1246. {
  1247. asASSERT( ctx->type.isVariable || ctx->type.isTemporary || isMakingCopy );
  1248. if( ctx->type.isVariable || ctx->type.isTemporary )
  1249. {
  1250. ctx->bc.Instr(asBC_PopPtr);
  1251. ctx->bc.InstrSHORT(asBC_VAR, ctx->type.stackOffset);
  1252. ProcessDeferredParams(ctx);
  1253. }
  1254. }
  1255. }
  1256. }
  1257. void asCCompiler::PrepareFunctionCall(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args)
  1258. {
  1259. // When a match has been found, compile the final byte code using correct parameter types
  1260. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1261. // If the function being called is the opAssign or copy constructor for the same type
  1262. // as the argument, then we should avoid making temporary copy of the argument
  1263. bool makingCopy = false;
  1264. if( descr->parameterTypes.GetLength() == 1 &&
  1265. descr->parameterTypes[0].IsEqualExceptRefAndConst(args[0]->type.dataType) &&
  1266. ((descr->name == "opAssign" && descr->objectType && descr->objectType == args[0]->type.dataType.GetObjectType()) ||
  1267. (args[0]->type.dataType.GetObjectType() && descr->name == args[0]->type.dataType.GetObjectType()->name)) )
  1268. makingCopy = true;
  1269. // Add code for arguments
  1270. asSExprContext e(engine);
  1271. for( int n = (int)args.GetLength()-1; n >= 0; n-- )
  1272. {
  1273. // Make sure PrepareArgument doesn't use any variable that is already
  1274. // being used by any of the following argument expressions
  1275. int l = int(reservedVariables.GetLength());
  1276. for( int m = n-1; m >= 0; m-- )
  1277. args[m]->bc.GetVarsUsed(reservedVariables);
  1278. PrepareArgument2(&e, args[n], &descr->parameterTypes[n], true, descr->inOutFlags[n], makingCopy);
  1279. reservedVariables.SetLength(l);
  1280. }
  1281. bc->AddCode(&e.bc);
  1282. }
  1283. void asCCompiler::MoveArgsToStack(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args, bool addOneToOffset)
  1284. {
  1285. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1286. int offset = 0;
  1287. if( addOneToOffset )
  1288. offset += AS_PTR_SIZE;
  1289. // The address of where the return value should be stored is push on top of the arguments
  1290. if( descr->DoesReturnOnStack() )
  1291. offset += AS_PTR_SIZE;
  1292. #ifdef AS_DEBUG
  1293. // If the function being called is the opAssign or copy constructor for the same type
  1294. // as the argument, then we should avoid making temporary copy of the argument
  1295. bool makingCopy = false;
  1296. if( descr->parameterTypes.GetLength() == 1 &&
  1297. descr->parameterTypes[0].IsEqualExceptRefAndConst(args[0]->type.dataType) &&
  1298. ((descr->name == "opAssign" && descr->objectType && descr->objectType == args[0]->type.dataType.GetObjectType()) ||
  1299. (args[0]->type.dataType.GetObjectType() && descr->name == args[0]->type.dataType.GetObjectType()->name)) )
  1300. makingCopy = true;
  1301. #endif
  1302. // Move the objects that are sent by value to the stack just before the call
  1303. for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
  1304. {
  1305. if( descr->parameterTypes[n].IsReference() )
  1306. {
  1307. if( descr->parameterTypes[n].IsObject() && !descr->parameterTypes[n].IsObjectHandle() )
  1308. {
  1309. if( descr->inOutFlags[n] != asTM_INOUTREF )
  1310. {
  1311. #ifdef AS_DEBUG
  1312. asASSERT( args[n]->type.isVariable || args[n]->type.isTemporary || makingCopy );
  1313. #endif
  1314. if( (args[n]->type.isVariable || args[n]->type.isTemporary) )
  1315. {
  1316. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1317. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  1318. // as the value allocated on the stack is guaranteed to be safe
  1319. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1320. else
  1321. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1322. }
  1323. }
  1324. if( args[n]->type.dataType.IsObjectHandle() )
  1325. bc->InstrWORD(asBC_ChkNullS, (asWORD)offset);
  1326. }
  1327. else if( descr->inOutFlags[n] != asTM_INOUTREF )
  1328. {
  1329. if( descr->parameterTypes[n].GetTokenType() == ttQuestion &&
  1330. args[n]->type.dataType.IsObject() && !args[n]->type.dataType.IsObjectHandle() )
  1331. {
  1332. // Send the object as a reference to the object,
  1333. // and not to the variable holding the object
  1334. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1335. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  1336. // as the value allocated on the stack is guaranteed to be safe
  1337. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1338. else
  1339. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1340. }
  1341. else
  1342. {
  1343. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1344. }
  1345. }
  1346. }
  1347. else if( descr->parameterTypes[n].IsObject() )
  1348. {
  1349. // TODO: value on stack: What can we do to avoid this unnecessary allocation?
  1350. // The object must be allocated on the heap, because this memory will be deleted in as_callfunc_xxx
  1351. asASSERT(IsVariableOnHeap(args[n]->type.stackOffset));
  1352. bc->InstrWORD(asBC_GETOBJ, (asWORD)offset);
  1353. // The temporary variable must not be freed as it will no longer hold an object
  1354. DeallocateVariable(args[n]->type.stackOffset);
  1355. args[n]->type.isTemporary = false;
  1356. }
  1357. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  1358. }
  1359. }
  1360. int asCCompiler::CompileArgumentList(asCScriptNode *node, asCArray<asSExprContext*> &args)
  1361. {
  1362. asASSERT(node->nodeType == snArgList);
  1363. // Count arguments
  1364. asCScriptNode *arg = node->firstChild;
  1365. int argCount = 0;
  1366. while( arg )
  1367. {
  1368. argCount++;
  1369. arg = arg->next;
  1370. }
  1371. // Prepare the arrays
  1372. args.SetLength(argCount);
  1373. int n;
  1374. for( n = 0; n < argCount; n++ )
  1375. args[n] = 0;
  1376. n = argCount-1;
  1377. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1378. bool anyErrors = false;
  1379. arg = node->lastChild;
  1380. while( arg )
  1381. {
  1382. asSExprContext expr(engine);
  1383. int r = CompileAssignment(arg, &expr);
  1384. if( r < 0 ) anyErrors = true;
  1385. args[n] = asNEW(asSExprContext)(engine);
  1386. MergeExprBytecodeAndType(args[n], &expr);
  1387. n--;
  1388. arg = arg->prev;
  1389. }
  1390. return anyErrors ? -1 : 0;
  1391. }
  1392. int asCCompiler::CompileDefaultArgs(asCScriptNode *node, asCArray<asSExprContext*> &args, asCScriptFunction *func)
  1393. {
  1394. bool anyErrors = false;
  1395. asCArray<int> varsUsed;
  1396. int explicitArgs = (int)args.GetLength();
  1397. for( int p = 0; p < explicitArgs; p++ )
  1398. args[p]->bc.GetVarsUsed(varsUsed);
  1399. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1400. args.SetLength(func->parameterTypes.GetLength());
  1401. for( asUINT c = explicitArgs; c < args.GetLength(); c++ )
  1402. args[c] = 0;
  1403. for( int n = (int)func->parameterTypes.GetLength() - 1; n >= explicitArgs; n-- )
  1404. {
  1405. if( func->defaultArgs[n] == 0 ) { anyErrors = true; continue; }
  1406. // Parse the default arg string
  1407. asCParser parser(builder);
  1408. asCScriptCode code;
  1409. code.SetCode("default arg", func->defaultArgs[n]->AddressOf(), false);
  1410. int r = parser.ParseExpression(&code);
  1411. if( r < 0 ) { anyErrors = true; continue; }
  1412. asCScriptNode *arg = parser.GetScriptNode();
  1413. // Temporarily set the script code to the default arg expression
  1414. asCScriptCode *origScript = script;
  1415. script = &code;
  1416. // Don't allow the expression to access local variables
  1417. // TODO: namespace: The default arg should see the symbols declared in the same scope as the function
  1418. isCompilingDefaultArg = true;
  1419. asSExprContext expr(engine);
  1420. r = CompileExpression(arg, &expr);
  1421. isCompilingDefaultArg = false;
  1422. script = origScript;
  1423. if( r < 0 )
  1424. {
  1425. asCString msg;
  1426. msg.Format(TXT_FAILED_TO_COMPILE_DEF_ARG_d_IN_FUNC_s, n, func->GetDeclaration());
  1427. Error(msg.AddressOf(), node);
  1428. anyErrors = true;
  1429. continue;
  1430. }
  1431. args[n] = asNEW(asSExprContext)(engine);
  1432. MergeExprBytecodeAndType(args[n], &expr);
  1433. // Make sure the default arg expression doesn't end up
  1434. // with a variable that is used in a previous expression
  1435. if( args[n]->type.isVariable )
  1436. {
  1437. int offset = args[n]->type.stackOffset;
  1438. if( varsUsed.Exists(offset) )
  1439. {
  1440. // Release the current temporary variable
  1441. ReleaseTemporaryVariable(args[n]->type, 0);
  1442. asCDataType dt = args[n]->type.dataType;
  1443. dt.MakeReference(false);
  1444. int newOffset = AllocateVariable(dt, true, IsVariableOnHeap(offset));
  1445. asASSERT( IsVariableOnHeap(offset) == IsVariableOnHeap(newOffset) );
  1446. args[n]->bc.ExchangeVar(offset, newOffset);
  1447. args[n]->type.stackOffset = (short)newOffset;
  1448. args[n]->type.isTemporary = true;
  1449. args[n]->type.isVariable = true;
  1450. }
  1451. }
  1452. }
  1453. return anyErrors ? -1 : 0;
  1454. }
  1455. 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)
  1456. {
  1457. asCArray<int> origFuncs = funcs; // Keep the original list for error message
  1458. asUINT cost = 0;
  1459. asUINT n;
  1460. if( funcs.GetLength() > 0 )
  1461. {
  1462. // Check the number of parameters in the found functions
  1463. for( n = 0; n < funcs.GetLength(); ++n )
  1464. {
  1465. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  1466. if( desc->parameterTypes.GetLength() != args.GetLength() )
  1467. {
  1468. bool noMatch = true;
  1469. if( args.GetLength() < desc->parameterTypes.GetLength() )
  1470. {
  1471. // Count the number of default args
  1472. asUINT defaultArgs = 0;
  1473. for( asUINT d = 0; d < desc->defaultArgs.GetLength(); d++ )
  1474. if( desc->defaultArgs[d] )
  1475. defaultArgs++;
  1476. if( args.GetLength() >= desc->parameterTypes.GetLength() - defaultArgs )
  1477. noMatch = false;
  1478. }
  1479. if( noMatch )
  1480. {
  1481. // remove it from the list
  1482. if( n == funcs.GetLength()-1 )
  1483. funcs.PopLast();
  1484. else
  1485. funcs[n] = funcs.PopLast();
  1486. n--;
  1487. }
  1488. }
  1489. }
  1490. // Match functions with the parameters, and discard those that do not match
  1491. asCArray<int> matchingFuncs = funcs;
  1492. for( n = 0; n < args.GetLength(); ++n )
  1493. {
  1494. asCArray<int> tempFuncs;
  1495. cost += MatchArgument(funcs, tempFuncs, &args[n]->type, n, allowObjectConstruct);
  1496. // Intersect the found functions with the list of matching functions
  1497. for( asUINT f = 0; f < matchingFuncs.GetLength(); f++ )
  1498. {
  1499. asUINT c;
  1500. for( c = 0; c < tempFuncs.GetLength(); c++ )
  1501. {
  1502. if( matchingFuncs[f] == tempFuncs[c] )
  1503. break;
  1504. }
  1505. // Was the function a match?
  1506. if( c == tempFuncs.GetLength() )
  1507. {
  1508. // No, remove it from the list
  1509. if( f == matchingFuncs.GetLength()-1 )
  1510. matchingFuncs.PopLast();
  1511. else
  1512. matchingFuncs[f] = matchingFuncs.PopLast();
  1513. f--;
  1514. }
  1515. }
  1516. }
  1517. funcs = matchingFuncs;
  1518. }
  1519. if( !isConstMethod )
  1520. FilterConst(funcs);
  1521. if( funcs.GetLength() != 1 && !silent )
  1522. {
  1523. // Build a readable string of the function with parameter types
  1524. asCString str;
  1525. if( scope != "" )
  1526. {
  1527. if( scope == "::" )
  1528. str = scope;
  1529. else
  1530. str = scope + "::";
  1531. }
  1532. str += name;
  1533. str += "(";
  1534. if( args.GetLength() )
  1535. str += args[0]->type.dataType.Format();
  1536. for( n = 1; n < args.GetLength(); n++ )
  1537. str += ", " + args[n]->type.dataType.Format();
  1538. str += ")";
  1539. if( isConstMethod )
  1540. str += " const";
  1541. if( objectType && scope == "" )
  1542. str = objectType->name + "::" + str;
  1543. if( funcs.GetLength() == 0 )
  1544. {
  1545. str.Format(TXT_NO_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1546. Error(str.AddressOf(), node);
  1547. // Print the list of candidates
  1548. if( origFuncs.GetLength() > 0 )
  1549. {
  1550. int r = 0, c = 0;
  1551. asASSERT( node );
  1552. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  1553. builder->WriteInfo(script->name.AddressOf(), TXT_CANDIDATES_ARE, r, c, false);
  1554. PrintMatchingFuncs(origFuncs, node);
  1555. }
  1556. }
  1557. else
  1558. {
  1559. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1560. Error(str.AddressOf(), node);
  1561. PrintMatchingFuncs(funcs, node);
  1562. }
  1563. }
  1564. return cost;
  1565. }
  1566. void asCCompiler::CompileDeclaration(asCScriptNode *decl, asCByteCode *bc)
  1567. {
  1568. // Get the data type
  1569. // TODO: namespace: Use correct implicit namespace from function
  1570. asCDataType type = builder->CreateDataTypeFromNode(decl->firstChild, script, "");
  1571. // Declare all variables in this declaration
  1572. asCScriptNode *node = decl->firstChild->next;
  1573. while( node )
  1574. {
  1575. // Is the type allowed?
  1576. if( !type.CanBeInstanciated() )
  1577. {
  1578. asCString str;
  1579. // TODO: Change to "'type' cannot be declared as variable"
  1580. str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format().AddressOf());
  1581. Error(str.AddressOf(), node);
  1582. // Use int instead to avoid further problems
  1583. type = asCDataType::CreatePrimitive(ttInt, false);
  1584. }
  1585. // A shared object may not declare variables of non-shared types
  1586. if( outFunc->IsShared() )
  1587. {
  1588. asCObjectType *ot = type.GetObjectType();
  1589. if( ot && !ot->IsShared() )
  1590. {
  1591. asCString msg;
  1592. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  1593. Error(msg.AddressOf(), decl);
  1594. }
  1595. }
  1596. // Get the name of the identifier
  1597. asCString name(&script->code[node->tokenPos], node->tokenLength);
  1598. // Verify that the name isn't used by a dynamic data type
  1599. if( engine->GetObjectType(name.AddressOf()) != 0 )
  1600. {
  1601. asCString str;
  1602. str.Format(TXT_ILLEGAL_VARIABLE_NAME_s, name.AddressOf());
  1603. Error(str.AddressOf(), node);
  1604. }
  1605. int offset = AllocateVariable(type, false);
  1606. if( variables->DeclareVariable(name.AddressOf(), type, offset, IsVariableOnHeap(offset)) < 0 )
  1607. {
  1608. asCString str;
  1609. str.Format(TXT_s_ALREADY_DECLARED, name.AddressOf());
  1610. Error(str.AddressOf(), node);
  1611. // Don't continue after this error, as it will just
  1612. // lead to more errors that are likely false
  1613. return;
  1614. }
  1615. // Add marker that the variable has been declared
  1616. bc->VarDecl((int)outFunc->variables.GetLength());
  1617. outFunc->AddVariable(name, type, offset);
  1618. // Keep the node for the variable decl
  1619. asCScriptNode *varNode = node;
  1620. node = node->next;
  1621. if( node && node->nodeType == snArgList )
  1622. {
  1623. // Make sure that it is a registered type, and that is isn't a pointer
  1624. if( type.GetObjectType() == 0 || type.IsObjectHandle() )
  1625. {
  1626. Error(TXT_MUST_BE_OBJECT, node);
  1627. }
  1628. else
  1629. {
  1630. // Compile the arguments
  1631. asCArray<asSExprContext *> args;
  1632. if( CompileArgumentList(node, args) >= 0 )
  1633. {
  1634. // Find all constructors
  1635. asCArray<int> funcs;
  1636. asSTypeBehaviour *beh = type.GetBehaviour();
  1637. if( beh )
  1638. {
  1639. if( type.GetObjectType()->flags & asOBJ_REF )
  1640. funcs = beh->factories;
  1641. else
  1642. funcs = beh->constructors;
  1643. }
  1644. asCString str = type.Format();
  1645. MatchFunctions(funcs, args, node, str.AddressOf());
  1646. if( funcs.GetLength() == 1 )
  1647. {
  1648. int r = asSUCCESS;
  1649. // Add the default values for arguments not explicitly supplied
  1650. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  1651. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  1652. r = CompileDefaultArgs(node, args, func);
  1653. if( r == asSUCCESS )
  1654. {
  1655. sVariable *v = variables->GetVariable(name.AddressOf());
  1656. asSExprContext ctx(engine);
  1657. if( v->type.GetObjectType() && (v->type.GetObjectType()->flags & asOBJ_REF) )
  1658. {
  1659. MakeFunctionCall(&ctx, funcs[0], 0, args, node, true, v->stackOffset);
  1660. // Pop the reference left by the function call
  1661. ctx.bc.Instr(asBC_PopPtr);
  1662. }
  1663. else
  1664. {
  1665. // When the object is allocated on the heap, the address where the
  1666. // reference will be stored must be pushed on the stack before the
  1667. // arguments. This reference on the stack is safe, even if the script
  1668. // is suspended during the evaluation of the arguments.
  1669. if( v->onHeap )
  1670. ctx.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1671. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  1672. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  1673. // When the object is allocated on the stack, the address to the
  1674. // object is pushed on the stack after the arguments as the object pointer
  1675. if( !v->onHeap )
  1676. ctx.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1677. PerformFunctionCall(funcs[0], &ctx, v->onHeap, &args, type.GetObjectType());
  1678. // TODO: value on stack: This probably has to be done in PerformFunctionCall
  1679. // Mark the object as initialized
  1680. ctx.bc.ObjInfo(v->stackOffset, asOBJ_INIT);
  1681. }
  1682. bc->AddCode(&ctx.bc);
  1683. }
  1684. }
  1685. }
  1686. // Cleanup
  1687. for( asUINT n = 0; n < args.GetLength(); n++ )
  1688. if( args[n] )
  1689. {
  1690. asDELETE(args[n],asSExprContext);
  1691. }
  1692. }
  1693. node = node->next;
  1694. }
  1695. else if( node && node->nodeType == snInitList )
  1696. {
  1697. sVariable *v = variables->GetVariable(name.AddressOf());
  1698. asCTypeInfo ti;
  1699. ti.Set(type);
  1700. ti.isVariable = true;
  1701. ti.isTemporary = false;
  1702. ti.stackOffset = (short)v->stackOffset;
  1703. ti.isLValue = true;
  1704. CompileInitList(&ti, node, bc);
  1705. node = node->next;
  1706. }
  1707. else if( node && node->nodeType == snAssignment )
  1708. {
  1709. asSExprContext ctx(engine);
  1710. // TODO: copy: Here we should look for the best matching constructor, instead of
  1711. // just the copy constructor. Only if no appropriate constructor is
  1712. // available should the assignment operator be used.
  1713. // Call the default constructor here
  1714. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), &ctx.bc, varNode);
  1715. // Compile the expression
  1716. asSExprContext expr(engine);
  1717. int r = CompileAssignment(node, &expr);
  1718. if( r >= 0 )
  1719. {
  1720. if( type.IsPrimitive() )
  1721. {
  1722. if( type.IsReadOnly() && expr.type.isConstant )
  1723. {
  1724. ImplicitConversion(&expr, type, node, asIC_IMPLICIT_CONV);
  1725. sVariable *v = variables->GetVariable(name.AddressOf());
  1726. v->isPureConstant = true;
  1727. v->constantValue = expr.type.qwordValue;
  1728. }
  1729. asSExprContext lctx(engine);
  1730. lctx.type.SetVariable(type, offset, false);
  1731. lctx.type.dataType.MakeReadOnly(false);
  1732. lctx.type.isLValue = true;
  1733. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  1734. ProcessDeferredParams(&ctx);
  1735. }
  1736. else
  1737. {
  1738. // TODO: runtime optimize: We can use a copy constructor here
  1739. sVariable *v = variables->GetVariable(name.AddressOf());
  1740. asSExprContext lexpr(engine);
  1741. lexpr.type.Set(type);
  1742. lexpr.type.dataType.MakeReference(v->onHeap);
  1743. // Allow initialization of constant variables
  1744. lexpr.type.dataType.MakeReadOnly(false);
  1745. if( type.IsObjectHandle() )
  1746. lexpr.type.isExplicitHandle = true;
  1747. lexpr.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1748. lexpr.type.stackOffset = (short)v->stackOffset;
  1749. lexpr.type.isVariable = true;
  1750. lexpr.type.isLValue = true;
  1751. // If left expression resolves into a registered type
  1752. // check if the assignment operator is overloaded, and check
  1753. // the type of the right hand expression. If none is found
  1754. // the default action is a direct copy if it is the same type
  1755. // and a simple assignment.
  1756. bool assigned = false;
  1757. // Even though an ASHANDLE can be an explicit handle the overloaded operator needs to be called
  1758. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  1759. {
  1760. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  1761. if( assigned )
  1762. {
  1763. // Pop the resulting value
  1764. ctx.bc.Instr(asBC_PopPtr);
  1765. // Release the argument
  1766. ProcessDeferredParams(&ctx);
  1767. // Release temporary variable that may be allocated by the overloaded operator
  1768. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1769. }
  1770. }
  1771. if( !assigned )
  1772. {
  1773. PrepareForAssignment(&lexpr.type.dataType, &expr, node, false);
  1774. // If the expression is constant and the variable also is constant
  1775. // then mark the variable as pure constant. This will allow the compiler
  1776. // to optimize expressions with this variable.
  1777. if( v->type.IsReadOnly() && expr.type.isConstant )
  1778. {
  1779. v->isPureConstant = true;
  1780. v->constantValue = expr.type.qwordValue;
  1781. }
  1782. // Add expression code to bytecode
  1783. MergeExprBytecode(&ctx, &expr);
  1784. // Add byte code for storing value of expression in variable
  1785. ctx.bc.AddCode(&lexpr.bc);
  1786. lexpr.type.stackOffset = (short)v->stackOffset;
  1787. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, node->prev);
  1788. // Release temporary variables used by expression
  1789. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  1790. ctx.bc.Instr(asBC_PopPtr);
  1791. ProcessDeferredParams(&ctx);
  1792. }
  1793. }
  1794. }
  1795. node = node->next;
  1796. bc->AddCode(&ctx.bc);
  1797. }
  1798. else
  1799. {
  1800. // Call the default constructor here if no explicit initialization is done
  1801. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), bc, varNode);
  1802. }
  1803. }
  1804. }
  1805. void asCCompiler::CompileInitList(asCTypeInfo *var, asCScriptNode *node, asCByteCode *bc)
  1806. {
  1807. // Check if the type supports initialization lists
  1808. if( var->dataType.GetObjectType() == 0 ||
  1809. var->dataType.GetBehaviour()->listFactory == 0 ||
  1810. var->dataType.IsObjectHandle() )
  1811. {
  1812. asCString str;
  1813. str.Format(TXT_INIT_LIST_CANNOT_BE_USED_WITH_s, var->dataType.Format().AddressOf());
  1814. Error(str.AddressOf(), node);
  1815. return;
  1816. }
  1817. // Count the number of elements and initialize the array with the correct size
  1818. int countElements = 0;
  1819. asCScriptNode *el = node->firstChild;
  1820. while( el )
  1821. {
  1822. countElements++;
  1823. el = el->next;
  1824. }
  1825. // Construct the array with the size elements
  1826. // TODO: value on stack: This needs to support value types on the stack as well
  1827. // Find the list factory
  1828. // TODO: initlist: Add support for value types as well
  1829. int funcId = var->dataType.GetBehaviour()->listFactory;
  1830. asCArray<asSExprContext *> args;
  1831. asSExprContext arg1(engine);
  1832. arg1.bc.InstrDWORD(asBC_PshC4, countElements);
  1833. arg1.type.Set(asCDataType::CreatePrimitive(ttUInt, false));
  1834. args.PushLast(&arg1);
  1835. asSExprContext ctx(engine);
  1836. PrepareFunctionCall(funcId, &ctx.bc, args);
  1837. MoveArgsToStack(funcId, &ctx.bc, args, false);
  1838. if( var->isVariable )
  1839. {
  1840. // Call factory and store the handle in the given variable
  1841. PerformFunctionCall(funcId, &ctx, false, &args, 0, true, var->stackOffset);
  1842. ctx.bc.Instr(asBC_PopPtr);
  1843. }
  1844. else
  1845. {
  1846. PerformFunctionCall(funcId, &ctx, false, &args);
  1847. // Store the returned handle in the global variable
  1848. ctx.bc.Instr(asBC_RDSPtr);
  1849. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  1850. ctx.bc.InstrPTR(asBC_REFCPY, var->dataType.GetObjectType());
  1851. ctx.bc.Instr(asBC_PopPtr);
  1852. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  1853. }
  1854. bc->AddCode(&ctx.bc);
  1855. // TODO: initlist: Should we have a special indexing operator for this? How can we support
  1856. // initialization lists with different types for different elements? Maybe
  1857. // by using the variable arguments the initialization can be done with one
  1858. // call, passing all the elements as arguments. The registered function can
  1859. // then traverse them however it wants.
  1860. // Find the indexing operator that is not read-only that will be used for all elements
  1861. asCDataType retType;
  1862. retType = var->dataType.GetSubType();
  1863. retType.MakeReference(true);
  1864. retType.MakeReadOnly(false);
  1865. funcId = 0;
  1866. for( asUINT n = 0; n < var->dataType.GetObjectType()->methods.GetLength(); n++ )
  1867. {
  1868. asCScriptFunction *desc = builder->GetFunctionDescription(var->dataType.GetObjectType()->methods[n]);
  1869. if( !desc->isReadOnly &&
  1870. desc->parameterTypes.GetLength() == 1 &&
  1871. (desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttUInt, false) ||
  1872. desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttInt, false)) &&
  1873. desc->returnType == retType &&
  1874. desc->name == "opIndex" )
  1875. {
  1876. funcId = var->dataType.GetObjectType()->methods[n];
  1877. break;
  1878. }
  1879. }
  1880. if( funcId == 0 )
  1881. {
  1882. Error(TXT_NO_APPROPRIATE_INDEX_OPERATOR, node);
  1883. return;
  1884. }
  1885. asUINT index = 0;
  1886. el = node->firstChild;
  1887. while( el )
  1888. {
  1889. if( el->nodeType == snAssignment || el->nodeType == snInitList )
  1890. {
  1891. asSExprContext lctx(engine);
  1892. asSExprContext rctx(engine);
  1893. if( el->nodeType == snAssignment )
  1894. {
  1895. // Compile the assignment expression
  1896. CompileAssignment(el, &rctx);
  1897. }
  1898. else if( el->nodeType == snInitList )
  1899. {
  1900. int offset = AllocateVariable(var->dataType.GetSubType(), true);
  1901. rctx.type.Set(var->dataType.GetSubType());
  1902. rctx.type.isVariable = true;
  1903. rctx.type.isTemporary = true;
  1904. rctx.type.stackOffset = (short)offset;
  1905. CompileInitList(&rctx.type, el, &rctx.bc);
  1906. // Put the object on the stack
  1907. rctx.bc.InstrSHORT(asBC_PSF, rctx.type.stackOffset);
  1908. // It is a reference that we place on the stack
  1909. rctx.type.dataType.MakeReference(true);
  1910. }
  1911. // Compile the lvalue
  1912. lctx.bc.InstrDWORD(asBC_PshC4, index);
  1913. if( var->isVariable )
  1914. lctx.bc.InstrSHORT(asBC_PSF, var->stackOffset);
  1915. else
  1916. lctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  1917. lctx.bc.Instr(asBC_RDSPtr);
  1918. lctx.bc.Call(asBC_CALLSYS, funcId, 1+AS_PTR_SIZE);
  1919. if( !var->dataType.GetSubType().IsPrimitive() )
  1920. lctx.bc.Instr(asBC_PshRPtr);
  1921. lctx.type.Set(var->dataType.GetSubType());
  1922. if( !lctx.type.dataType.IsObject() || lctx.type.dataType.IsObjectHandle() )
  1923. lctx.type.dataType.MakeReference(true);
  1924. // If the element type is handles, then we're expected to do handle assignments
  1925. if( lctx.type.dataType.IsObjectHandle() )
  1926. lctx.type.isExplicitHandle = true;
  1927. lctx.type.isLValue = true;
  1928. asSExprContext ctx(engine);
  1929. DoAssignment(&ctx, &lctx, &rctx, el, el, ttAssignment, el);
  1930. if( !lctx.type.dataType.IsPrimitive() )
  1931. ctx.bc.Instr(asBC_PopPtr);
  1932. // Release temporary variables used by expression
  1933. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1934. ProcessDeferredParams(&ctx);
  1935. bc->AddCode(&ctx.bc);
  1936. }
  1937. el = el->next;
  1938. index++;
  1939. }
  1940. }
  1941. void asCCompiler::CompileStatement(asCScriptNode *statement, bool *hasReturn, asCByteCode *bc)
  1942. {
  1943. *hasReturn = false;
  1944. if( statement->nodeType == snStatementBlock )
  1945. CompileStatementBlock(statement, true, hasReturn, bc);
  1946. else if( statement->nodeType == snIf )
  1947. CompileIfStatement(statement, hasReturn, bc);
  1948. else if( statement->nodeType == snFor )
  1949. CompileForStatement(statement, bc);
  1950. else if( statement->nodeType == snWhile )
  1951. CompileWhileStatement(statement, bc);
  1952. else if( statement->nodeType == snDoWhile )
  1953. CompileDoWhileStatement(statement, bc);
  1954. else if( statement->nodeType == snExpressionStatement )
  1955. CompileExpressionStatement(statement, bc);
  1956. else if( statement->nodeType == snBreak )
  1957. CompileBreakStatement(statement, bc);
  1958. else if( statement->nodeType == snContinue )
  1959. CompileContinueStatement(statement, bc);
  1960. else if( statement->nodeType == snSwitch )
  1961. CompileSwitchStatement(statement, hasReturn, bc);
  1962. else if( statement->nodeType == snReturn )
  1963. {
  1964. CompileReturnStatement(statement, bc);
  1965. *hasReturn = true;
  1966. }
  1967. }
  1968. void asCCompiler::CompileSwitchStatement(asCScriptNode *snode, bool *, asCByteCode *bc)
  1969. {
  1970. // TODO: inheritance: Must guarantee that all options in the switch case call a constructor, or that none call it.
  1971. // Reserve label for break statements
  1972. int breakLabel = nextLabel++;
  1973. breakLabels.PushLast(breakLabel);
  1974. // Add a variable scope that will be used by CompileBreak
  1975. // to know where to stop deallocating variables
  1976. AddVariableScope(true, false);
  1977. //---------------------------
  1978. // Compile the switch expression
  1979. //-------------------------------
  1980. // Compile the switch expression
  1981. asSExprContext expr(engine);
  1982. CompileAssignment(snode->firstChild, &expr);
  1983. // Verify that the expression is a primitive type
  1984. if( !expr.type.dataType.IsIntegerType() && !expr.type.dataType.IsUnsignedType() && !expr.type.dataType.IsEnumType() )
  1985. {
  1986. Error(TXT_SWITCH_MUST_BE_INTEGRAL, snode->firstChild);
  1987. return;
  1988. }
  1989. ProcessPropertyGetAccessor(&expr, snode);
  1990. // TODO: Need to support 64bit integers
  1991. // Convert the expression to a 32bit variable
  1992. asCDataType to;
  1993. if( expr.type.dataType.IsIntegerType() || expr.type.dataType.IsEnumType() )
  1994. to.SetTokenType(ttInt);
  1995. else if( expr.type.dataType.IsUnsignedType() )
  1996. to.SetTokenType(ttUInt);
  1997. // Make sure the value is in a variable
  1998. if( expr.type.dataType.IsReference() )
  1999. ConvertToVariable(&expr);
  2000. ImplicitConversion(&expr, to, snode->firstChild, asIC_IMPLICIT_CONV, true);
  2001. ConvertToVariable(&expr);
  2002. int offset = expr.type.stackOffset;
  2003. ProcessDeferredParams(&expr);
  2004. //-------------------------------
  2005. // Determine case values and labels
  2006. //--------------------------------
  2007. // Remember the first label so that we can later pass the
  2008. // correct label to each CompileCase()
  2009. int firstCaseLabel = nextLabel;
  2010. int defaultLabel = 0;
  2011. asCArray<int> caseValues;
  2012. asCArray<int> caseLabels;
  2013. // Compile all case comparisons and make them jump to the right label
  2014. asCScriptNode *cnode = snode->firstChild->next;
  2015. while( cnode )
  2016. {
  2017. // Each case should have a constant expression
  2018. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  2019. {
  2020. // Compile expression
  2021. asSExprContext c(engine);
  2022. CompileExpression(cnode->firstChild, &c);
  2023. // Verify that the result is a constant
  2024. if( !c.type.isConstant )
  2025. Error(TXT_SWITCH_CASE_MUST_BE_CONSTANT, cnode->firstChild);
  2026. // Verify that the result is an integral number
  2027. if( !c.type.dataType.IsIntegerType() && !c.type.dataType.IsUnsignedType() && !c.type.dataType.IsEnumType() )
  2028. Error(TXT_SWITCH_MUST_BE_INTEGRAL, cnode->firstChild);
  2029. ImplicitConversion(&c, to, cnode->firstChild, asIC_IMPLICIT_CONV, true);
  2030. // Has this case been declared already?
  2031. if( caseValues.IndexOf(c.type.intValue) >= 0 )
  2032. {
  2033. Error(TXT_DUPLICATE_SWITCH_CASE, cnode->firstChild);
  2034. }
  2035. // TODO: Optimize: We can insert the numbers sorted already
  2036. // Store constant for later use
  2037. caseValues.PushLast(c.type.intValue);
  2038. // Reserve label for this case
  2039. caseLabels.PushLast(nextLabel++);
  2040. }
  2041. else
  2042. {
  2043. // Is default the last case?
  2044. if( cnode->next )
  2045. {
  2046. Error(TXT_DEFAULT_MUST_BE_LAST, cnode);
  2047. break;
  2048. }
  2049. // Reserve label for this case
  2050. defaultLabel = nextLabel++;
  2051. }
  2052. cnode = cnode->next;
  2053. }
  2054. // check for empty switch
  2055. if (caseValues.GetLength() == 0)
  2056. {
  2057. Error(TXT_EMPTY_SWITCH, snode);
  2058. return;
  2059. }
  2060. if( defaultLabel == 0 )
  2061. defaultLabel = breakLabel;
  2062. //---------------------------------
  2063. // Output the optimized case comparisons
  2064. // with jumps to the case code
  2065. //------------------------------------
  2066. // Sort the case values by increasing value. Do the sort together with the labels
  2067. // A simple bubble sort is sufficient since we don't expect a huge number of values
  2068. for( asUINT fwd = 1; fwd < caseValues.GetLength(); fwd++ )
  2069. {
  2070. for( int bck = fwd - 1; bck >= 0; bck-- )
  2071. {
  2072. int bckp = bck + 1;
  2073. if( caseValues[bck] > caseValues[bckp] )
  2074. {
  2075. // Swap the values in both arrays
  2076. int swap = caseValues[bckp];
  2077. caseValues[bckp] = caseValues[bck];
  2078. caseValues[bck] = swap;
  2079. swap = caseLabels[bckp];
  2080. caseLabels[bckp] = caseLabels[bck];
  2081. caseLabels[bck] = swap;
  2082. }
  2083. else
  2084. break;
  2085. }
  2086. }
  2087. // Find ranges of consecutive numbers
  2088. asCArray<int> ranges;
  2089. ranges.PushLast(0);
  2090. asUINT n;
  2091. for( n = 1; n < caseValues.GetLength(); ++n )
  2092. {
  2093. // We can join numbers that are less than 5 numbers
  2094. // apart since the output code will still be smaller
  2095. if( caseValues[n] > caseValues[n-1] + 5 )
  2096. ranges.PushLast(n);
  2097. }
  2098. // If the value is larger than the largest case value, jump to default
  2099. int tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2100. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[caseValues.GetLength()-1]);
  2101. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2102. expr.bc.InstrDWORD(asBC_JP, defaultLabel);
  2103. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2104. // TODO: runtime optimize: We could possibly optimize this even more by doing a
  2105. // binary search instead of a linear search through the ranges
  2106. // For each range
  2107. int range;
  2108. for( range = 0; range < (int)ranges.GetLength(); range++ )
  2109. {
  2110. // Find the largest value in this range
  2111. int maxRange = caseValues[ranges[range]];
  2112. int index = ranges[range];
  2113. for( ; (index < (int)caseValues.GetLength()) && (caseValues[index] <= maxRange + 5); index++ )
  2114. maxRange = caseValues[index];
  2115. // If there are only 2 numbers then it is better to compare them directly
  2116. if( index - ranges[range] > 2 )
  2117. {
  2118. // If the value is smaller than the smallest case value in the range, jump to default
  2119. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2120. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  2121. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2122. expr.bc.InstrDWORD(asBC_JS, defaultLabel);
  2123. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2124. int nextRangeLabel = nextLabel++;
  2125. // If this is the last range we don't have to make this test
  2126. if( range < (int)ranges.GetLength() - 1 )
  2127. {
  2128. // If the value is larger than the largest case value in the range, jump to the next range
  2129. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2130. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, maxRange);
  2131. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2132. expr.bc.InstrDWORD(asBC_JP, nextRangeLabel);
  2133. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2134. }
  2135. // Jump forward according to the value
  2136. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2137. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  2138. expr.bc.InstrW_W_W(asBC_SUBi, tmpOffset, offset, tmpOffset);
  2139. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2140. expr.bc.JmpP(tmpOffset, maxRange - caseValues[ranges[range]]);
  2141. // Add the list of jumps to the correct labels (any holes, jump to default)
  2142. index = ranges[range];
  2143. for( int n = caseValues[index]; n <= maxRange; n++ )
  2144. {
  2145. if( caseValues[index] == n )
  2146. expr.bc.InstrINT(asBC_JMP, caseLabels[index++]);
  2147. else
  2148. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  2149. }
  2150. expr.bc.Label((short)nextRangeLabel);
  2151. }
  2152. else
  2153. {
  2154. // Simply make a comparison with each value
  2155. int n;
  2156. for( n = ranges[range]; n < index; ++n )
  2157. {
  2158. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2159. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[n]);
  2160. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2161. expr.bc.InstrDWORD(asBC_JZ, caseLabels[n]);
  2162. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2163. }
  2164. }
  2165. }
  2166. // Catch any value that falls trough
  2167. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  2168. // Release the temporary variable previously stored
  2169. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2170. //----------------------------------
  2171. // Output case implementations
  2172. //----------------------------------
  2173. // Compile case implementations, each one with the label before it
  2174. cnode = snode->firstChild->next;
  2175. while( cnode )
  2176. {
  2177. // Each case should have a constant expression
  2178. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  2179. {
  2180. expr.bc.Label((short)firstCaseLabel++);
  2181. CompileCase(cnode->firstChild->next, &expr.bc);
  2182. }
  2183. else
  2184. {
  2185. expr.bc.Label((short)defaultLabel);
  2186. // Is default the last case?
  2187. if( cnode->next )
  2188. {
  2189. // We've already reported this error
  2190. break;
  2191. }
  2192. CompileCase(cnode->firstChild, &expr.bc);
  2193. }
  2194. cnode = cnode->next;
  2195. }
  2196. //--------------------------------
  2197. bc->AddCode(&expr.bc);
  2198. // Add break label
  2199. bc->Label((short)breakLabel);
  2200. breakLabels.PopLast();
  2201. RemoveVariableScope();
  2202. }
  2203. void asCCompiler::CompileCase(asCScriptNode *node, asCByteCode *bc)
  2204. {
  2205. bool isFinished = false;
  2206. bool hasReturn = false;
  2207. while( node )
  2208. {
  2209. if( hasReturn || isFinished )
  2210. {
  2211. Warning(TXT_UNREACHABLE_CODE, node);
  2212. break;
  2213. }
  2214. if( node->nodeType == snBreak || node->nodeType == snContinue )
  2215. isFinished = true;
  2216. asCByteCode statement(engine);
  2217. if( node->nodeType == snDeclaration )
  2218. {
  2219. Error(TXT_DECL_IN_SWITCH, node);
  2220. // Compile it anyway to avoid further compiler errors
  2221. CompileDeclaration(node, &statement);
  2222. }
  2223. else
  2224. CompileStatement(node, &hasReturn, &statement);
  2225. LineInstr(bc, node->tokenPos);
  2226. bc->AddCode(&statement);
  2227. if( !hasCompileErrors )
  2228. asASSERT( tempVariables.GetLength() == 0 );
  2229. node = node->next;
  2230. }
  2231. }
  2232. void asCCompiler::CompileIfStatement(asCScriptNode *inode, bool *hasReturn, asCByteCode *bc)
  2233. {
  2234. // We will use one label for the if statement
  2235. // and possibly another for the else statement
  2236. int afterLabel = nextLabel++;
  2237. // Compile the expression
  2238. asSExprContext expr(engine);
  2239. CompileAssignment(inode->firstChild, &expr);
  2240. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2241. {
  2242. Error(TXT_EXPR_MUST_BE_BOOL, inode->firstChild);
  2243. expr.type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 1);
  2244. }
  2245. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2246. ProcessDeferredParams(&expr);
  2247. if( !expr.type.isConstant )
  2248. {
  2249. ProcessPropertyGetAccessor(&expr, inode);
  2250. ConvertToVariable(&expr);
  2251. // Add byte code from the expression
  2252. bc->AddCode(&expr.bc);
  2253. // Add a test
  2254. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2255. bc->Instr(asBC_ClrHi);
  2256. bc->InstrDWORD(asBC_JZ, afterLabel);
  2257. ReleaseTemporaryVariable(expr.type, bc);
  2258. }
  2259. else if( expr.type.dwordValue == 0 )
  2260. {
  2261. // Jump to the else case
  2262. bc->InstrINT(asBC_JMP, afterLabel);
  2263. // TODO: Should we warn that the expression will always go to the else?
  2264. }
  2265. // Compile the if statement
  2266. bool origIsConstructorCalled = m_isConstructorCalled;
  2267. bool hasReturn1;
  2268. asCByteCode ifBC(engine);
  2269. CompileStatement(inode->firstChild->next, &hasReturn1, &ifBC);
  2270. // Add the byte code
  2271. LineInstr(bc, inode->firstChild->next->tokenPos);
  2272. bc->AddCode(&ifBC);
  2273. if( inode->firstChild->next->nodeType == snExpressionStatement && inode->firstChild->next->firstChild == 0 )
  2274. {
  2275. // Don't allow if( expr );
  2276. Error(TXT_IF_WITH_EMPTY_STATEMENT, inode->firstChild->next);
  2277. }
  2278. // If one of the statements call the constructor, the other must as well
  2279. // otherwise it is possible the constructor is never called
  2280. bool constructorCall1 = false;
  2281. bool constructorCall2 = false;
  2282. if( !origIsConstructorCalled && m_isConstructorCalled )
  2283. constructorCall1 = true;
  2284. // Do we have an else statement?
  2285. if( inode->firstChild->next != inode->lastChild )
  2286. {
  2287. // Reset the constructor called flag so the else statement can call the constructor too
  2288. m_isConstructorCalled = origIsConstructorCalled;
  2289. int afterElse = 0;
  2290. if( !hasReturn1 )
  2291. {
  2292. afterElse = nextLabel++;
  2293. // Add jump to after the else statement
  2294. bc->InstrINT(asBC_JMP, afterElse);
  2295. }
  2296. // Add label for the else statement
  2297. bc->Label((short)afterLabel);
  2298. bool hasReturn2;
  2299. asCByteCode elseBC(engine);
  2300. CompileStatement(inode->lastChild, &hasReturn2, &elseBC);
  2301. // Add byte code for the else statement
  2302. LineInstr(bc, inode->lastChild->tokenPos);
  2303. bc->AddCode(&elseBC);
  2304. if( inode->lastChild->nodeType == snExpressionStatement && inode->lastChild->firstChild == 0 )
  2305. {
  2306. // Don't allow if( expr ) {} else;
  2307. Error(TXT_ELSE_WITH_EMPTY_STATEMENT, inode->lastChild);
  2308. }
  2309. if( !hasReturn1 )
  2310. {
  2311. // Add label for the end of else statement
  2312. bc->Label((short)afterElse);
  2313. }
  2314. // The if statement only has return if both alternatives have
  2315. *hasReturn = hasReturn1 && hasReturn2;
  2316. if( !origIsConstructorCalled && m_isConstructorCalled )
  2317. constructorCall2 = true;
  2318. }
  2319. else
  2320. {
  2321. // Add label for the end of if statement
  2322. bc->Label((short)afterLabel);
  2323. *hasReturn = false;
  2324. }
  2325. // Make sure both or neither conditions call a constructor
  2326. if( (constructorCall1 && !constructorCall2) ||
  2327. (constructorCall2 && !constructorCall1) )
  2328. {
  2329. Error(TXT_BOTH_CONDITIONS_MUST_CALL_CONSTRUCTOR, inode);
  2330. }
  2331. m_isConstructorCalled = origIsConstructorCalled || constructorCall1 || constructorCall2;
  2332. }
  2333. void asCCompiler::CompileForStatement(asCScriptNode *fnode, asCByteCode *bc)
  2334. {
  2335. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2336. AddVariableScope(true, true);
  2337. // We will use three labels for the for loop
  2338. int conditionLabel = nextLabel++;
  2339. int afterLabel = nextLabel++;
  2340. int continueLabel = nextLabel++;
  2341. int insideLabel = nextLabel++;
  2342. continueLabels.PushLast(continueLabel);
  2343. breakLabels.PushLast(afterLabel);
  2344. //---------------------------------------
  2345. // Compile the initialization statement
  2346. asCByteCode initBC(engine);
  2347. if( fnode->firstChild->nodeType == snDeclaration )
  2348. CompileDeclaration(fnode->firstChild, &initBC);
  2349. else
  2350. CompileExpressionStatement(fnode->firstChild, &initBC);
  2351. //-----------------------------------
  2352. // Compile the condition statement
  2353. asSExprContext expr(engine);
  2354. asCScriptNode *second = fnode->firstChild->next;
  2355. if( second->firstChild )
  2356. {
  2357. int r = CompileAssignment(second->firstChild, &expr);
  2358. if( r >= 0 )
  2359. {
  2360. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2361. Error(TXT_EXPR_MUST_BE_BOOL, second);
  2362. else
  2363. {
  2364. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2365. ProcessDeferredParams(&expr);
  2366. ProcessPropertyGetAccessor(&expr, second);
  2367. // If expression is false exit the loop
  2368. ConvertToVariable(&expr);
  2369. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2370. expr.bc.Instr(asBC_ClrHi);
  2371. expr.bc.InstrDWORD(asBC_JNZ, insideLabel);
  2372. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2373. }
  2374. }
  2375. }
  2376. //---------------------------
  2377. // Compile the increment statement
  2378. asCByteCode nextBC(engine);
  2379. asCScriptNode *third = second->next;
  2380. if( third->nodeType == snExpressionStatement )
  2381. CompileExpressionStatement(third, &nextBC);
  2382. //------------------------------
  2383. // Compile loop statement
  2384. bool hasReturn;
  2385. asCByteCode forBC(engine);
  2386. CompileStatement(fnode->lastChild, &hasReturn, &forBC);
  2387. //-------------------------------
  2388. // Join the code pieces
  2389. bc->AddCode(&initBC);
  2390. bc->InstrDWORD(asBC_JMP, conditionLabel);
  2391. bc->Label((short)insideLabel);
  2392. // Add a suspend bytecode inside the loop to guarantee
  2393. // that the application can suspend the execution
  2394. bc->Instr(asBC_SUSPEND);
  2395. bc->InstrPTR(asBC_JitEntry, 0);
  2396. LineInstr(bc, fnode->lastChild->tokenPos);
  2397. bc->AddCode(&forBC);
  2398. bc->Label((short)continueLabel);
  2399. bc->AddCode(&nextBC);
  2400. bc->Label((short)conditionLabel);
  2401. if( expr.bc.GetLastInstr() == -1 )
  2402. // There is no condition, so we just always jump
  2403. bc->InstrDWORD(asBC_JMP, insideLabel);
  2404. else
  2405. bc->AddCode(&expr.bc);
  2406. bc->Label((short)afterLabel);
  2407. continueLabels.PopLast();
  2408. breakLabels.PopLast();
  2409. // Deallocate variables in this block, in reverse order
  2410. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  2411. {
  2412. sVariable *v = variables->variables[n];
  2413. // Call variable destructors here, for variables not yet destroyed
  2414. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  2415. // Don't deallocate function parameters
  2416. if( v->stackOffset > 0 )
  2417. DeallocateVariable(v->stackOffset);
  2418. }
  2419. RemoveVariableScope();
  2420. }
  2421. void asCCompiler::CompileWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2422. {
  2423. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2424. AddVariableScope(true, true);
  2425. // We will use two labels for the while loop
  2426. int beforeLabel = nextLabel++;
  2427. int afterLabel = nextLabel++;
  2428. continueLabels.PushLast(beforeLabel);
  2429. breakLabels.PushLast(afterLabel);
  2430. // Add label before the expression
  2431. bc->Label((short)beforeLabel);
  2432. // Compile expression
  2433. asSExprContext expr(engine);
  2434. CompileAssignment(wnode->firstChild, &expr);
  2435. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2436. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2437. else
  2438. {
  2439. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2440. ProcessDeferredParams(&expr);
  2441. ProcessPropertyGetAccessor(&expr, wnode);
  2442. // Add byte code for the expression
  2443. ConvertToVariable(&expr);
  2444. bc->AddCode(&expr.bc);
  2445. // Jump to end of statement if expression is false
  2446. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2447. bc->Instr(asBC_ClrHi);
  2448. bc->InstrDWORD(asBC_JZ, afterLabel);
  2449. ReleaseTemporaryVariable(expr.type, bc);
  2450. }
  2451. // Add a suspend bytecode inside the loop to guarantee
  2452. // that the application can suspend the execution
  2453. bc->Instr(asBC_SUSPEND);
  2454. bc->InstrPTR(asBC_JitEntry, 0);
  2455. // Compile statement
  2456. bool hasReturn;
  2457. asCByteCode whileBC(engine);
  2458. CompileStatement(wnode->lastChild, &hasReturn, &whileBC);
  2459. // Add byte code for the statement
  2460. LineInstr(bc, wnode->lastChild->tokenPos);
  2461. bc->AddCode(&whileBC);
  2462. // Jump to the expression
  2463. bc->InstrINT(asBC_JMP, beforeLabel);
  2464. // Add label after the statement
  2465. bc->Label((short)afterLabel);
  2466. continueLabels.PopLast();
  2467. breakLabels.PopLast();
  2468. RemoveVariableScope();
  2469. }
  2470. void asCCompiler::CompileDoWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2471. {
  2472. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2473. AddVariableScope(true, true);
  2474. // We will use two labels for the while loop
  2475. int beforeLabel = nextLabel++;
  2476. int beforeTest = nextLabel++;
  2477. int afterLabel = nextLabel++;
  2478. continueLabels.PushLast(beforeTest);
  2479. breakLabels.PushLast(afterLabel);
  2480. // Add label before the statement
  2481. bc->Label((short)beforeLabel);
  2482. // Compile statement
  2483. bool hasReturn;
  2484. asCByteCode whileBC(engine);
  2485. CompileStatement(wnode->firstChild, &hasReturn, &whileBC);
  2486. // Add byte code for the statement
  2487. LineInstr(bc, wnode->firstChild->tokenPos);
  2488. bc->AddCode(&whileBC);
  2489. // Add label before the expression
  2490. bc->Label((short)beforeTest);
  2491. // Add a suspend bytecode inside the loop to guarantee
  2492. // that the application can suspend the execution
  2493. bc->Instr(asBC_SUSPEND);
  2494. bc->InstrPTR(asBC_JitEntry, 0);
  2495. // Add a line instruction
  2496. LineInstr(bc, wnode->lastChild->tokenPos);
  2497. // Compile expression
  2498. asSExprContext expr(engine);
  2499. CompileAssignment(wnode->lastChild, &expr);
  2500. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2501. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2502. else
  2503. {
  2504. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2505. ProcessDeferredParams(&expr);
  2506. ProcessPropertyGetAccessor(&expr, wnode);
  2507. // Add byte code for the expression
  2508. ConvertToVariable(&expr);
  2509. bc->AddCode(&expr.bc);
  2510. // Jump to next iteration if expression is true
  2511. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2512. bc->Instr(asBC_ClrHi);
  2513. bc->InstrDWORD(asBC_JNZ, beforeLabel);
  2514. ReleaseTemporaryVariable(expr.type, bc);
  2515. }
  2516. // Add label after the statement
  2517. bc->Label((short)afterLabel);
  2518. continueLabels.PopLast();
  2519. breakLabels.PopLast();
  2520. RemoveVariableScope();
  2521. }
  2522. void asCCompiler::CompileBreakStatement(asCScriptNode *node, asCByteCode *bc)
  2523. {
  2524. if( breakLabels.GetLength() == 0 )
  2525. {
  2526. Error(TXT_INVALID_BREAK, node);
  2527. return;
  2528. }
  2529. // Add destructor calls for all variables that will go out of scope
  2530. // Put this clean up in a block to allow exception handler to understand them
  2531. bc->Block(true);
  2532. asCVariableScope *vs = variables;
  2533. while( !vs->isBreakScope )
  2534. {
  2535. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2536. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2537. vs = vs->parent;
  2538. }
  2539. bc->Block(false);
  2540. bc->InstrINT(asBC_JMP, breakLabels[breakLabels.GetLength()-1]);
  2541. }
  2542. void asCCompiler::CompileContinueStatement(asCScriptNode *node, asCByteCode *bc)
  2543. {
  2544. if( continueLabels.GetLength() == 0 )
  2545. {
  2546. Error(TXT_INVALID_CONTINUE, node);
  2547. return;
  2548. }
  2549. // Add destructor calls for all variables that will go out of scope
  2550. // Put this clean up in a block to allow exception handler to understand them
  2551. bc->Block(true);
  2552. asCVariableScope *vs = variables;
  2553. while( !vs->isContinueScope )
  2554. {
  2555. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2556. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2557. vs = vs->parent;
  2558. }
  2559. bc->Block(false);
  2560. bc->InstrINT(asBC_JMP, continueLabels[continueLabels.GetLength()-1]);
  2561. }
  2562. void asCCompiler::CompileExpressionStatement(asCScriptNode *enode, asCByteCode *bc)
  2563. {
  2564. if( enode->firstChild )
  2565. {
  2566. // Compile the expression
  2567. asSExprContext expr(engine);
  2568. CompileAssignment(enode->firstChild, &expr);
  2569. // If we get here and there is still an unprocessed property
  2570. // accessor, then process it as a get access. Don't call if there is
  2571. // already a compile error, or we might report an error that is not valid
  2572. if( !hasCompileErrors )
  2573. ProcessPropertyGetAccessor(&expr, enode);
  2574. // Pop the value from the stack
  2575. if( !expr.type.dataType.IsPrimitive() )
  2576. expr.bc.Instr(asBC_PopPtr);
  2577. // Release temporary variables used by expression
  2578. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2579. ProcessDeferredParams(&expr);
  2580. bc->AddCode(&expr.bc);
  2581. }
  2582. }
  2583. void asCCompiler::PrepareTemporaryObject(asCScriptNode *node, asSExprContext *ctx, bool forceOnHeap)
  2584. {
  2585. // If the object already is stored in temporary variable then nothing needs to be done
  2586. // Note, a type can be temporary without being a variable, in which case it is holding off
  2587. // on releasing a previously used object.
  2588. if( ctx->type.isTemporary && ctx->type.isVariable &&
  2589. !(forceOnHeap && !IsVariableOnHeap(ctx->type.stackOffset)) )
  2590. {
  2591. // If the temporary object is currently not a reference
  2592. // the expression needs to be reevaluated to a reference
  2593. if( !ctx->type.dataType.IsReference() )
  2594. {
  2595. ctx->bc.Instr(asBC_PopPtr);
  2596. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  2597. ctx->type.dataType.MakeReference(true);
  2598. }
  2599. return;
  2600. }
  2601. // Allocate temporary variable
  2602. asCDataType dt = ctx->type.dataType;
  2603. dt.MakeReference(false);
  2604. dt.MakeReadOnly(false);
  2605. int offset = AllocateVariable(dt, true, forceOnHeap);
  2606. // Objects stored on the stack are not considered references
  2607. dt.MakeReference(IsVariableOnHeap(offset));
  2608. asCTypeInfo lvalue;
  2609. lvalue.Set(dt);
  2610. lvalue.isTemporary = true;
  2611. lvalue.stackOffset = (short)offset;
  2612. lvalue.isVariable = true;
  2613. lvalue.isExplicitHandle = ctx->type.isExplicitHandle;
  2614. if( !dt.IsObjectHandle() &&
  2615. dt.GetObjectType() && (dt.GetBehaviour()->copyconstruct || dt.GetBehaviour()->copyfactory) )
  2616. {
  2617. PrepareForAssignment(&lvalue.dataType, ctx, node, true);
  2618. // Use the copy constructor/factory when available
  2619. CallCopyConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, ctx, node);
  2620. }
  2621. else
  2622. {
  2623. // Allocate and construct the temporary object
  2624. int r = CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, node);
  2625. if( r < 0 )
  2626. {
  2627. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  2628. }
  2629. else
  2630. {
  2631. // Assign the object to the temporary variable
  2632. PrepareForAssignment(&lvalue.dataType, ctx, node, true);
  2633. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2634. r = PerformAssignment(&lvalue, &ctx->type, &ctx->bc, node);
  2635. if( r < 0 )
  2636. {
  2637. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  2638. }
  2639. // Pop the original reference
  2640. ctx->bc.Instr(asBC_PopPtr);
  2641. }
  2642. }
  2643. // If the expression was holding off on releasing a
  2644. // previously used object, we need to release it now
  2645. if( ctx->type.isTemporary )
  2646. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  2647. // Push the reference to the temporary variable on the stack
  2648. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2649. lvalue.dataType.MakeReference(IsVariableOnHeap(offset));
  2650. ctx->type = lvalue;
  2651. }
  2652. void asCCompiler::CompileReturnStatement(asCScriptNode *rnode, asCByteCode *bc)
  2653. {
  2654. // Get return type and location
  2655. sVariable *v = variables->GetVariable("return");
  2656. // Basic validations
  2657. if( v->type.GetSizeOnStackDWords() > 0 && !rnode->firstChild )
  2658. {
  2659. Error(TXT_MUST_RETURN_VALUE, rnode);
  2660. return;
  2661. }
  2662. else if( v->type.GetSizeOnStackDWords() == 0 && rnode->firstChild )
  2663. {
  2664. Error(TXT_CANT_RETURN_VALUE, rnode);
  2665. return;
  2666. }
  2667. // Compile the expression
  2668. if( rnode->firstChild )
  2669. {
  2670. // Compile the expression
  2671. asSExprContext expr(engine);
  2672. int r = CompileAssignment(rnode->firstChild, &expr);
  2673. if( r < 0 ) return;
  2674. if( v->type.IsReference() )
  2675. {
  2676. // The expression that gives the reference must not use any of the
  2677. // variables that must be destroyed upon exit, because then it means
  2678. // reference will stay alive while the clean-up is done, which could
  2679. // potentially mean that the reference is invalidated by the clean-up.
  2680. //
  2681. // When the function is returning a reference, the clean-up of the
  2682. // variables must be done before the evaluation of the expression.
  2683. //
  2684. // A reference to a global variable, or a class member for class methods
  2685. // should be allowed to be returned.
  2686. if( !(expr.type.dataType.IsReference() ||
  2687. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle())) )
  2688. {
  2689. // Clean up the potential deferred parameters
  2690. ProcessDeferredParams(&expr);
  2691. Error(TXT_NOT_VALID_REFERENCE, rnode);
  2692. return;
  2693. }
  2694. // No references to local variables, temporary variables, or parameters
  2695. // are allowed to be returned, since they go out of scope when the function
  2696. // returns. Even reference parameters are disallowed, since it is not possible
  2697. // to know the scope of them. The exception is the 'this' pointer, which
  2698. // is treated by the compiler as a local variable, but isn't really so.
  2699. if( (expr.type.isVariable && !(expr.type.stackOffset == 0 && outFunc->objectType)) || expr.type.isTemporary )
  2700. {
  2701. // Clean up the potential deferred parameters
  2702. ProcessDeferredParams(&expr);
  2703. Error(TXT_CANNOT_RETURN_REF_TO_LOCAL, rnode);
  2704. return;
  2705. }
  2706. // The type must match exactly as we cannot convert
  2707. // the reference without loosing the original value
  2708. if( !(v->type == expr.type.dataType ||
  2709. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle() && v->type.IsEqualExceptRef(expr.type.dataType))) )
  2710. {
  2711. // Clean up the potential deferred parameters
  2712. ProcessDeferredParams(&expr);
  2713. asCString str;
  2714. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2715. Error(str.AddressOf(), rnode);
  2716. return;
  2717. }
  2718. // The expression must not have any deferred expressions, because the evaluation
  2719. // of these cannot be done without keeping the reference which is not safe
  2720. if( expr.deferredParams.GetLength() )
  2721. {
  2722. // Clean up the potential deferred parameters
  2723. ProcessDeferredParams(&expr);
  2724. Error(TXT_REF_CANT_BE_RETURNED_DEFERRED_PARAM, rnode);
  2725. return;
  2726. }
  2727. // Make sure the expression isn't using any local variables that
  2728. // will need to be cleaned up before the function completes
  2729. asCArray<int> usedVars;
  2730. expr.bc.GetVarsUsed(usedVars);
  2731. for( asUINT n = 0; n < usedVars.GetLength(); n++ )
  2732. {
  2733. int var = GetVariableSlot(usedVars[n]);
  2734. if( var != -1 )
  2735. {
  2736. asCDataType dt = variableAllocations[var];
  2737. if( dt.IsObject() )
  2738. {
  2739. ProcessDeferredParams(&expr);
  2740. Error(TXT_REF_CANT_BE_RETURNED_LOCAL_VARS, rnode);
  2741. return;
  2742. }
  2743. }
  2744. }
  2745. // All objects in the function must be cleaned up before the expression
  2746. // is evaluated, otherwise there is a possibility that the cleanup will
  2747. // invalidate the reference.
  2748. // Destroy the local variables before loading
  2749. // the reference into the register. This will
  2750. // be done before the expression is evaluated.
  2751. DestroyVariables(bc);
  2752. // For primitives the reference is already in the register,
  2753. // but for non-primitives the reference is on the stack so we
  2754. // need to load it into the register
  2755. if( !expr.type.dataType.IsPrimitive() )
  2756. {
  2757. if( !expr.type.dataType.IsObjectHandle() &&
  2758. expr.type.dataType.IsReference() )
  2759. expr.bc.Instr(asBC_RDSPtr);
  2760. expr.bc.Instr(asBC_PopRPtr);
  2761. }
  2762. // There are no temporaries to release so we're done
  2763. }
  2764. else // if( !v->type.IsReference() )
  2765. {
  2766. ProcessPropertyGetAccessor(&expr, rnode);
  2767. // Prepare the value for assignment
  2768. IsVariableInitialized(&expr.type, rnode->firstChild);
  2769. if( v->type.IsPrimitive() )
  2770. {
  2771. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2772. // Implicitly convert the value to the return type
  2773. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  2774. // Verify that the conversion was successful
  2775. if( expr.type.dataType != v->type )
  2776. {
  2777. asCString str;
  2778. str.Format(TXT_NO_CONVERSION_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2779. Error(str.AddressOf(), rnode);
  2780. return;
  2781. }
  2782. else
  2783. {
  2784. ConvertToVariable(&expr);
  2785. // Clean up the local variables and process deferred parameters
  2786. DestroyVariables(&expr.bc);
  2787. ProcessDeferredParams(&expr);
  2788. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2789. // Load the variable in the register
  2790. if( v->type.GetSizeOnStackDWords() == 1 )
  2791. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2792. else
  2793. expr.bc.InstrSHORT(asBC_CpyVtoR8, expr.type.stackOffset);
  2794. }
  2795. }
  2796. else if( v->type.IsObject() )
  2797. {
  2798. // Value types are returned on the stack, in a location
  2799. // that has been reserved by the calling function.
  2800. if( outFunc->DoesReturnOnStack() )
  2801. {
  2802. // TODO: runtime optimize: If the return type has a constructor that takes the type of the expression,
  2803. // it should be called directly instead of first converting the expression and
  2804. // then copy the value.
  2805. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  2806. {
  2807. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  2808. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  2809. {
  2810. asCString str;
  2811. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2812. Error(str.AddressOf(), rnode->firstChild);
  2813. return;
  2814. }
  2815. }
  2816. int offset = outFunc->objectType ? -AS_PTR_SIZE : 0;
  2817. if( v->type.GetObjectType()->beh.copyconstruct )
  2818. {
  2819. PrepareForAssignment(&v->type, &expr, rnode->firstChild, false);
  2820. CallCopyConstructor(v->type, offset, false, &expr.bc, &expr, rnode->firstChild, false, true);
  2821. }
  2822. else
  2823. {
  2824. // If the copy constructor doesn't exist, then a manual assignment needs to be done instead.
  2825. CallDefaultConstructor(v->type, offset, false, &expr.bc, rnode->firstChild, false, true);
  2826. PrepareForAssignment(&v->type, &expr, rnode->firstChild, false);
  2827. expr.bc.InstrSHORT(asBC_PSF, (short)offset);
  2828. expr.bc.Instr(asBC_RDSPtr);
  2829. asSExprContext lexpr(engine);
  2830. lexpr.type.Set(v->type);
  2831. lexpr.type.isLValue = true;
  2832. PerformAssignment(&lexpr.type, &expr.type, &expr.bc, rnode->firstChild);
  2833. expr.bc.Instr(asBC_PopPtr);
  2834. // Release any temporary variable
  2835. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2836. }
  2837. // Clean up the local variables and process deferred parameters
  2838. DestroyVariables(&expr.bc);
  2839. ProcessDeferredParams(&expr);
  2840. }
  2841. else
  2842. {
  2843. asASSERT( v->type.GetObjectType()->flags & asOBJ_REF );
  2844. // Prepare the expression to be loaded into the object
  2845. // register. This will place the reference in local variable
  2846. PrepareArgument(&v->type, &expr, rnode->firstChild, false, 0);
  2847. // Pop the reference to the temporary variable
  2848. expr.bc.Instr(asBC_PopPtr);
  2849. // Clean up the local variables and process deferred parameters
  2850. DestroyVariables(&expr.bc);
  2851. ProcessDeferredParams(&expr);
  2852. // Load the object pointer into the object register
  2853. // LOADOBJ also clears the address in the variable
  2854. expr.bc.InstrSHORT(asBC_LOADOBJ, expr.type.stackOffset);
  2855. // LOADOBJ cleared the address in the variable so the object will not be freed
  2856. // here, but the temporary variable must still be freed so the slot can be reused
  2857. // By releasing without the bytecode we do just that.
  2858. ReleaseTemporaryVariable(expr.type, 0);
  2859. }
  2860. }
  2861. }
  2862. bc->AddCode(&expr.bc);
  2863. }
  2864. else
  2865. {
  2866. // For functions that don't return anything
  2867. // we just detroy the local variables
  2868. DestroyVariables(bc);
  2869. }
  2870. // Jump to the end of the function
  2871. bc->InstrINT(asBC_JMP, 0);
  2872. }
  2873. void asCCompiler::DestroyVariables(asCByteCode *bc)
  2874. {
  2875. // Call destructor on all variables except for the function parameters
  2876. // Put the clean-up in a block to allow exception handler to understand this
  2877. bc->Block(true);
  2878. asCVariableScope *vs = variables;
  2879. while( vs )
  2880. {
  2881. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2882. if( vs->variables[n]->stackOffset > 0 )
  2883. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2884. vs = vs->parent;
  2885. }
  2886. bc->Block(false);
  2887. }
  2888. void asCCompiler::AddVariableScope(bool isBreakScope, bool isContinueScope)
  2889. {
  2890. variables = asNEW(asCVariableScope)(variables);
  2891. variables->isBreakScope = isBreakScope;
  2892. variables->isContinueScope = isContinueScope;
  2893. }
  2894. void asCCompiler::RemoveVariableScope()
  2895. {
  2896. if( variables )
  2897. {
  2898. asCVariableScope *var = variables;
  2899. variables = variables->parent;
  2900. asDELETE(var,asCVariableScope);
  2901. }
  2902. }
  2903. void asCCompiler::Error(const char *msg, asCScriptNode *node)
  2904. {
  2905. asCString str;
  2906. int r = 0, c = 0;
  2907. asASSERT( node );
  2908. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2909. builder->WriteError(script->name.AddressOf(), msg, r, c);
  2910. hasCompileErrors = true;
  2911. }
  2912. void asCCompiler::Warning(const char *msg, asCScriptNode *node)
  2913. {
  2914. asCString str;
  2915. int r = 0, c = 0;
  2916. asASSERT( node );
  2917. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2918. builder->WriteWarning(script->name.AddressOf(), msg, r, c);
  2919. }
  2920. void asCCompiler::Information(const char *msg, asCScriptNode *node)
  2921. {
  2922. asCString str;
  2923. int r = 0, c = 0;
  2924. asASSERT( node );
  2925. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2926. builder->WriteInfo(script->name.AddressOf(), msg, r, c, false);
  2927. }
  2928. void asCCompiler::PrintMatchingFuncs(asCArray<int> &funcs, asCScriptNode *node)
  2929. {
  2930. int r = 0, c = 0;
  2931. asASSERT( node );
  2932. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2933. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  2934. {
  2935. asIScriptFunction *func = builder->GetFunctionDescription(funcs[n]);
  2936. builder->WriteInfo(script->name.AddressOf(), func->GetDeclaration(true), r, c, false);
  2937. }
  2938. }
  2939. int asCCompiler::AllocateVariableNotIn(const asCDataType &type, bool isTemporary, bool forceOnHeap, asSExprContext *ctx)
  2940. {
  2941. int l = int(reservedVariables.GetLength());
  2942. ctx->bc.GetVarsUsed(reservedVariables);
  2943. int var = AllocateVariable(type, isTemporary, forceOnHeap);
  2944. reservedVariables.SetLength(l);
  2945. return var;
  2946. }
  2947. int asCCompiler::AllocateVariable(const asCDataType &type, bool isTemporary, bool forceOnHeap)
  2948. {
  2949. asCDataType t(type);
  2950. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 1 )
  2951. t.SetTokenType(ttInt);
  2952. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 2 )
  2953. t.SetTokenType(ttDouble);
  2954. // Only null handles have the token type unrecognized token
  2955. asASSERT( t.IsObjectHandle() || t.GetTokenType() != ttUnrecognizedToken );
  2956. bool isOnHeap = true;
  2957. if( t.IsPrimitive() ||
  2958. (t.GetObjectType() && (t.GetObjectType()->GetFlags() & asOBJ_VALUE) && !forceOnHeap) )
  2959. {
  2960. // Primitives and value types (unless overridden) are allocated on the stack
  2961. isOnHeap = false;
  2962. }
  2963. // Find a free location with the same type
  2964. for( asUINT n = 0; n < freeVariables.GetLength(); n++ )
  2965. {
  2966. int slot = freeVariables[n];
  2967. if( variableAllocations[slot].IsEqualExceptConst(t) &&
  2968. variableIsTemporary[slot] == isTemporary &&
  2969. variableIsOnHeap[slot] == isOnHeap )
  2970. {
  2971. // We can't return by slot, must count variable sizes
  2972. int offset = GetVariableOffset(slot);
  2973. // Verify that it is not in the list of reserved variables
  2974. bool isUsed = false;
  2975. if( reservedVariables.GetLength() )
  2976. isUsed = reservedVariables.Exists(offset);
  2977. if( !isUsed )
  2978. {
  2979. if( n != freeVariables.GetLength() - 1 )
  2980. freeVariables[n] = freeVariables.PopLast();
  2981. else
  2982. freeVariables.PopLast();
  2983. if( isTemporary )
  2984. tempVariables.PushLast(offset);
  2985. return offset;
  2986. }
  2987. }
  2988. }
  2989. variableAllocations.PushLast(t);
  2990. variableIsTemporary.PushLast(isTemporary);
  2991. variableIsOnHeap.PushLast(isOnHeap);
  2992. int offset = GetVariableOffset((int)variableAllocations.GetLength()-1);
  2993. if( isTemporary )
  2994. tempVariables.PushLast(offset);
  2995. return offset;
  2996. }
  2997. int asCCompiler::GetVariableOffset(int varIndex)
  2998. {
  2999. // Return offset to the last dword on the stack
  3000. int varOffset = 1;
  3001. for( int n = 0; n < varIndex; n++ )
  3002. {
  3003. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  3004. varOffset += variableAllocations[n].GetSizeInMemoryDWords();
  3005. else
  3006. varOffset += variableAllocations[n].GetSizeOnStackDWords();
  3007. }
  3008. if( varIndex < (int)variableAllocations.GetLength() )
  3009. {
  3010. int size;
  3011. if( !variableIsOnHeap[varIndex] && variableAllocations[varIndex].IsObject() )
  3012. size = variableAllocations[varIndex].GetSizeInMemoryDWords();
  3013. else
  3014. size = variableAllocations[varIndex].GetSizeOnStackDWords();
  3015. if( size > 1 )
  3016. varOffset += size-1;
  3017. }
  3018. return varOffset;
  3019. }
  3020. int asCCompiler::GetVariableSlot(int offset)
  3021. {
  3022. int varOffset = 1;
  3023. for( asUINT n = 0; n < variableAllocations.GetLength(); n++ )
  3024. {
  3025. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  3026. varOffset += -1 + variableAllocations[n].GetSizeInMemoryDWords();
  3027. else
  3028. varOffset += -1 + variableAllocations[n].GetSizeOnStackDWords();
  3029. if( varOffset == offset )
  3030. return n;
  3031. varOffset++;
  3032. }
  3033. return -1;
  3034. }
  3035. bool asCCompiler::IsVariableOnHeap(int offset)
  3036. {
  3037. int varSlot = GetVariableSlot(offset);
  3038. if( varSlot < 0 )
  3039. {
  3040. // This happens for function arguments that are considered as on the heap
  3041. return true;
  3042. }
  3043. return variableIsOnHeap[varSlot];
  3044. }
  3045. void asCCompiler::DeallocateVariable(int offset)
  3046. {
  3047. // Remove temporary variable
  3048. int n;
  3049. for( n = 0; n < (int)tempVariables.GetLength(); n++ )
  3050. {
  3051. if( offset == tempVariables[n] )
  3052. {
  3053. if( n == (int)tempVariables.GetLength()-1 )
  3054. tempVariables.PopLast();
  3055. else
  3056. tempVariables[n] = tempVariables.PopLast();
  3057. break;
  3058. }
  3059. }
  3060. n = GetVariableSlot(offset);
  3061. if( n != -1 )
  3062. {
  3063. freeVariables.PushLast(n);
  3064. return;
  3065. }
  3066. // We might get here if the variable was implicitly declared
  3067. // because it was use before a formal declaration, in this case
  3068. // the offset is 0x7FFF
  3069. asASSERT(offset == 0x7FFF);
  3070. }
  3071. void asCCompiler::ReleaseTemporaryVariable(asCTypeInfo &t, asCByteCode *bc)
  3072. {
  3073. if( t.isTemporary )
  3074. {
  3075. ReleaseTemporaryVariable(t.stackOffset, bc);
  3076. t.isTemporary = false;
  3077. }
  3078. }
  3079. void asCCompiler::ReleaseTemporaryVariable(int offset, asCByteCode *bc)
  3080. {
  3081. if( bc )
  3082. {
  3083. // We need to call the destructor on the true variable type
  3084. int n = GetVariableSlot(offset);
  3085. asASSERT( n >= 0 );
  3086. if( n >= 0 )
  3087. {
  3088. asCDataType dt = variableAllocations[n];
  3089. bool isOnHeap = variableIsOnHeap[n];
  3090. // Call destructor
  3091. CallDestructor(dt, offset, isOnHeap, bc);
  3092. }
  3093. }
  3094. DeallocateVariable(offset);
  3095. }
  3096. void asCCompiler::Dereference(asSExprContext *ctx, bool generateCode)
  3097. {
  3098. if( ctx->type.dataType.IsReference() )
  3099. {
  3100. if( ctx->type.dataType.IsObject() )
  3101. {
  3102. ctx->type.dataType.MakeReference(false);
  3103. if( generateCode )
  3104. ctx->bc.Instr(asBC_RDSPtr);
  3105. }
  3106. else
  3107. {
  3108. // This should never happen as primitives are treated differently
  3109. asASSERT(false);
  3110. }
  3111. }
  3112. }
  3113. bool asCCompiler::IsVariableInitialized(asCTypeInfo *type, asCScriptNode *node)
  3114. {
  3115. // Temporary variables are assumed to be initialized
  3116. if( type->isTemporary ) return true;
  3117. // Verify that it is a variable
  3118. if( !type->isVariable ) return true;
  3119. // Find the variable
  3120. sVariable *v = variables->GetVariableByOffset(type->stackOffset);
  3121. // The variable isn't found if it is a constant, in which case it is guaranteed to be initialized
  3122. if( v == 0 ) return true;
  3123. if( v->isInitialized ) return true;
  3124. // Complex types don't need this test
  3125. if( v->type.IsObject() ) return true;
  3126. // Mark as initialized so that the user will not be bothered again
  3127. v->isInitialized = true;
  3128. // Write warning
  3129. asCString str;
  3130. str.Format(TXT_s_NOT_INITIALIZED, (const char *)v->name.AddressOf());
  3131. Warning(str.AddressOf(), node);
  3132. return false;
  3133. }
  3134. void asCCompiler::PrepareOperand(asSExprContext *ctx, asCScriptNode *node)
  3135. {
  3136. // Check if the variable is initialized (if it indeed is a variable)
  3137. IsVariableInitialized(&ctx->type, node);
  3138. asCDataType to = ctx->type.dataType;
  3139. to.MakeReference(false);
  3140. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  3141. ProcessDeferredParams(ctx);
  3142. }
  3143. void asCCompiler::PrepareForAssignment(asCDataType *lvalue, asSExprContext *rctx, asCScriptNode *node, bool toTemporary, asSExprContext *lvalueExpr)
  3144. {
  3145. ProcessPropertyGetAccessor(rctx, node);
  3146. // Make sure the rvalue is initialized if it is a variable
  3147. IsVariableInitialized(&rctx->type, node);
  3148. if( lvalue->IsPrimitive() )
  3149. {
  3150. if( rctx->type.dataType.IsPrimitive() )
  3151. {
  3152. if( rctx->type.dataType.IsReference() )
  3153. {
  3154. // Cannot do implicit conversion of references so we first convert the reference to a variable
  3155. ConvertToVariableNotIn(rctx, lvalueExpr);
  3156. }
  3157. }
  3158. // Implicitly convert the value to the right type
  3159. int l = int(reservedVariables.GetLength());
  3160. if( lvalueExpr ) lvalueExpr->bc.GetVarsUsed(reservedVariables);
  3161. ImplicitConversion(rctx, *lvalue, node, asIC_IMPLICIT_CONV);
  3162. reservedVariables.SetLength(l);
  3163. // Check data type
  3164. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  3165. {
  3166. asCString str;
  3167. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  3168. Error(str.AddressOf(), node);
  3169. rctx->type.SetDummy();
  3170. }
  3171. // Make sure the rvalue is a variable
  3172. if( !rctx->type.isVariable )
  3173. ConvertToVariableNotIn(rctx, lvalueExpr);
  3174. }
  3175. else
  3176. {
  3177. asCDataType to = *lvalue;
  3178. to.MakeReference(false);
  3179. // TODO: ImplicitConversion should know to do this by itself
  3180. // First convert to a handle which will do a reference cast
  3181. if( !lvalue->IsObjectHandle() &&
  3182. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  3183. to.MakeHandle(true);
  3184. // Don't allow the implicit conversion to create an object
  3185. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, !toTemporary);
  3186. if( !lvalue->IsObjectHandle() &&
  3187. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  3188. {
  3189. // Then convert to a reference, which will validate the handle
  3190. to.MakeHandle(false);
  3191. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, !toTemporary);
  3192. }
  3193. // Check data type
  3194. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  3195. {
  3196. asCString str;
  3197. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  3198. Error(str.AddressOf(), node);
  3199. }
  3200. else
  3201. {
  3202. // If the assignment will be made with the copy behaviour then the rvalue must not be a reference
  3203. if( lvalue->IsObject() )
  3204. asASSERT(!rctx->type.dataType.IsReference());
  3205. }
  3206. }
  3207. }
  3208. bool asCCompiler::IsLValue(asCTypeInfo &type)
  3209. {
  3210. if( !type.isLValue ) return false;
  3211. if( type.dataType.IsReadOnly() ) return false;
  3212. if( !type.dataType.IsObject() && !type.isVariable && !type.dataType.IsReference() ) return false;
  3213. return true;
  3214. }
  3215. int asCCompiler::PerformAssignment(asCTypeInfo *lvalue, asCTypeInfo *rvalue, asCByteCode *bc, asCScriptNode *node)
  3216. {
  3217. if( lvalue->dataType.IsReadOnly() )
  3218. {
  3219. Error(TXT_REF_IS_READ_ONLY, node);
  3220. return -1;
  3221. }
  3222. if( lvalue->dataType.IsPrimitive() )
  3223. {
  3224. if( lvalue->isVariable )
  3225. {
  3226. // Copy the value between the variables directly
  3227. if( lvalue->dataType.GetSizeInMemoryDWords() == 1 )
  3228. bc->InstrW_W(asBC_CpyVtoV4, lvalue->stackOffset, rvalue->stackOffset);
  3229. else
  3230. bc->InstrW_W(asBC_CpyVtoV8, lvalue->stackOffset, rvalue->stackOffset);
  3231. // Mark variable as initialized
  3232. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3233. if( v ) v->isInitialized = true;
  3234. }
  3235. else if( lvalue->dataType.IsReference() )
  3236. {
  3237. // Copy the value of the variable to the reference in the register
  3238. int s = lvalue->dataType.GetSizeInMemoryBytes();
  3239. if( s == 1 )
  3240. bc->InstrSHORT(asBC_WRTV1, rvalue->stackOffset);
  3241. else if( s == 2 )
  3242. bc->InstrSHORT(asBC_WRTV2, rvalue->stackOffset);
  3243. else if( s == 4 )
  3244. bc->InstrSHORT(asBC_WRTV4, rvalue->stackOffset);
  3245. else if( s == 8 )
  3246. bc->InstrSHORT(asBC_WRTV8, rvalue->stackOffset);
  3247. }
  3248. else
  3249. {
  3250. Error(TXT_NOT_VALID_LVALUE, node);
  3251. return -1;
  3252. }
  3253. }
  3254. else if( !lvalue->isExplicitHandle )
  3255. {
  3256. asSExprContext ctx(engine);
  3257. ctx.type = *lvalue;
  3258. Dereference(&ctx, true);
  3259. *lvalue = ctx.type;
  3260. bc->AddCode(&ctx.bc);
  3261. // TODO: Should find the opAssign method that implements the default copy behaviour.
  3262. // The beh->copy member will be removed.
  3263. asSTypeBehaviour *beh = lvalue->dataType.GetBehaviour();
  3264. if( beh->copy )
  3265. {
  3266. // Call the copy operator
  3267. bc->Call(asBC_CALLSYS, (asDWORD)beh->copy, 2*AS_PTR_SIZE);
  3268. bc->Instr(asBC_PshRPtr);
  3269. }
  3270. else
  3271. {
  3272. // Default copy operator
  3273. if( lvalue->dataType.GetSizeInMemoryDWords() == 0 ||
  3274. !(lvalue->dataType.GetObjectType()->flags & asOBJ_POD) )
  3275. {
  3276. asCString msg;
  3277. msg.Format(TXT_NO_DEFAULT_COPY_OP_FOR_s, lvalue->dataType.GetObjectType()->name.AddressOf());
  3278. Error(msg.AddressOf(), node);
  3279. return -1;
  3280. }
  3281. // Copy larger data types from a reference
  3282. // TODO: runtime optimize: COPY should pop both arguments and store the reference in the register.
  3283. bc->InstrSHORT_DW(asBC_COPY, (short)lvalue->dataType.GetSizeInMemoryDWords(), engine->GetTypeIdFromDataType(lvalue->dataType));
  3284. }
  3285. }
  3286. else
  3287. {
  3288. // TODO: The object handle can be stored in a variable as well
  3289. if( !lvalue->dataType.IsReference() )
  3290. {
  3291. Error(TXT_NOT_VALID_REFERENCE, node);
  3292. return -1;
  3293. }
  3294. bc->InstrPTR(asBC_REFCPY, lvalue->dataType.GetObjectType());
  3295. // Mark variable as initialized
  3296. if( variables )
  3297. {
  3298. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3299. if( v ) v->isInitialized = true;
  3300. }
  3301. }
  3302. return 0;
  3303. }
  3304. bool asCCompiler::CompileRefCast(asSExprContext *ctx, const asCDataType &to, bool isExplicit, asCScriptNode *node, bool generateCode)
  3305. {
  3306. bool conversionDone = false;
  3307. asCArray<int> ops;
  3308. asUINT n;
  3309. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT )
  3310. {
  3311. // We need it to be a reference
  3312. if( !ctx->type.dataType.IsReference() )
  3313. {
  3314. asCDataType to = ctx->type.dataType;
  3315. to.MakeReference(true);
  3316. ImplicitConversion(ctx, to, 0, isExplicit ? asIC_EXPLICIT_REF_CAST : asIC_IMPLICIT_CONV, generateCode);
  3317. }
  3318. if( isExplicit )
  3319. {
  3320. // Allow dynamic cast between object handles (only for script objects).
  3321. // At run time this may result in a null handle,
  3322. // which when used will throw an exception
  3323. conversionDone = true;
  3324. if( generateCode )
  3325. {
  3326. ctx->bc.InstrDWORD(asBC_Cast, engine->GetTypeIdFromDataType(to));
  3327. // Allocate a temporary variable for the returned object
  3328. int returnOffset = AllocateVariable(to, true);
  3329. // Move the pointer from the object register to the temporary variable
  3330. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  3331. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  3332. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3333. ctx->type.SetVariable(to, returnOffset, true);
  3334. ctx->type.dataType.MakeReference(true);
  3335. }
  3336. else
  3337. {
  3338. ctx->type.dataType = to;
  3339. ctx->type.dataType.MakeReference(true);
  3340. }
  3341. }
  3342. else
  3343. {
  3344. if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3345. {
  3346. conversionDone = true;
  3347. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3348. }
  3349. }
  3350. }
  3351. else
  3352. {
  3353. // Find a suitable registered behaviour
  3354. asSTypeBehaviour *beh = &ctx->type.dataType.GetObjectType()->beh;
  3355. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3356. {
  3357. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3358. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3359. {
  3360. int funcId = beh->operators[n+1];
  3361. // Is the operator for the output type?
  3362. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3363. if( func->returnType.GetObjectType() != to.GetObjectType() )
  3364. continue;
  3365. ops.PushLast(funcId);
  3366. }
  3367. }
  3368. // It shouldn't be possible to have more than one
  3369. asASSERT( ops.GetLength() <= 1 );
  3370. // Should only have one behaviour for each output type
  3371. if( ops.GetLength() == 1 )
  3372. {
  3373. if( generateCode )
  3374. {
  3375. // TODO: runtime optimize: Instead of producing bytecode for checking if the handle is
  3376. // null, we can create a special CALLSYS instruction that checks
  3377. // if the object pointer is null and if so sets the object register
  3378. // to null directly without executing the function.
  3379. //
  3380. // Alternatively I could force the ref cast behaviours be global
  3381. // functions with 1 parameter, even though they should still be
  3382. // registered with RegisterObjectBehaviour()
  3383. // Add code to avoid calling the cast behaviour if the handle is already null,
  3384. // because that will raise a null pointer exception due to the cast behaviour
  3385. // being a class method, and the this pointer cannot be null.
  3386. if( ctx->type.isVariable )
  3387. ctx->bc.Instr(asBC_PopPtr);
  3388. else
  3389. {
  3390. Dereference(ctx, true);
  3391. ConvertToVariable(ctx);
  3392. }
  3393. // TODO: runtime optimize: should have immediate comparison for null pointer
  3394. int offset = AllocateVariable(asCDataType::CreateNullHandle(), true);
  3395. // 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)
  3396. ctx->bc.InstrSHORT(asBC_ClrVPtr, (asWORD)offset);
  3397. ctx->bc.InstrW_W(asBC_CmpPtr, ctx->type.stackOffset, offset);
  3398. DeallocateVariable(offset);
  3399. int afterLabel = nextLabel++;
  3400. ctx->bc.InstrDWORD(asBC_JZ, afterLabel);
  3401. // Call the cast operator
  3402. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3403. ctx->bc.Instr(asBC_RDSPtr);
  3404. ctx->type.dataType.MakeReference(false);
  3405. asCTypeInfo objType = ctx->type;
  3406. asCArray<asSExprContext *> args;
  3407. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  3408. ctx->bc.Instr(asBC_PopPtr);
  3409. int endLabel = nextLabel++;
  3410. ctx->bc.InstrINT(asBC_JMP, endLabel);
  3411. ctx->bc.Label((short)afterLabel);
  3412. // Make a NULL pointer
  3413. ctx->bc.InstrSHORT(asBC_ClrVPtr, ctx->type.stackOffset);
  3414. ctx->bc.Label((short)endLabel);
  3415. // Since we're receiving a handle, we can release the original variable
  3416. ReleaseTemporaryVariable(objType, &ctx->bc);
  3417. // Push the reference to the handle on the stack
  3418. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3419. }
  3420. else
  3421. {
  3422. asCScriptFunction *func = engine->scriptFunctions[ops[0]];
  3423. ctx->type.Set(func->returnType);
  3424. }
  3425. }
  3426. else if( ops.GetLength() == 0 )
  3427. {
  3428. // Check for the generic ref cast behaviour
  3429. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3430. {
  3431. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3432. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3433. {
  3434. int funcId = beh->operators[n+1];
  3435. // Does the operator take the ?&out parameter?
  3436. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3437. if( func->parameterTypes.GetLength() != 1 ||
  3438. func->parameterTypes[0].GetTokenType() != ttQuestion ||
  3439. func->inOutFlags[0] != asTM_OUTREF )
  3440. continue;
  3441. ops.PushLast(funcId);
  3442. }
  3443. }
  3444. // It shouldn't be possible to have more than one
  3445. asASSERT( ops.GetLength() <= 1 );
  3446. if( ops.GetLength() == 1 )
  3447. {
  3448. if( generateCode )
  3449. {
  3450. asASSERT(to.IsObjectHandle());
  3451. // Allocate a temporary variable of the requested handle type
  3452. int stackOffset = AllocateVariableNotIn(to, true, false, ctx);
  3453. // Pass the reference of that variable to the function as output parameter
  3454. asCDataType toRef(to);
  3455. toRef.MakeReference(true);
  3456. asCArray<asSExprContext *> args;
  3457. asSExprContext arg(engine);
  3458. arg.bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3459. // Don't mark the variable as temporary, so it won't be freed too early
  3460. arg.type.SetVariable(toRef, stackOffset, false);
  3461. arg.type.isLValue = true;
  3462. arg.type.isExplicitHandle = true;
  3463. args.PushLast(&arg);
  3464. // Call the behaviour method
  3465. MakeFunctionCall(ctx, ops[0], ctx->type.dataType.GetObjectType(), args, node);
  3466. // Use the reference to the variable as the result of the expression
  3467. // Now we can mark the variable as temporary
  3468. ctx->type.SetVariable(toRef, stackOffset, true);
  3469. ctx->bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3470. }
  3471. else
  3472. {
  3473. // All casts are legal
  3474. ctx->type.Set(to);
  3475. }
  3476. }
  3477. }
  3478. }
  3479. return conversionDone;
  3480. }
  3481. asUINT asCCompiler::ImplicitConvPrimitiveToPrimitive(asSExprContext *ctx, const asCDataType &toOrig, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  3482. {
  3483. asCDataType to = toOrig;
  3484. to.MakeReference(false);
  3485. asASSERT( !ctx->type.dataType.IsReference() );
  3486. // Maybe no conversion is needed
  3487. if( to.IsEqualExceptConst(ctx->type.dataType) )
  3488. {
  3489. // A primitive is const or not
  3490. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3491. return asCC_NO_CONV;
  3492. }
  3493. // Determine the cost of this conversion
  3494. asUINT cost = asCC_NO_CONV;
  3495. if( (to.IsIntegerType() || to.IsUnsignedType()) && (ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType()) )
  3496. cost = asCC_INT_FLOAT_CONV;
  3497. else if( (to.IsFloatType() || to.IsDoubleType()) && (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() || ctx->type.dataType.IsEnumType()) )
  3498. cost = asCC_INT_FLOAT_CONV;
  3499. else if( to.IsUnsignedType() && ctx->type.dataType.IsIntegerType() )
  3500. cost = asCC_SIGNED_CONV;
  3501. else if( to.IsIntegerType() && (ctx->type.dataType.IsUnsignedType() || ctx->type.dataType.IsEnumType()) )
  3502. cost = asCC_SIGNED_CONV;
  3503. else if( to.GetSizeInMemoryBytes() || ctx->type.dataType.GetSizeInMemoryBytes() )
  3504. cost = asCC_PRIMITIVE_SIZE_CONV;
  3505. // Start by implicitly converting constant values
  3506. if( ctx->type.isConstant )
  3507. {
  3508. ImplicitConversionConstant(ctx, to, node, convType);
  3509. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3510. return cost;
  3511. }
  3512. // Allow implicit conversion between numbers
  3513. if( generateCode )
  3514. {
  3515. // When generating the code the decision has already been made, so we don't bother determining the cost
  3516. // Convert smaller types to 32bit first
  3517. int s = ctx->type.dataType.GetSizeInMemoryBytes();
  3518. if( s < 4 )
  3519. {
  3520. ConvertToTempVariable(ctx);
  3521. if( ctx->type.dataType.IsIntegerType() )
  3522. {
  3523. if( s == 1 )
  3524. ctx->bc.InstrSHORT(asBC_sbTOi, ctx->type.stackOffset);
  3525. else if( s == 2 )
  3526. ctx->bc.InstrSHORT(asBC_swTOi, ctx->type.stackOffset);
  3527. ctx->type.dataType.SetTokenType(ttInt);
  3528. }
  3529. else if( ctx->type.dataType.IsUnsignedType() )
  3530. {
  3531. if( s == 1 )
  3532. ctx->bc.InstrSHORT(asBC_ubTOi, ctx->type.stackOffset);
  3533. else if( s == 2 )
  3534. ctx->bc.InstrSHORT(asBC_uwTOi, ctx->type.stackOffset);
  3535. ctx->type.dataType.SetTokenType(ttUInt);
  3536. }
  3537. }
  3538. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1) ||
  3539. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  3540. {
  3541. if( ctx->type.dataType.IsIntegerType() ||
  3542. ctx->type.dataType.IsUnsignedType() ||
  3543. ctx->type.dataType.IsEnumType() )
  3544. {
  3545. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3546. {
  3547. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3548. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3549. }
  3550. else
  3551. {
  3552. ConvertToTempVariable(ctx);
  3553. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3554. int offset = AllocateVariable(to, true);
  3555. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3556. ctx->type.SetVariable(to, offset, true);
  3557. }
  3558. }
  3559. else if( ctx->type.dataType.IsFloatType() )
  3560. {
  3561. ConvertToTempVariable(ctx);
  3562. ctx->bc.InstrSHORT(asBC_fTOi, ctx->type.stackOffset);
  3563. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3564. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3565. }
  3566. else if( ctx->type.dataType.IsDoubleType() )
  3567. {
  3568. ConvertToTempVariable(ctx);
  3569. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3570. int offset = AllocateVariable(to, true);
  3571. ctx->bc.InstrW_W(asBC_dTOi, offset, ctx->type.stackOffset);
  3572. ctx->type.SetVariable(to, offset, true);
  3573. }
  3574. // Convert to smaller integer if necessary
  3575. int s = to.GetSizeInMemoryBytes();
  3576. if( s < 4 )
  3577. {
  3578. ConvertToTempVariable(ctx);
  3579. if( s == 1 )
  3580. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3581. else if( s == 2 )
  3582. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3583. }
  3584. }
  3585. if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  3586. {
  3587. if( ctx->type.dataType.IsIntegerType() ||
  3588. ctx->type.dataType.IsUnsignedType() ||
  3589. ctx->type.dataType.IsEnumType() )
  3590. {
  3591. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3592. {
  3593. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3594. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3595. }
  3596. else
  3597. {
  3598. ConvertToTempVariable(ctx);
  3599. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3600. int offset = AllocateVariable(to, true);
  3601. if( ctx->type.dataType.IsUnsignedType() )
  3602. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3603. else
  3604. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3605. ctx->type.SetVariable(to, offset, true);
  3606. }
  3607. }
  3608. else if( ctx->type.dataType.IsFloatType() )
  3609. {
  3610. ConvertToTempVariable(ctx);
  3611. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3612. int offset = AllocateVariable(to, true);
  3613. ctx->bc.InstrW_W(asBC_fTOi64, offset, ctx->type.stackOffset);
  3614. ctx->type.SetVariable(to, offset, true);
  3615. }
  3616. else if( ctx->type.dataType.IsDoubleType() )
  3617. {
  3618. ConvertToTempVariable(ctx);
  3619. ctx->bc.InstrSHORT(asBC_dTOi64, ctx->type.stackOffset);
  3620. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3621. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3622. }
  3623. }
  3624. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  3625. {
  3626. if( ctx->type.dataType.IsIntegerType() ||
  3627. ctx->type.dataType.IsUnsignedType() ||
  3628. ctx->type.dataType.IsEnumType() )
  3629. {
  3630. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3631. {
  3632. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3633. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3634. }
  3635. else
  3636. {
  3637. ConvertToTempVariable(ctx);
  3638. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3639. int offset = AllocateVariable(to, true);
  3640. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3641. ctx->type.SetVariable(to, offset, true);
  3642. }
  3643. }
  3644. else if( ctx->type.dataType.IsFloatType() )
  3645. {
  3646. ConvertToTempVariable(ctx);
  3647. ctx->bc.InstrSHORT(asBC_fTOu, ctx->type.stackOffset);
  3648. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3649. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3650. }
  3651. else if( ctx->type.dataType.IsDoubleType() )
  3652. {
  3653. ConvertToTempVariable(ctx);
  3654. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3655. int offset = AllocateVariable(to, true);
  3656. ctx->bc.InstrW_W(asBC_dTOu, offset, ctx->type.stackOffset);
  3657. ctx->type.SetVariable(to, offset, true);
  3658. }
  3659. // Convert to smaller integer if necessary
  3660. int s = to.GetSizeInMemoryBytes();
  3661. if( s < 4 )
  3662. {
  3663. ConvertToTempVariable(ctx);
  3664. if( s == 1 )
  3665. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3666. else if( s == 2 )
  3667. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3668. }
  3669. }
  3670. if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  3671. {
  3672. if( ctx->type.dataType.IsIntegerType() ||
  3673. ctx->type.dataType.IsUnsignedType() ||
  3674. ctx->type.dataType.IsEnumType() )
  3675. {
  3676. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3677. {
  3678. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3679. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3680. }
  3681. else
  3682. {
  3683. ConvertToTempVariable(ctx);
  3684. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3685. int offset = AllocateVariable(to, true);
  3686. if( ctx->type.dataType.IsUnsignedType() )
  3687. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3688. else
  3689. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3690. ctx->type.SetVariable(to, offset, true);
  3691. }
  3692. }
  3693. else if( ctx->type.dataType.IsFloatType() )
  3694. {
  3695. ConvertToTempVariable(ctx);
  3696. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3697. int offset = AllocateVariable(to, true);
  3698. ctx->bc.InstrW_W(asBC_fTOu64, offset, ctx->type.stackOffset);
  3699. ctx->type.SetVariable(to, offset, true);
  3700. }
  3701. else if( ctx->type.dataType.IsDoubleType() )
  3702. {
  3703. ConvertToTempVariable(ctx);
  3704. ctx->bc.InstrSHORT(asBC_dTOu64, ctx->type.stackOffset);
  3705. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3706. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3707. }
  3708. }
  3709. else if( to.IsFloatType() )
  3710. {
  3711. if( (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType()) && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3712. {
  3713. ConvertToTempVariable(ctx);
  3714. ctx->bc.InstrSHORT(asBC_iTOf, ctx->type.stackOffset);
  3715. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3716. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3717. }
  3718. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3719. {
  3720. ConvertToTempVariable(ctx);
  3721. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3722. int offset = AllocateVariable(to, true);
  3723. ctx->bc.InstrW_W(asBC_i64TOf, offset, ctx->type.stackOffset);
  3724. ctx->type.SetVariable(to, offset, true);
  3725. }
  3726. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3727. {
  3728. ConvertToTempVariable(ctx);
  3729. ctx->bc.InstrSHORT(asBC_uTOf, ctx->type.stackOffset);
  3730. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3731. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3732. }
  3733. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3734. {
  3735. ConvertToTempVariable(ctx);
  3736. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3737. int offset = AllocateVariable(to, true);
  3738. ctx->bc.InstrW_W(asBC_u64TOf, offset, ctx->type.stackOffset);
  3739. ctx->type.SetVariable(to, offset, true);
  3740. }
  3741. else if( ctx->type.dataType.IsDoubleType() )
  3742. {
  3743. ConvertToTempVariable(ctx);
  3744. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3745. int offset = AllocateVariable(to, true);
  3746. ctx->bc.InstrW_W(asBC_dTOf, offset, ctx->type.stackOffset);
  3747. ctx->type.SetVariable(to, offset, true);
  3748. }
  3749. }
  3750. else if( to.IsDoubleType() )
  3751. {
  3752. if( (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType()) && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3753. {
  3754. ConvertToTempVariable(ctx);
  3755. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3756. int offset = AllocateVariable(to, true);
  3757. ctx->bc.InstrW_W(asBC_iTOd, offset, ctx->type.stackOffset);
  3758. ctx->type.SetVariable(to, offset, true);
  3759. }
  3760. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3761. {
  3762. ConvertToTempVariable(ctx);
  3763. ctx->bc.InstrSHORT(asBC_i64TOd, ctx->type.stackOffset);
  3764. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3765. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3766. }
  3767. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3768. {
  3769. ConvertToTempVariable(ctx);
  3770. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3771. int offset = AllocateVariable(to, true);
  3772. ctx->bc.InstrW_W(asBC_uTOd, offset, ctx->type.stackOffset);
  3773. ctx->type.SetVariable(to, offset, true);
  3774. }
  3775. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3776. {
  3777. ConvertToTempVariable(ctx);
  3778. ctx->bc.InstrSHORT(asBC_u64TOd, ctx->type.stackOffset);
  3779. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3780. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3781. }
  3782. else if( ctx->type.dataType.IsFloatType() )
  3783. {
  3784. ConvertToTempVariable(ctx);
  3785. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3786. int offset = AllocateVariable(to, true);
  3787. ctx->bc.InstrW_W(asBC_fTOd, offset, ctx->type.stackOffset);
  3788. ctx->type.SetVariable(to, offset, true);
  3789. }
  3790. }
  3791. }
  3792. else
  3793. {
  3794. if( (to.IsIntegerType() || to.IsUnsignedType() ||
  3795. to.IsFloatType() || to.IsDoubleType() ||
  3796. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST)) &&
  3797. (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() ||
  3798. ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType() ||
  3799. ctx->type.dataType.IsEnumType()) )
  3800. {
  3801. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3802. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3803. }
  3804. }
  3805. // Primitive types on the stack, can be const or non-const
  3806. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3807. return cost;
  3808. }
  3809. asUINT asCCompiler::ImplicitConversion(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, bool allowObjectConstruct)
  3810. {
  3811. asASSERT( ctx->type.dataType.GetTokenType() != ttUnrecognizedToken ||
  3812. ctx->type.dataType.IsNullHandle() );
  3813. // No conversion from void to any other type
  3814. if( ctx->type.dataType.GetTokenType() == ttVoid )
  3815. return asCC_NO_CONV;
  3816. // Do we want a var type?
  3817. if( to.GetTokenType() == ttQuestion )
  3818. {
  3819. // Any type can be converted to a var type, but only when not generating code
  3820. asASSERT( !generateCode );
  3821. ctx->type.dataType = to;
  3822. return asCC_VARIABLE_CONV;
  3823. }
  3824. // Do we want a primitive?
  3825. else if( to.IsPrimitive() )
  3826. {
  3827. if( !ctx->type.dataType.IsPrimitive() )
  3828. return ImplicitConvObjectToPrimitive(ctx, to, node, convType, generateCode);
  3829. else
  3830. return ImplicitConvPrimitiveToPrimitive(ctx, to, node, convType, generateCode);
  3831. }
  3832. else // The target is a complex type
  3833. {
  3834. if( ctx->type.dataType.IsPrimitive() )
  3835. return ImplicitConvPrimitiveToObject(ctx, to, node, convType, generateCode, allowObjectConstruct);
  3836. else if( ctx->type.IsNullConstant() || ctx->type.dataType.GetObjectType() )
  3837. return ImplicitConvObjectToObject(ctx, to, node, convType, generateCode, allowObjectConstruct);
  3838. }
  3839. return asCC_NO_CONV;
  3840. }
  3841. asUINT asCCompiler::ImplicitConvObjectToPrimitive(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  3842. {
  3843. if( ctx->type.isExplicitHandle )
  3844. {
  3845. // An explicit handle cannot be converted to a primitive
  3846. if( convType != asIC_IMPLICIT_CONV && node )
  3847. {
  3848. asCString str;
  3849. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3850. Error(str.AddressOf(), node);
  3851. }
  3852. return asCC_NO_CONV;
  3853. }
  3854. // TODO: Must use the const cast behaviour if the object is read-only
  3855. // Find matching value cast behaviours
  3856. // Here we're only interested in those that convert the type to a primitive type
  3857. asCArray<int> funcs;
  3858. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  3859. if( beh )
  3860. {
  3861. if( convType == asIC_EXPLICIT_VAL_CAST )
  3862. {
  3863. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3864. {
  3865. // accept both implicit and explicit cast
  3866. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  3867. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  3868. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  3869. funcs.PushLast(beh->operators[n+1]);
  3870. }
  3871. }
  3872. else
  3873. {
  3874. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3875. {
  3876. // accept only implicit cast
  3877. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  3878. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  3879. funcs.PushLast(beh->operators[n+1]);
  3880. }
  3881. }
  3882. }
  3883. // This matrix describes the priorities of the types to search for, for each target type
  3884. // The first column is the target type, the priorities goes from left to right
  3885. eTokenType matchMtx[10][10] =
  3886. {
  3887. {ttDouble, ttFloat, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  3888. {ttFloat, ttDouble, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  3889. {ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  3890. {ttUInt64, ttInt64, ttUInt, ttInt, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  3891. {ttInt, ttUInt, ttInt64, ttUInt64, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  3892. {ttUInt, ttInt, ttUInt64, ttInt64, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  3893. {ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttInt8, ttUInt8, ttDouble, ttFloat},
  3894. {ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttUInt8, ttInt8, ttDouble, ttFloat},
  3895. {ttInt8, ttUInt8, ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttDouble, ttFloat},
  3896. {ttUInt8, ttInt8, ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttDouble, ttFloat},
  3897. };
  3898. // Which row to use?
  3899. eTokenType *row = 0;
  3900. for( unsigned int type = 0; type < 10; type++ )
  3901. {
  3902. if( to.GetTokenType() == matchMtx[type][0] )
  3903. {
  3904. row = &matchMtx[type][0];
  3905. break;
  3906. }
  3907. }
  3908. // Find the best matching cast operator
  3909. int funcId = 0;
  3910. if( row )
  3911. {
  3912. asCDataType target(to);
  3913. // Priority goes from left to right in the matrix
  3914. for( unsigned int attempt = 0; attempt < 10 && funcId == 0; attempt++ )
  3915. {
  3916. target.SetTokenType(row[attempt]);
  3917. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  3918. {
  3919. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[n]);
  3920. if( descr->returnType.IsEqualExceptConst(target) )
  3921. {
  3922. funcId = funcs[n];
  3923. break;
  3924. }
  3925. }
  3926. }
  3927. }
  3928. // Did we find a suitable function?
  3929. if( funcId != 0 )
  3930. {
  3931. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  3932. if( generateCode )
  3933. {
  3934. asCTypeInfo objType = ctx->type;
  3935. Dereference(ctx, true);
  3936. PerformFunctionCall(funcId, ctx);
  3937. ReleaseTemporaryVariable(objType, &ctx->bc);
  3938. }
  3939. else
  3940. ctx->type.Set(descr->returnType);
  3941. // Allow one more implicit conversion to another primitive type
  3942. return asCC_OBJ_TO_PRIMITIVE_CONV + ImplicitConversion(ctx, to, node, convType, generateCode, false);
  3943. }
  3944. else
  3945. {
  3946. if( convType != asIC_IMPLICIT_CONV && node )
  3947. {
  3948. asCString str;
  3949. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3950. Error(str.AddressOf(), node);
  3951. }
  3952. }
  3953. return asCC_NO_CONV;
  3954. }
  3955. asUINT asCCompiler::ImplicitConvObjectRef(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  3956. {
  3957. // Convert null to any object type handle, but not to a non-handle type
  3958. if( ctx->type.IsNullConstant() )
  3959. {
  3960. if( to.IsObjectHandle() )
  3961. {
  3962. ctx->type.dataType = to;
  3963. return asCC_REF_CONV;
  3964. }
  3965. return asCC_NO_CONV;
  3966. }
  3967. asASSERT(ctx->type.dataType.GetObjectType());
  3968. // First attempt to convert the base type without instanciating another instance
  3969. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  3970. {
  3971. // If the to type is an interface and the from type implements it, then we can convert it immediately
  3972. if( ctx->type.dataType.GetObjectType()->Implements(to.GetObjectType()) )
  3973. {
  3974. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3975. return asCC_REF_CONV;
  3976. }
  3977. // If the to type is a class and the from type derives from it, then we can convert it immediately
  3978. else if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3979. {
  3980. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3981. return asCC_REF_CONV;
  3982. }
  3983. // If the types are not equal yet, then we may still be able to find a reference cast
  3984. else if( ctx->type.dataType.GetObjectType() != to.GetObjectType() )
  3985. {
  3986. // A ref cast must not remove the constness
  3987. bool isConst = false;
  3988. if( (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) ||
  3989. (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) )
  3990. isConst = true;
  3991. // We may still be able to find an implicit ref cast behaviour
  3992. CompileRefCast(ctx, to, convType == asIC_EXPLICIT_REF_CAST, node, generateCode);
  3993. ctx->type.dataType.MakeHandleToConst(isConst);
  3994. // Was the conversion done?
  3995. if( ctx->type.dataType.GetObjectType() == to.GetObjectType() )
  3996. return asCC_REF_CONV;
  3997. }
  3998. }
  3999. // Convert matching function types
  4000. if( to.GetFuncDef() && ctx->type.dataType.GetFuncDef() &&
  4001. to.GetFuncDef() != ctx->type.dataType.GetFuncDef() )
  4002. {
  4003. asCScriptFunction *toFunc = to.GetFuncDef();
  4004. asCScriptFunction *fromFunc = ctx->type.dataType.GetFuncDef();
  4005. if( toFunc->IsSignatureExceptNameEqual(fromFunc) )
  4006. {
  4007. ctx->type.dataType.SetFuncDef(toFunc);
  4008. return asCC_REF_CONV;
  4009. }
  4010. }
  4011. return asCC_NO_CONV;
  4012. }
  4013. asUINT asCCompiler::ImplicitConvObjectValue(asSExprContext *ctx, const asCDataType &to, asCScriptNode * /*node*/, EImplicitConv convType, bool generateCode)
  4014. {
  4015. asUINT cost = asCC_NO_CONV;
  4016. // If the base type is still different, and we are allowed to instance
  4017. // another object then we can try an implicit value cast
  4018. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  4019. {
  4020. // TODO: Implement support for implicit constructor/factory
  4021. asCArray<int> funcs;
  4022. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  4023. if( beh )
  4024. {
  4025. if( convType == asIC_EXPLICIT_VAL_CAST )
  4026. {
  4027. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  4028. {
  4029. // accept both implicit and explicit cast
  4030. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  4031. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  4032. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  4033. funcs.PushLast(beh->operators[n+1]);
  4034. }
  4035. }
  4036. else
  4037. {
  4038. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  4039. {
  4040. // accept only implicit cast
  4041. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  4042. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  4043. funcs.PushLast(beh->operators[n+1]);
  4044. }
  4045. }
  4046. }
  4047. // TODO: If there are multiple valid value casts, then we must choose the most appropriate one
  4048. asASSERT( funcs.GetLength() <= 1 );
  4049. if( funcs.GetLength() == 1 )
  4050. {
  4051. asCScriptFunction *f = builder->GetFunctionDescription(funcs[0]);
  4052. if( generateCode )
  4053. {
  4054. asCTypeInfo objType = ctx->type;
  4055. Dereference(ctx, true);
  4056. bool useVariable = false;
  4057. int stackOffset = 0;
  4058. if( f->DoesReturnOnStack() )
  4059. {
  4060. useVariable = true;
  4061. stackOffset = AllocateVariable(f->returnType, true);
  4062. // Push the pointer to the pre-allocated space for the return value
  4063. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  4064. // The object pointer is already on the stack, but should be the top
  4065. // one, so we need to swap the pointers in order to get the correct
  4066. ctx->bc.Instr(asBC_SwapPtr);
  4067. }
  4068. PerformFunctionCall(funcs[0], ctx, false, 0, 0, useVariable, stackOffset);
  4069. ReleaseTemporaryVariable(objType, &ctx->bc);
  4070. }
  4071. else
  4072. ctx->type.Set(f->returnType);
  4073. cost = asCC_TO_OBJECT_CONV;
  4074. }
  4075. }
  4076. return cost;
  4077. }
  4078. asUINT asCCompiler::ImplicitConvObjectToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, bool allowObjectConstruct)
  4079. {
  4080. // First try a ref cast
  4081. asUINT cost = ImplicitConvObjectRef(ctx, to, node, convType, generateCode);
  4082. // If the desired type is an asOBJ_ASHANDLE then we'll assume it is allowed to implicitly
  4083. // construct the object through any of the available constructors
  4084. if( to.GetObjectType() && (to.GetObjectType()->flags & asOBJ_ASHANDLE) && to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  4085. {
  4086. asCArray<int> funcs;
  4087. funcs = to.GetObjectType()->beh.constructors;
  4088. asCArray<asSExprContext *> args;
  4089. args.PushLast(ctx);
  4090. cost = asCC_TO_OBJECT_CONV + MatchFunctions(funcs, args, node, 0, 0, false, true, false);
  4091. // Did we find a matching constructor?
  4092. if( funcs.GetLength() == 1 )
  4093. {
  4094. if( generateCode )
  4095. {
  4096. // TODO: This should really reuse the code from CompileConstructCall
  4097. // Allocate the new object
  4098. asCTypeInfo tempObj;
  4099. tempObj.dataType = to;
  4100. tempObj.dataType.MakeReference(false);
  4101. tempObj.stackOffset = (short)AllocateVariable(tempObj.dataType, true);
  4102. tempObj.dataType.MakeReference(true);
  4103. tempObj.isTemporary = true;
  4104. tempObj.isVariable = true;
  4105. bool onHeap = IsVariableOnHeap(tempObj.stackOffset);
  4106. // Push the address of the object on the stack
  4107. asSExprContext e(engine);
  4108. if( onHeap )
  4109. e.bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  4110. PrepareFunctionCall(funcs[0], &e.bc, args);
  4111. MoveArgsToStack(funcs[0], &e.bc, args, false);
  4112. // If the object is allocated on the stack, then call the constructor as a normal function
  4113. if( onHeap )
  4114. {
  4115. int offset = 0;
  4116. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  4117. offset = descr->parameterTypes[0].GetSizeOnStackDWords();
  4118. e.bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  4119. }
  4120. else
  4121. e.bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  4122. PerformFunctionCall(funcs[0], &e, onHeap, &args, tempObj.dataType.GetObjectType());
  4123. // Add tag that the object has been initialized
  4124. e.bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  4125. // The constructor doesn't return anything,
  4126. // so we have to manually inform the type of
  4127. // the return value
  4128. e.type = tempObj;
  4129. if( !onHeap )
  4130. e.type.dataType.MakeReference(false);
  4131. // Push the address of the object on the stack again
  4132. e.bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  4133. MergeExprBytecodeAndType(ctx, &e);
  4134. }
  4135. else
  4136. {
  4137. ctx->type.Set(asCDataType::CreateObject(to.GetObjectType(), false));
  4138. }
  4139. }
  4140. }
  4141. // If the base type is still different, and we are allowed to instance
  4142. // another object then we can try an implicit value cast
  4143. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  4144. {
  4145. // Attempt implicit value cast
  4146. cost = ImplicitConvObjectValue(ctx, to, node, convType, generateCode);
  4147. }
  4148. // If we still haven't converted the base type to the correct type, then there is
  4149. // no need to continue as it is not possible to do the conversion
  4150. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  4151. return asCC_NO_CONV;
  4152. if( to.IsObjectHandle() )
  4153. {
  4154. // There is no extra cost in converting to a handle
  4155. // reference to handle -> handle
  4156. // reference -> handle
  4157. // object -> handle
  4158. // handle -> reference to handle
  4159. // reference -> reference to handle
  4160. // object -> reference to handle
  4161. // TODO: If the type is handle, then we can't use IsReadOnly to determine the constness of the basetype
  4162. // If the rvalue is a handle to a const object, then
  4163. // the lvalue must also be a handle to a const object
  4164. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() )
  4165. {
  4166. if( convType != asIC_IMPLICIT_CONV )
  4167. {
  4168. asASSERT(node);
  4169. asCString str;
  4170. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  4171. Error(str.AddressOf(), node);
  4172. }
  4173. }
  4174. if( !ctx->type.dataType.IsObjectHandle() )
  4175. {
  4176. // An object type can be directly converted to a handle of the same type
  4177. if( ctx->type.dataType.SupportHandles() )
  4178. {
  4179. ctx->type.dataType.MakeHandle(true);
  4180. }
  4181. if( ctx->type.dataType.IsObjectHandle() )
  4182. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4183. if( to.IsHandleToConst() && ctx->type.dataType.IsObjectHandle() )
  4184. ctx->type.dataType.MakeHandleToConst(true);
  4185. }
  4186. else
  4187. {
  4188. // A handle to non-const can be converted to a
  4189. // handle to const, but not the other way
  4190. if( to.IsHandleToConst() )
  4191. ctx->type.dataType.MakeHandleToConst(true);
  4192. // A const handle can be converted to a non-const
  4193. // handle and vice versa as the handle is just a value
  4194. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4195. }
  4196. if( to.IsReference() && !ctx->type.dataType.IsReference() )
  4197. {
  4198. if( generateCode )
  4199. {
  4200. asASSERT( ctx->type.dataType.IsObjectHandle() );
  4201. // If the input type is a handle, then a simple ref copy is enough
  4202. bool isExplicitHandle = ctx->type.isExplicitHandle;
  4203. ctx->type.isExplicitHandle = ctx->type.dataType.IsObjectHandle();
  4204. // If the input type is read-only we'll need to temporarily
  4205. // remove this constness, otherwise the assignment will fail
  4206. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  4207. ctx->type.dataType.MakeReadOnly(false);
  4208. // If the object already is a temporary variable, then the copy
  4209. // doesn't have to be made as it is already a unique object
  4210. PrepareTemporaryObject(node, ctx);
  4211. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  4212. ctx->type.isExplicitHandle = isExplicitHandle;
  4213. }
  4214. // A non-reference can be converted to a reference,
  4215. // by putting the value in a temporary variable
  4216. ctx->type.dataType.MakeReference(true);
  4217. // Since it is a new temporary variable it doesn't have to be const
  4218. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4219. }
  4220. else if( !to.IsReference() && ctx->type.dataType.IsReference() )
  4221. {
  4222. Dereference(ctx, generateCode);
  4223. }
  4224. }
  4225. else
  4226. {
  4227. if( !to.IsReference() )
  4228. {
  4229. // reference to handle -> object
  4230. // handle -> object
  4231. // reference -> object
  4232. // An implicit handle can be converted to an object by adding a check for null pointer
  4233. if( ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  4234. {
  4235. if( generateCode )
  4236. ctx->bc.Instr(asBC_CHKREF);
  4237. ctx->type.dataType.MakeHandle(false);
  4238. }
  4239. // A const object can be converted to a non-const object through a copy
  4240. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() &&
  4241. allowObjectConstruct )
  4242. {
  4243. // Does the object type allow a copy to be made?
  4244. if( ctx->type.dataType.CanBeCopied() )
  4245. {
  4246. if( generateCode )
  4247. {
  4248. // Make a temporary object with the copy
  4249. PrepareTemporaryObject(node, ctx);
  4250. }
  4251. // In case the object was already in a temporary variable, then the function
  4252. // didn't really do anything so we need to remove the constness here
  4253. ctx->type.dataType.MakeReadOnly(false);
  4254. // Add the cost for the copy
  4255. cost += asCC_TO_OBJECT_CONV;
  4256. }
  4257. }
  4258. if( ctx->type.dataType.IsReference() )
  4259. {
  4260. // This may look strange, but a value type allocated on the stack is already
  4261. // correct, so nothing should be done other than remove the mark as reference.
  4262. // For types allocated on the heap, it is necessary to dereference the pointer
  4263. // that is currently on the stack
  4264. if( IsVariableOnHeap(ctx->type.stackOffset) )
  4265. Dereference(ctx, generateCode);
  4266. else
  4267. ctx->type.dataType.MakeReference(false);
  4268. }
  4269. // A non-const object can be converted to a const object directly
  4270. if( !ctx->type.dataType.IsReadOnly() && to.IsReadOnly() )
  4271. {
  4272. ctx->type.dataType.MakeReadOnly(true);
  4273. }
  4274. }
  4275. else
  4276. {
  4277. // reference to handle -> reference
  4278. // handle -> reference
  4279. // object -> reference
  4280. if( ctx->type.dataType.IsReference() )
  4281. {
  4282. if( ctx->type.isExplicitHandle && ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  4283. {
  4284. // ASHANDLE objects are really value types, so explicit handle can be removed
  4285. ctx->type.isExplicitHandle = false;
  4286. ctx->type.dataType.MakeHandle(false);
  4287. }
  4288. // A reference to a handle can be converted to a reference to an object
  4289. // by first reading the address, then verifying that it is not null
  4290. if( !to.IsObjectHandle() && ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  4291. {
  4292. ctx->type.dataType.MakeHandle(false);
  4293. if( generateCode )
  4294. ctx->bc.Instr(asBC_ChkRefS);
  4295. }
  4296. // A reference to a non-const can be converted to a reference to a const
  4297. if( to.IsReadOnly() )
  4298. ctx->type.dataType.MakeReadOnly(true);
  4299. else if( ctx->type.dataType.IsReadOnly() )
  4300. {
  4301. // A reference to a const can be converted to a reference to a
  4302. // non-const by copying the object to a temporary variable
  4303. ctx->type.dataType.MakeReadOnly(false);
  4304. if( generateCode )
  4305. {
  4306. // If the object already is a temporary variable, then the copy
  4307. // doesn't have to be made as it is already a unique object
  4308. PrepareTemporaryObject(node, ctx);
  4309. }
  4310. // Add the cost for the copy
  4311. cost += asCC_TO_OBJECT_CONV;
  4312. }
  4313. }
  4314. else
  4315. {
  4316. // A value type allocated on the stack is differentiated
  4317. // by it not being a reference. But it can be handled as
  4318. // reference by pushing the pointer on the stack
  4319. if( (ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) &&
  4320. (ctx->type.isVariable || ctx->type.isTemporary) &&
  4321. !IsVariableOnHeap(ctx->type.stackOffset) )
  4322. {
  4323. // Actually the pointer is already pushed on the stack in
  4324. // CompileVariableAccess, so we don't need to do anything else
  4325. }
  4326. else if( generateCode )
  4327. {
  4328. // A non-reference can be converted to a reference,
  4329. // by putting the value in a temporary variable
  4330. // If the input type is read-only we'll need to temporarily
  4331. // remove this constness, otherwise the assignment will fail
  4332. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  4333. ctx->type.dataType.MakeReadOnly(false);
  4334. // If the object already is a temporary variable, then the copy
  4335. // doesn't have to be made as it is already a unique object
  4336. PrepareTemporaryObject(node, ctx);
  4337. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  4338. // Add the cost for the copy
  4339. cost += asCC_TO_OBJECT_CONV;
  4340. }
  4341. // A handle can be converted to a reference, by checking for a null pointer
  4342. if( ctx->type.dataType.IsObjectHandle() )
  4343. {
  4344. if( generateCode )
  4345. ctx->bc.InstrSHORT(asBC_ChkNullV, ctx->type.stackOffset);
  4346. ctx->type.dataType.MakeHandle(false);
  4347. ctx->type.dataType.MakeReference(true);
  4348. // TODO: Make sure a handle to const isn't converted to non-const reference
  4349. }
  4350. else
  4351. {
  4352. // This may look strange as the conversion was to make the expression a reference
  4353. // but a value type allocated on the stack is a reference even without the type
  4354. // being marked as such.
  4355. ctx->type.dataType.MakeReference(IsVariableOnHeap(ctx->type.stackOffset));
  4356. }
  4357. // TODO: If the variable is an object allocated on the stack the following is not true as the copy may not have been made
  4358. // Since it is a new temporary variable it doesn't have to be const
  4359. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4360. }
  4361. }
  4362. }
  4363. return cost;
  4364. }
  4365. asUINT asCCompiler::ImplicitConvPrimitiveToObject(asSExprContext * /*ctx*/, const asCDataType & /*to*/, asCScriptNode * /*node*/, EImplicitConv /*isExplicit*/, bool /*generateCode*/, bool /*allowObjectConstruct*/)
  4366. {
  4367. // TODO: This function should call the constructor/factory that has been marked as available
  4368. // for implicit conversions. The code will likely be similar to CallCopyConstructor()
  4369. return asCC_NO_CONV;
  4370. }
  4371. void asCCompiler::ImplicitConversionConstant(asSExprContext *from, const asCDataType &to, asCScriptNode *node, EImplicitConv convType)
  4372. {
  4373. asASSERT(from->type.isConstant);
  4374. // TODO: node should be the node of the value that is
  4375. // converted (not the operator that provokes the implicit
  4376. // conversion)
  4377. // If the base type is correct there is no more to do
  4378. if( to.IsEqualExceptRefAndConst(from->type.dataType) ) return;
  4379. // References cannot be constants
  4380. if( from->type.dataType.IsReference() ) return;
  4381. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1) ||
  4382. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  4383. {
  4384. if( from->type.dataType.IsFloatType() ||
  4385. from->type.dataType.IsDoubleType() ||
  4386. from->type.dataType.IsUnsignedType() ||
  4387. from->type.dataType.IsIntegerType() ||
  4388. from->type.dataType.IsEnumType() )
  4389. {
  4390. // Transform the value
  4391. // Float constants can be implicitly converted to int
  4392. if( from->type.dataType.IsFloatType() )
  4393. {
  4394. float fc = from->type.floatValue;
  4395. int ic = int(fc);
  4396. if( float(ic) != fc )
  4397. {
  4398. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4399. }
  4400. from->type.intValue = ic;
  4401. }
  4402. // Double constants can be implicitly converted to int
  4403. else if( from->type.dataType.IsDoubleType() )
  4404. {
  4405. double fc = from->type.doubleValue;
  4406. int ic = int(fc);
  4407. if( double(ic) != fc )
  4408. {
  4409. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4410. }
  4411. from->type.intValue = ic;
  4412. }
  4413. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4414. {
  4415. // Verify that it is possible to convert to signed without getting negative
  4416. if( from->type.intValue < 0 )
  4417. {
  4418. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4419. }
  4420. // Convert to 32bit
  4421. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4422. from->type.intValue = from->type.byteValue;
  4423. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4424. from->type.intValue = from->type.wordValue;
  4425. }
  4426. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4427. {
  4428. // Convert to 32bit
  4429. from->type.intValue = int(from->type.qwordValue);
  4430. }
  4431. else if( from->type.dataType.IsIntegerType() &&
  4432. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4433. {
  4434. // Convert to 32bit
  4435. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4436. from->type.intValue = (signed char)from->type.byteValue;
  4437. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4438. from->type.intValue = (short)from->type.wordValue;
  4439. }
  4440. else if( from->type.dataType.IsEnumType() )
  4441. {
  4442. // Enum type is already an integer type
  4443. }
  4444. // Set the resulting type
  4445. if( to.IsEnumType() )
  4446. from->type.dataType = to;
  4447. else
  4448. from->type.dataType = asCDataType::CreatePrimitive(ttInt, true);
  4449. }
  4450. // Check if a downsize is necessary
  4451. if( to.IsIntegerType() &&
  4452. from->type.dataType.IsIntegerType() &&
  4453. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4454. {
  4455. // Verify if it is possible
  4456. if( to.GetSizeInMemoryBytes() == 1 )
  4457. {
  4458. if( char(from->type.intValue) != from->type.intValue )
  4459. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4460. from->type.byteValue = char(from->type.intValue);
  4461. }
  4462. else if( to.GetSizeInMemoryBytes() == 2 )
  4463. {
  4464. if( short(from->type.intValue) != from->type.intValue )
  4465. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4466. from->type.wordValue = short(from->type.intValue);
  4467. }
  4468. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4469. }
  4470. }
  4471. else if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  4472. {
  4473. // Float constants can be implicitly converted to int
  4474. if( from->type.dataType.IsFloatType() )
  4475. {
  4476. float fc = from->type.floatValue;
  4477. asINT64 ic = asINT64(fc);
  4478. if( float(ic) != fc )
  4479. {
  4480. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4481. }
  4482. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4483. from->type.qwordValue = ic;
  4484. }
  4485. // Double constants can be implicitly converted to int
  4486. else if( from->type.dataType.IsDoubleType() )
  4487. {
  4488. double fc = from->type.doubleValue;
  4489. asINT64 ic = asINT64(fc);
  4490. if( double(ic) != fc )
  4491. {
  4492. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4493. }
  4494. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4495. from->type.qwordValue = ic;
  4496. }
  4497. else if( from->type.dataType.IsUnsignedType() )
  4498. {
  4499. // Convert to 64bit
  4500. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4501. from->type.qwordValue = from->type.byteValue;
  4502. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4503. from->type.qwordValue = from->type.wordValue;
  4504. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4505. from->type.qwordValue = from->type.dwordValue;
  4506. else if( from->type.dataType.GetSizeInMemoryBytes() == 8 )
  4507. {
  4508. if( asINT64(from->type.qwordValue) < 0 )
  4509. {
  4510. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4511. }
  4512. }
  4513. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4514. }
  4515. else if( from->type.dataType.IsEnumType() )
  4516. {
  4517. from->type.qwordValue = from->type.intValue;
  4518. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4519. }
  4520. else if( from->type.dataType.IsIntegerType() )
  4521. {
  4522. // Convert to 64bit
  4523. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4524. from->type.qwordValue = (signed char)from->type.byteValue;
  4525. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4526. from->type.qwordValue = (short)from->type.wordValue;
  4527. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4528. from->type.qwordValue = from->type.intValue;
  4529. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4530. }
  4531. }
  4532. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  4533. {
  4534. if( from->type.dataType.IsFloatType() )
  4535. {
  4536. float fc = from->type.floatValue;
  4537. // Some compilers set the value to 0 when converting a negative float to unsigned int.
  4538. // To maintain a consistent behaviour across compilers we convert to int first.
  4539. asUINT uic = asUINT(int(fc));
  4540. if( float(uic) != fc )
  4541. {
  4542. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4543. }
  4544. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4545. from->type.intValue = uic;
  4546. // Try once more, in case of a smaller type
  4547. ImplicitConversionConstant(from, to, node, convType);
  4548. }
  4549. else if( from->type.dataType.IsDoubleType() )
  4550. {
  4551. double fc = from->type.doubleValue;
  4552. // Some compilers set the value to 0 when converting a negative double to unsigned int.
  4553. // To maintain a consistent behaviour across compilers we convert to int first.
  4554. asUINT uic = asUINT(int(fc));
  4555. if( double(uic) != fc )
  4556. {
  4557. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4558. }
  4559. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4560. from->type.intValue = uic;
  4561. // Try once more, in case of a smaller type
  4562. ImplicitConversionConstant(from, to, node, convType);
  4563. }
  4564. else if( from->type.dataType.IsEnumType() )
  4565. {
  4566. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4567. // Try once more, in case of a smaller type
  4568. ImplicitConversionConstant(from, to, node, convType);
  4569. }
  4570. else if( from->type.dataType.IsIntegerType() )
  4571. {
  4572. // Verify that it is possible to convert to unsigned without loosing negative
  4573. if( from->type.intValue < 0 )
  4574. {
  4575. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4576. }
  4577. // Convert to 32bit
  4578. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4579. from->type.intValue = (signed char)from->type.byteValue;
  4580. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4581. from->type.intValue = (short)from->type.wordValue;
  4582. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4583. // Try once more, in case of a smaller type
  4584. ImplicitConversionConstant(from, to, node, convType);
  4585. }
  4586. else if( from->type.dataType.IsUnsignedType() &&
  4587. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4588. {
  4589. // Convert to 32bit
  4590. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4591. from->type.dwordValue = from->type.byteValue;
  4592. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4593. from->type.dwordValue = from->type.wordValue;
  4594. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4595. // Try once more, in case of a smaller type
  4596. ImplicitConversionConstant(from, to, node, convType);
  4597. }
  4598. else if( from->type.dataType.IsUnsignedType() &&
  4599. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4600. {
  4601. // Verify if it is possible
  4602. if( to.GetSizeInMemoryBytes() == 1 )
  4603. {
  4604. if( asBYTE(from->type.dwordValue) != from->type.dwordValue )
  4605. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4606. from->type.byteValue = asBYTE(from->type.dwordValue);
  4607. }
  4608. else if( to.GetSizeInMemoryBytes() == 2 )
  4609. {
  4610. if( asWORD(from->type.dwordValue) != from->type.dwordValue )
  4611. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4612. from->type.wordValue = asWORD(from->type.dwordValue);
  4613. }
  4614. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4615. }
  4616. }
  4617. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  4618. {
  4619. if( from->type.dataType.IsFloatType() )
  4620. {
  4621. float fc = from->type.floatValue;
  4622. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  4623. asQWORD uic = asQWORD(asINT64(fc));
  4624. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  4625. // MSVC6 doesn't support this conversion
  4626. if( float(uic) != fc )
  4627. {
  4628. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4629. }
  4630. #endif
  4631. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4632. from->type.qwordValue = uic;
  4633. }
  4634. else if( from->type.dataType.IsDoubleType() )
  4635. {
  4636. double fc = from->type.doubleValue;
  4637. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  4638. asQWORD uic = asQWORD(asINT64(fc));
  4639. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  4640. // MSVC6 doesn't support this conversion
  4641. if( double(uic) != fc )
  4642. {
  4643. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4644. }
  4645. #endif
  4646. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4647. from->type.qwordValue = uic;
  4648. }
  4649. else if( from->type.dataType.IsEnumType() )
  4650. {
  4651. from->type.qwordValue = (asINT64)from->type.intValue;
  4652. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4653. }
  4654. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4655. {
  4656. // Convert to 64bit
  4657. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4658. from->type.qwordValue = (asINT64)(signed char)from->type.byteValue;
  4659. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4660. from->type.qwordValue = (asINT64)(short)from->type.wordValue;
  4661. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4662. from->type.qwordValue = (asINT64)from->type.intValue;
  4663. // Verify that it is possible to convert to unsigned without loosing negative
  4664. if( asINT64(from->type.qwordValue) < 0 )
  4665. {
  4666. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4667. }
  4668. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4669. }
  4670. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4671. {
  4672. // Verify that it is possible to convert to unsigned without loosing negative
  4673. if( asINT64(from->type.qwordValue) < 0 )
  4674. {
  4675. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4676. }
  4677. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4678. }
  4679. else if( from->type.dataType.IsUnsignedType() )
  4680. {
  4681. // Convert to 64bit
  4682. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4683. from->type.qwordValue = from->type.byteValue;
  4684. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4685. from->type.qwordValue = from->type.wordValue;
  4686. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4687. from->type.qwordValue = from->type.dwordValue;
  4688. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4689. }
  4690. }
  4691. else if( to.IsFloatType() )
  4692. {
  4693. if( from->type.dataType.IsDoubleType() )
  4694. {
  4695. double ic = from->type.doubleValue;
  4696. float fc = float(ic);
  4697. // Don't bother warning about this
  4698. // if( double(fc) != ic )
  4699. // {
  4700. // asCString str;
  4701. // str.Format(TXT_POSSIBLE_LOSS_OF_PRECISION);
  4702. // if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(str.AddressOf(), node);
  4703. // }
  4704. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4705. from->type.floatValue = fc;
  4706. }
  4707. else if( from->type.dataType.IsEnumType() )
  4708. {
  4709. float fc = float(from->type.intValue);
  4710. if( int(fc) != from->type.intValue )
  4711. {
  4712. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4713. }
  4714. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4715. from->type.floatValue = fc;
  4716. }
  4717. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4718. {
  4719. // Must properly convert value in case the from value is smaller
  4720. int ic;
  4721. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4722. ic = (signed char)from->type.byteValue;
  4723. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4724. ic = (short)from->type.wordValue;
  4725. else
  4726. ic = from->type.intValue;
  4727. float fc = float(ic);
  4728. if( int(fc) != ic )
  4729. {
  4730. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4731. }
  4732. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4733. from->type.floatValue = fc;
  4734. }
  4735. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4736. {
  4737. float fc = float(asINT64(from->type.qwordValue));
  4738. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  4739. {
  4740. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4741. }
  4742. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4743. from->type.floatValue = fc;
  4744. }
  4745. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4746. {
  4747. // Must properly convert value in case the from value is smaller
  4748. unsigned int uic;
  4749. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4750. uic = from->type.byteValue;
  4751. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4752. uic = from->type.wordValue;
  4753. else
  4754. uic = from->type.dwordValue;
  4755. float fc = float(uic);
  4756. if( (unsigned int)(fc) != uic )
  4757. {
  4758. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4759. }
  4760. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4761. from->type.floatValue = fc;
  4762. }
  4763. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4764. {
  4765. float fc = float((asINT64)from->type.qwordValue);
  4766. if( asQWORD(fc) != from->type.qwordValue )
  4767. {
  4768. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4769. }
  4770. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4771. from->type.floatValue = fc;
  4772. }
  4773. }
  4774. else if( to.IsDoubleType() )
  4775. {
  4776. if( from->type.dataType.IsFloatType() )
  4777. {
  4778. float ic = from->type.floatValue;
  4779. double fc = double(ic);
  4780. // Don't check for float->double
  4781. // if( float(fc) != ic )
  4782. // {
  4783. // acCString str;
  4784. // str.Format(TXT_NOT_EXACT_g_g_g, ic, fc, float(fc));
  4785. // if( !isExplicit ) Warning(str, node);
  4786. // }
  4787. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4788. from->type.doubleValue = fc;
  4789. }
  4790. else if( from->type.dataType.IsEnumType() )
  4791. {
  4792. double fc = double(from->type.intValue);
  4793. if( int(fc) != from->type.intValue )
  4794. {
  4795. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4796. }
  4797. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4798. from->type.doubleValue = fc;
  4799. }
  4800. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4801. {
  4802. // Must properly convert value in case the from value is smaller
  4803. int ic;
  4804. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4805. ic = (signed char)from->type.byteValue;
  4806. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4807. ic = (short)from->type.wordValue;
  4808. else
  4809. ic = from->type.intValue;
  4810. double fc = double(ic);
  4811. if( int(fc) != ic )
  4812. {
  4813. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4814. }
  4815. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4816. from->type.doubleValue = fc;
  4817. }
  4818. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4819. {
  4820. double fc = double(asINT64(from->type.qwordValue));
  4821. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  4822. {
  4823. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4824. }
  4825. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4826. from->type.doubleValue = fc;
  4827. }
  4828. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4829. {
  4830. // Must properly convert value in case the from value is smaller
  4831. unsigned int uic;
  4832. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4833. uic = from->type.byteValue;
  4834. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4835. uic = from->type.wordValue;
  4836. else
  4837. uic = from->type.dwordValue;
  4838. double fc = double(uic);
  4839. if( (unsigned int)(fc) != uic )
  4840. {
  4841. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4842. }
  4843. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4844. from->type.doubleValue = fc;
  4845. }
  4846. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4847. {
  4848. double fc = double((asINT64)from->type.qwordValue);
  4849. if( asQWORD(fc) != from->type.qwordValue )
  4850. {
  4851. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4852. }
  4853. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4854. from->type.doubleValue = fc;
  4855. }
  4856. }
  4857. }
  4858. int asCCompiler::DoAssignment(asSExprContext *ctx, asSExprContext *lctx, asSExprContext *rctx, asCScriptNode *lexpr, asCScriptNode *rexpr, int op, asCScriptNode *opNode)
  4859. {
  4860. // Implicit handle types should always be treated as handles in assignments
  4861. if (lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  4862. {
  4863. lctx->type.dataType.MakeHandle(true);
  4864. lctx->type.isExplicitHandle = true;
  4865. }
  4866. // Urho3D: if there is a handle type, and it does not have an overloaded assignment operator, convert to an explicit handle
  4867. // for scripting convenience. (For the Urho3D handle types, value assignment is not supported)
  4868. if (lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle && !lctx->type.dataType.GetBehaviour()->copy)
  4869. lctx->type.isExplicitHandle = true;
  4870. // If the left hand expression is a property accessor, then that should be used
  4871. // to do the assignment instead of the ordinary operator. The exception is when
  4872. // the property accessor is for a handle property, and the operation is a value
  4873. // assignment.
  4874. if( (lctx->property_get || lctx->property_set) &&
  4875. !(lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle) )
  4876. {
  4877. if( op != ttAssignment )
  4878. {
  4879. // TODO: getset: We may actually be able to support this, if we can
  4880. // guarantee that the object reference will stay valid
  4881. // between the calls to the get and set accessors.
  4882. // Process the property to free the memory
  4883. ProcessPropertySetAccessor(lctx, rctx, opNode);
  4884. // Compound assignments are not allowed for properties
  4885. Error(TXT_COMPOUND_ASGN_WITH_PROP, opNode);
  4886. return -1;
  4887. }
  4888. // It is not allowed to do a handle assignment on a property
  4889. // accessor that doesn't take a handle in the set accessor.
  4890. if( lctx->property_set && lctx->type.isExplicitHandle )
  4891. {
  4892. // set_opIndex has 2 arguments, where as normal setters have only 1
  4893. asCArray<asCDataType>& parameterTypes =
  4894. builder->GetFunctionDescription(lctx->property_set)->parameterTypes;
  4895. if( !parameterTypes[parameterTypes.GetLength() - 1].IsObjectHandle() )
  4896. {
  4897. // Process the property to free the memory
  4898. ProcessPropertySetAccessor(lctx, rctx, opNode);
  4899. Error(TXT_HANDLE_ASSIGN_ON_NON_HANDLE_PROP, opNode);
  4900. return -1;
  4901. }
  4902. }
  4903. MergeExprBytecodeAndType(ctx, lctx);
  4904. return ProcessPropertySetAccessor(ctx, rctx, opNode);
  4905. }
  4906. else if( lctx->property_get && lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  4907. {
  4908. // Get the handle to the object that will be used for the value assignment
  4909. ProcessPropertyGetAccessor(lctx, opNode);
  4910. }
  4911. if( lctx->type.dataType.IsPrimitive() )
  4912. {
  4913. if( !lctx->type.isLValue )
  4914. {
  4915. Error(TXT_NOT_LVALUE, lexpr);
  4916. return -1;
  4917. }
  4918. if( op != ttAssignment )
  4919. {
  4920. // Compute the operator before the assignment
  4921. asCTypeInfo lvalue = lctx->type;
  4922. if( lctx->type.isTemporary && !lctx->type.isVariable )
  4923. {
  4924. // The temporary variable must not be freed until the
  4925. // assignment has been performed. lvalue still holds
  4926. // the information about the temporary variable
  4927. lctx->type.isTemporary = false;
  4928. }
  4929. asSExprContext o(engine);
  4930. CompileOperator(opNode, lctx, rctx, &o);
  4931. MergeExprBytecode(rctx, &o);
  4932. rctx->type = o.type;
  4933. // Convert the rvalue to the right type and validate it
  4934. PrepareForAssignment(&lvalue.dataType, rctx, rexpr, false);
  4935. MergeExprBytecode(ctx, rctx);
  4936. lctx->type = lvalue;
  4937. // The lvalue continues the same, either it was a variable, or a reference in the register
  4938. }
  4939. else
  4940. {
  4941. // Convert the rvalue to the right type and validate it
  4942. PrepareForAssignment(&lctx->type.dataType, rctx, rexpr, false, lctx);
  4943. MergeExprBytecode(ctx, rctx);
  4944. MergeExprBytecode(ctx, lctx);
  4945. }
  4946. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4947. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4948. ctx->type = lctx->type;
  4949. }
  4950. else if( lctx->type.isExplicitHandle )
  4951. {
  4952. if( !lctx->type.isLValue )
  4953. {
  4954. Error(TXT_NOT_LVALUE, lexpr);
  4955. return -1;
  4956. }
  4957. // Object handles don't have any compound assignment operators
  4958. if( op != ttAssignment )
  4959. {
  4960. asCString str;
  4961. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4962. Error(str.AddressOf(), lexpr);
  4963. return -1;
  4964. }
  4965. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  4966. {
  4967. // The object is a value type but that should be treated as a handle
  4968. // TODO: handle: Make sure the right hand value is a handle
  4969. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  4970. {
  4971. // An overloaded assignment operator was found (or a compilation error occured)
  4972. return 0;
  4973. }
  4974. // The object must implement the opAssign method
  4975. Error(TXT_NO_APPROPRIATE_OPASSIGN, opNode);
  4976. return -1;
  4977. }
  4978. else
  4979. {
  4980. asCDataType dt = lctx->type.dataType;
  4981. dt.MakeReference(false);
  4982. PrepareArgument(&dt, rctx, rexpr, true, 1);
  4983. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4984. {
  4985. asCString str;
  4986. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  4987. Error(str.AddressOf(), rexpr);
  4988. return -1;
  4989. }
  4990. MergeExprBytecode(ctx, rctx);
  4991. MergeExprBytecode(ctx, lctx);
  4992. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  4993. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4994. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4995. ctx->type = rctx->type;
  4996. }
  4997. }
  4998. else // if( lctx->type.dataType.IsObject() )
  4999. {
  5000. // An ASHANDLE type must not allow a value assignment, as
  5001. // the opAssign operator is used for the handle assignment
  5002. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  5003. {
  5004. asCString str;
  5005. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  5006. Error(str.AddressOf(), lexpr);
  5007. return -1;
  5008. }
  5009. // The lvalue reference may be marked as a temporary, if for example
  5010. // it was originated as a handle returned from a function. In such
  5011. // cases it must be possible to assign values to it anyway.
  5012. if( lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  5013. {
  5014. // Convert the handle to a object reference
  5015. asCDataType to;
  5016. to = lctx->type.dataType;
  5017. to.MakeHandle(false);
  5018. ImplicitConversion(lctx, to, lexpr, asIC_IMPLICIT_CONV);
  5019. lctx->type.isLValue = true; // Handle may not have been an lvalue, but the dereferenced object is
  5020. }
  5021. // Check for overloaded assignment operator
  5022. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  5023. {
  5024. // An overloaded assignment operator was found (or a compilation error occured)
  5025. return 0;
  5026. }
  5027. // No registered operator was found. In case the operation is a direct
  5028. // assignment and the rvalue is the same type as the lvalue, then we can
  5029. // still use the byte-for-byte copy to do the assignment
  5030. if( op != ttAssignment )
  5031. {
  5032. asCString str;
  5033. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  5034. Error(str.AddressOf(), lexpr);
  5035. return -1;
  5036. }
  5037. // If the left hand expression is simple, i.e. without any
  5038. // function calls or allocations of memory, then we can avoid
  5039. // doing a copy of the right hand expression (done by PrepareArgument).
  5040. // Instead the reference to the value can be placed directly on the
  5041. // stack.
  5042. //
  5043. // This optimization should only be done for value types, where
  5044. // the application developer is responsible for making the
  5045. // implementation safe against unwanted destruction of the input
  5046. // reference before the time.
  5047. bool simpleExpr = (lctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) && lctx->bc.IsSimpleExpression();
  5048. // Implicitly convert the rvalue to the type of the lvalue
  5049. if( !lctx->type.dataType.IsEqualExceptRefAndConst(rctx->type.dataType) )
  5050. simpleExpr = false;
  5051. if( !simpleExpr )
  5052. {
  5053. asCDataType dt = lctx->type.dataType;
  5054. dt.MakeReference(true);
  5055. dt.MakeReadOnly(true);
  5056. PrepareArgument(&dt, rctx, rexpr, true, 1);
  5057. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  5058. {
  5059. asCString str;
  5060. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  5061. Error(str.AddressOf(), rexpr);
  5062. return -1;
  5063. }
  5064. }
  5065. else
  5066. {
  5067. // Process any property accessor first, before placing the final reference on the stack
  5068. ProcessPropertyGetAccessor(rctx, rexpr);
  5069. if( rctx->type.dataType.IsReference() && (!(rctx->type.isVariable || rctx->type.isTemporary) || IsVariableOnHeap(rctx->type.stackOffset)) )
  5070. rctx->bc.Instr(asBC_RDSPtr);
  5071. }
  5072. MergeExprBytecode(ctx, rctx);
  5073. MergeExprBytecode(ctx, lctx);
  5074. if( !simpleExpr )
  5075. {
  5076. if( (rctx->type.isVariable || rctx->type.isTemporary) && !IsVariableOnHeap(rctx->type.stackOffset) )
  5077. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  5078. // as the value allocated on the stack is guaranteed to be safe.
  5079. // The bytecode optimizer should be able to determine this and optimize away the VAR + GETREF
  5080. ctx->bc.InstrWORD(asBC_GETREF, AS_PTR_SIZE);
  5081. else
  5082. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  5083. }
  5084. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  5085. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  5086. ctx->type = lctx->type;
  5087. }
  5088. return 0;
  5089. }
  5090. int asCCompiler::CompileAssignment(asCScriptNode *expr, asSExprContext *ctx)
  5091. {
  5092. asCScriptNode *lexpr = expr->firstChild;
  5093. if( lexpr->next )
  5094. {
  5095. // Compile the two expression terms
  5096. asSExprContext lctx(engine), rctx(engine);
  5097. int rr = CompileAssignment(lexpr->next->next, &rctx);
  5098. int lr = CompileCondition(lexpr, &lctx);
  5099. if( lr >= 0 && rr >= 0 )
  5100. return DoAssignment(ctx, &lctx, &rctx, lexpr, lexpr->next->next, lexpr->next->tokenType, lexpr->next);
  5101. // Since the operands failed, the assignment was not computed
  5102. ctx->type.SetDummy();
  5103. return -1;
  5104. }
  5105. return CompileCondition(lexpr, ctx);
  5106. }
  5107. int asCCompiler::CompileCondition(asCScriptNode *expr, asSExprContext *ctx)
  5108. {
  5109. asCTypeInfo ctype;
  5110. // Compile the conditional expression
  5111. asCScriptNode *cexpr = expr->firstChild;
  5112. if( cexpr->next )
  5113. {
  5114. //-------------------------------
  5115. // Compile the condition
  5116. asSExprContext e(engine);
  5117. int r = CompileExpression(cexpr, &e);
  5118. if( r < 0 )
  5119. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  5120. if( r >= 0 && !e.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  5121. {
  5122. Error(TXT_EXPR_MUST_BE_BOOL, cexpr);
  5123. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  5124. }
  5125. ctype = e.type;
  5126. ProcessPropertyGetAccessor(&e, cexpr);
  5127. if( e.type.dataType.IsReference() ) ConvertToVariable(&e);
  5128. ProcessDeferredParams(&e);
  5129. //-------------------------------
  5130. // Compile the left expression
  5131. asSExprContext le(engine);
  5132. int lr = CompileAssignment(cexpr->next, &le);
  5133. //-------------------------------
  5134. // Compile the right expression
  5135. asSExprContext re(engine);
  5136. int rr = CompileAssignment(cexpr->next->next, &re);
  5137. if( lr >= 0 && rr >= 0 )
  5138. {
  5139. ProcessPropertyGetAccessor(&le, cexpr->next);
  5140. ProcessPropertyGetAccessor(&re, cexpr->next->next);
  5141. bool isExplicitHandle = le.type.isExplicitHandle || re.type.isExplicitHandle;
  5142. // Allow a 0 or null in the first case to be implicitly converted to the second type
  5143. if( le.type.isConstant && le.type.intValue == 0 && le.type.dataType.IsUnsignedType() )
  5144. {
  5145. asCDataType to = re.type.dataType;
  5146. to.MakeReference(false);
  5147. to.MakeReadOnly(true);
  5148. ImplicitConversionConstant(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  5149. }
  5150. else if( le.type.IsNullConstant() )
  5151. {
  5152. asCDataType to = re.type.dataType;
  5153. to.MakeHandle(true);
  5154. ImplicitConversion(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  5155. }
  5156. //---------------------------------
  5157. // Output the byte code
  5158. int afterLabel = nextLabel++;
  5159. int elseLabel = nextLabel++;
  5160. // If left expression is void, then we don't need to store the result
  5161. if( le.type.dataType.IsEqualExceptConst(asCDataType::CreatePrimitive(ttVoid, false)) )
  5162. {
  5163. // Put the code for the condition expression on the output
  5164. MergeExprBytecode(ctx, &e);
  5165. // Added the branch decision
  5166. ctx->type = e.type;
  5167. ConvertToVariable(ctx);
  5168. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  5169. ctx->bc.Instr(asBC_ClrHi);
  5170. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  5171. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  5172. // Add the left expression
  5173. MergeExprBytecode(ctx, &le);
  5174. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  5175. // Add the right expression
  5176. ctx->bc.Label((short)elseLabel);
  5177. MergeExprBytecode(ctx, &re);
  5178. ctx->bc.Label((short)afterLabel);
  5179. // Make sure both expressions have the same type
  5180. if( le.type.dataType != re.type.dataType )
  5181. Error(TXT_BOTH_MUST_BE_SAME, expr);
  5182. // Set the type of the result
  5183. ctx->type = le.type;
  5184. }
  5185. else
  5186. {
  5187. // Allocate temporary variable and copy the result to that one
  5188. asCTypeInfo temp;
  5189. temp = le.type;
  5190. temp.dataType.MakeReference(false);
  5191. temp.dataType.MakeReadOnly(false);
  5192. // Make sure the variable isn't used in the initial expression
  5193. int offset = AllocateVariableNotIn(temp.dataType, true, false, &e);
  5194. temp.SetVariable(temp.dataType, offset, true);
  5195. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  5196. CallDefaultConstructor(temp.dataType, offset, IsVariableOnHeap(offset), &ctx->bc, expr);
  5197. // Put the code for the condition expression on the output
  5198. MergeExprBytecode(ctx, &e);
  5199. // Add the branch decision
  5200. ctx->type = e.type;
  5201. ConvertToVariable(ctx);
  5202. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  5203. ctx->bc.Instr(asBC_ClrHi);
  5204. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  5205. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  5206. // Assign the result of the left expression to the temporary variable
  5207. asCTypeInfo rtemp;
  5208. rtemp = temp;
  5209. if( rtemp.dataType.IsObjectHandle() )
  5210. rtemp.isExplicitHandle = true;
  5211. PrepareForAssignment(&rtemp.dataType, &le, cexpr->next, true);
  5212. MergeExprBytecode(ctx, &le);
  5213. if( !rtemp.dataType.IsPrimitive() )
  5214. {
  5215. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5216. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  5217. }
  5218. PerformAssignment(&rtemp, &le.type, &ctx->bc, cexpr->next);
  5219. if( !rtemp.dataType.IsPrimitive() )
  5220. ctx->bc.Instr(asBC_PopPtr); // Pop the original value (always a pointer)
  5221. // Release the old temporary variable
  5222. ReleaseTemporaryVariable(le.type, &ctx->bc);
  5223. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  5224. // Start of the right expression
  5225. ctx->bc.Label((short)elseLabel);
  5226. // Copy the result to the same temporary variable
  5227. PrepareForAssignment(&rtemp.dataType, &re, cexpr->next, true);
  5228. MergeExprBytecode(ctx, &re);
  5229. if( !rtemp.dataType.IsPrimitive() )
  5230. {
  5231. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5232. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  5233. }
  5234. PerformAssignment(&rtemp, &re.type, &ctx->bc, cexpr->next);
  5235. if( !rtemp.dataType.IsPrimitive() )
  5236. ctx->bc.Instr(asBC_PopPtr); // Pop the original value (always a pointer)
  5237. // Release the old temporary variable
  5238. ReleaseTemporaryVariable(re.type, &ctx->bc);
  5239. ctx->bc.Label((short)afterLabel);
  5240. // Make sure both expressions have the same type
  5241. if( !le.type.dataType.IsEqualExceptConst(re.type.dataType) )
  5242. Error(TXT_BOTH_MUST_BE_SAME, expr);
  5243. // Set the temporary variable as output
  5244. ctx->type = rtemp;
  5245. ctx->type.isExplicitHandle = isExplicitHandle;
  5246. if( !ctx->type.dataType.IsPrimitive() )
  5247. {
  5248. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5249. ctx->type.dataType.MakeReference(IsVariableOnHeap(offset));
  5250. }
  5251. // Make sure the output isn't marked as being a literal constant
  5252. ctx->type.isConstant = false;
  5253. }
  5254. }
  5255. else
  5256. {
  5257. ctx->type.SetDummy();
  5258. return -1;
  5259. }
  5260. }
  5261. else
  5262. return CompileExpression(cexpr, ctx);
  5263. return 0;
  5264. }
  5265. int asCCompiler::CompileExpression(asCScriptNode *expr, asSExprContext *ctx)
  5266. {
  5267. asASSERT(expr->nodeType == snExpression);
  5268. // Convert to polish post fix, i.e: a+b => ab+
  5269. // The algorithm that I've implemented here is similar to
  5270. // Djikstra's Shunting Yard algorithm, though I didn't know it at the time.
  5271. // ref: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
  5272. // Count the nodes in order to preallocate the buffers
  5273. int count = 0;
  5274. asCScriptNode *node = expr->firstChild;
  5275. while( node )
  5276. {
  5277. count++;
  5278. node = node->next;
  5279. }
  5280. asCArray<asCScriptNode *> stack(count);
  5281. asCArray<asCScriptNode *> stack2(count);
  5282. asCArray<asCScriptNode *> postfix(count);
  5283. node = expr->firstChild;
  5284. while( node )
  5285. {
  5286. int precedence = GetPrecedence(node);
  5287. while( stack.GetLength() > 0 &&
  5288. precedence <= GetPrecedence(stack[stack.GetLength()-1]) )
  5289. stack2.PushLast(stack.PopLast());
  5290. stack.PushLast(node);
  5291. node = node->next;
  5292. }
  5293. while( stack.GetLength() > 0 )
  5294. stack2.PushLast(stack.PopLast());
  5295. // We need to swap operands so that the left
  5296. // operand is always computed before the right
  5297. SwapPostFixOperands(stack2, postfix);
  5298. // Compile the postfix formatted expression
  5299. return CompilePostFixExpression(&postfix, ctx);
  5300. }
  5301. void asCCompiler::SwapPostFixOperands(asCArray<asCScriptNode *> &postfix, asCArray<asCScriptNode *> &target)
  5302. {
  5303. if( postfix.GetLength() == 0 ) return;
  5304. asCScriptNode *node = postfix.PopLast();
  5305. if( node->nodeType == snExprTerm )
  5306. {
  5307. target.PushLast(node);
  5308. return;
  5309. }
  5310. SwapPostFixOperands(postfix, target);
  5311. SwapPostFixOperands(postfix, target);
  5312. target.PushLast(node);
  5313. }
  5314. int asCCompiler::CompilePostFixExpression(asCArray<asCScriptNode *> *postfix, asSExprContext *ctx)
  5315. {
  5316. // Shouldn't send any byte code
  5317. asASSERT(ctx->bc.GetLastInstr() == -1);
  5318. // Set the context to a dummy type to avoid further
  5319. // errors in case the expression fails to compile
  5320. ctx->type.SetDummy();
  5321. // Pop the last node
  5322. asCScriptNode *node = postfix->PopLast();
  5323. ctx->exprNode = node;
  5324. // If term, compile the term
  5325. if( node->nodeType == snExprTerm )
  5326. return CompileExpressionTerm(node, ctx);
  5327. // Compile the two expression terms
  5328. asSExprContext r(engine), l(engine);
  5329. int ret;
  5330. ret = CompilePostFixExpression(postfix, &l); if( ret < 0 ) return ret;
  5331. ret = CompilePostFixExpression(postfix, &r); if( ret < 0 ) return ret;
  5332. // Compile the operation
  5333. return CompileOperator(node, &l, &r, ctx);
  5334. }
  5335. int asCCompiler::CompileExpressionTerm(asCScriptNode *node, asSExprContext *ctx)
  5336. {
  5337. // Shouldn't send any byte code
  5338. asASSERT(ctx->bc.GetLastInstr() == -1);
  5339. // Set the type as a dummy by default, in case of any compiler errors
  5340. ctx->type.SetDummy();
  5341. // Compile the value node
  5342. asCScriptNode *vnode = node->firstChild;
  5343. while( vnode->nodeType != snExprValue )
  5344. vnode = vnode->next;
  5345. asSExprContext v(engine);
  5346. int r = CompileExpressionValue(vnode, &v); if( r < 0 ) return r;
  5347. // Compile post fix operators
  5348. asCScriptNode *pnode = vnode->next;
  5349. while( pnode )
  5350. {
  5351. r = CompileExpressionPostOp(pnode, &v); if( r < 0 ) return r;
  5352. pnode = pnode->next;
  5353. }
  5354. // Compile pre fix operators
  5355. pnode = vnode->prev;
  5356. while( pnode )
  5357. {
  5358. r = CompileExpressionPreOp(pnode, &v); if( r < 0 ) return r;
  5359. pnode = pnode->prev;
  5360. }
  5361. // Return the byte code and final type description
  5362. MergeExprBytecodeAndType(ctx, &v);
  5363. return 0;
  5364. }
  5365. int asCCompiler::CompileVariableAccess(const asCString &name, const asCString &scope, asSExprContext *ctx, asCScriptNode *errNode, bool isOptional, bool noFunction, asCObjectType *objType)
  5366. {
  5367. bool found = false;
  5368. // It is a local variable or parameter?
  5369. // This is not accessible by default arg expressions
  5370. sVariable *v = 0;
  5371. if( !isCompilingDefaultArg && scope == "" && !objType )
  5372. v = variables->GetVariable(name.AddressOf());
  5373. if( v )
  5374. {
  5375. found = true;
  5376. if( v->isPureConstant )
  5377. ctx->type.SetConstantQW(v->type, v->constantValue);
  5378. else if( v->type.IsPrimitive() )
  5379. {
  5380. if( v->type.IsReference() )
  5381. {
  5382. // Copy the reference into the register
  5383. ctx->bc.InstrSHORT(asBC_PshVPtr, (short)v->stackOffset);
  5384. ctx->bc.Instr(asBC_PopRPtr);
  5385. ctx->type.Set(v->type);
  5386. }
  5387. else
  5388. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5389. ctx->type.isLValue = true;
  5390. }
  5391. else
  5392. {
  5393. ctx->bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  5394. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5395. // If the variable is allocated on the heap we have a reference,
  5396. // otherwise the actual object pointer is pushed on the stack.
  5397. if( v->onHeap || v->type.IsObjectHandle() ) ctx->type.dataType.MakeReference(true);
  5398. // Implicitly dereference handle parameters sent by reference
  5399. if( v->type.IsReference() && (!v->type.IsObject() || v->type.IsObjectHandle()) )
  5400. ctx->bc.Instr(asBC_RDSPtr);
  5401. ctx->type.isLValue = true;
  5402. }
  5403. }
  5404. // Is it a class member?
  5405. // This is not accessible by default arg expressions
  5406. if( !isCompilingDefaultArg && !found && ((objType) || (outFunc && outFunc->objectType && scope == "")) )
  5407. {
  5408. if( name == THIS_TOKEN && !objType )
  5409. {
  5410. asCDataType dt = asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly);
  5411. // The object pointer is located at stack position 0
  5412. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5413. ctx->type.SetVariable(dt, 0, false);
  5414. ctx->type.dataType.MakeReference(true);
  5415. ctx->type.isLValue = true;
  5416. found = true;
  5417. }
  5418. if( !found )
  5419. {
  5420. // See if there are any matching property accessors
  5421. asSExprContext access(engine);
  5422. if( objType )
  5423. access.type.Set(asCDataType::CreateObject(objType, false));
  5424. else
  5425. access.type.Set(asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly));
  5426. access.type.dataType.MakeReference(true);
  5427. int r = 0;
  5428. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5429. {
  5430. // This is an index access, check if there is a property accessor that takes an index arg
  5431. asSExprContext dummyArg(engine);
  5432. r = FindPropertyAccessor(name, &access, &dummyArg, errNode, true);
  5433. }
  5434. if( r == 0 )
  5435. {
  5436. // Normal property access
  5437. r = FindPropertyAccessor(name, &access, errNode, true);
  5438. }
  5439. if( r < 0 ) return -1;
  5440. if( access.property_get || access.property_set )
  5441. {
  5442. if( !objType )
  5443. {
  5444. // Prepare the bytecode for the member access
  5445. // This is only done when accessing through the implicit this pointer
  5446. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5447. }
  5448. MergeExprBytecodeAndType(ctx, &access);
  5449. found = true;
  5450. }
  5451. }
  5452. if( !found )
  5453. {
  5454. asCDataType dt;
  5455. if( objType )
  5456. dt = asCDataType::CreateObject(objType, false);
  5457. else
  5458. dt = asCDataType::CreateObject(outFunc->objectType, false);
  5459. asCObjectProperty *prop = builder->GetObjectProperty(dt, name.AddressOf());
  5460. if( prop )
  5461. {
  5462. if( !objType )
  5463. {
  5464. // The object pointer is located at stack position 0
  5465. // This is only done when accessing through the implicit this pointer
  5466. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5467. ctx->type.SetVariable(dt, 0, false);
  5468. ctx->type.dataType.MakeReference(true);
  5469. Dereference(ctx, true);
  5470. }
  5471. // TODO: This is the same as what is in CompileExpressionPostOp
  5472. // Put the offset on the stack
  5473. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(dt));
  5474. if( prop->type.IsReference() )
  5475. ctx->bc.Instr(asBC_RDSPtr);
  5476. // Reference to primitive must be stored in the temp register
  5477. if( prop->type.IsPrimitive() )
  5478. {
  5479. // TODO: runtime optimize: The ADD offset command should store the reference in the register directly
  5480. ctx->bc.Instr(asBC_PopRPtr);
  5481. }
  5482. // Set the new type (keeping info about temp variable)
  5483. ctx->type.dataType = prop->type;
  5484. ctx->type.dataType.MakeReference(true);
  5485. ctx->type.isVariable = false;
  5486. ctx->type.isLValue = true;
  5487. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  5488. {
  5489. // Objects that are members are not references
  5490. ctx->type.dataType.MakeReference(false);
  5491. }
  5492. // If the object reference is const, the property will also be const
  5493. ctx->type.dataType.MakeReadOnly(outFunc->isReadOnly);
  5494. found = true;
  5495. }
  5496. }
  5497. }
  5498. // Is it a global property?
  5499. if( !found && !objType )
  5500. {
  5501. // See if there are any matching global property accessors
  5502. // TODO: namespace: Support namespaces for global property accessors too
  5503. asSExprContext access(engine);
  5504. int r = 0;
  5505. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5506. {
  5507. // This is an index access, check if there is a property accessor that takes an index arg
  5508. asSExprContext dummyArg(engine);
  5509. r = FindPropertyAccessor(name, &access, &dummyArg, errNode);
  5510. }
  5511. if( r == 0 )
  5512. {
  5513. // Normal property access
  5514. r = FindPropertyAccessor(name, &access, errNode);
  5515. }
  5516. if( r < 0 ) return -1;
  5517. if( access.property_get || access.property_set )
  5518. {
  5519. // Prepare the bytecode for the function call
  5520. MergeExprBytecodeAndType(ctx, &access);
  5521. found = true;
  5522. }
  5523. // See if there is any matching global property
  5524. if( !found )
  5525. {
  5526. bool isCompiled = true;
  5527. bool isPureConstant = false;
  5528. bool isAppProp = false;
  5529. asQWORD constantValue;
  5530. asCString ns = scope == "::" ? "" : scope;
  5531. if( ns == "" )
  5532. {
  5533. if( outFunc->nameSpace != "" )
  5534. ns = outFunc->nameSpace;
  5535. else if( outFunc->objectType && outFunc->objectType->nameSpace != "" )
  5536. ns = outFunc->objectType->nameSpace;
  5537. }
  5538. asCGlobalProperty *prop = builder->GetGlobalProperty(name.AddressOf(), ns, &isCompiled, &isPureConstant, &constantValue, &isAppProp);
  5539. if( prop )
  5540. {
  5541. found = true;
  5542. // Verify that the global property has been compiled already
  5543. if( isCompiled )
  5544. {
  5545. if( ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  5546. {
  5547. ctx->type.dataType.MakeHandle(true);
  5548. ctx->type.isExplicitHandle = true;
  5549. }
  5550. // If the global property is a pure constant
  5551. // we can allow the compiler to optimize it. Pure
  5552. // constants are global constant variables that were
  5553. // initialized by literal constants.
  5554. if( isPureConstant )
  5555. ctx->type.SetConstantQW(prop->type, constantValue);
  5556. else
  5557. {
  5558. // A shared type must not access global vars, unless they
  5559. // too are shared, e.g. application registered vars
  5560. if( outFunc->IsShared() )
  5561. {
  5562. if( !isAppProp )
  5563. {
  5564. asCString str;
  5565. str.Format(TXT_SHARED_CANNOT_ACCESS_NON_SHARED_VAR_s, prop->name.AddressOf());
  5566. Error(str.AddressOf(), errNode);
  5567. // Allow the compilation to continue to catch other problems
  5568. }
  5569. }
  5570. ctx->type.Set(prop->type);
  5571. ctx->type.dataType.MakeReference(true);
  5572. ctx->type.isLValue = true;
  5573. if( ctx->type.dataType.IsPrimitive() )
  5574. {
  5575. // Load the address of the variable into the register
  5576. ctx->bc.InstrPTR(asBC_LDG, prop->GetAddressOfValue());
  5577. }
  5578. else
  5579. {
  5580. // Push the address of the variable on the stack
  5581. ctx->bc.InstrPTR(asBC_PGA, prop->GetAddressOfValue());
  5582. // If the object is a value type, then we must validate the existance,
  5583. // as it could potentially be accessed before it is initialized.
  5584. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_VALUE ||
  5585. !ctx->type.dataType.IsObjectHandle() )
  5586. {
  5587. // TODO: runtime optimize: This is not necessary for application registered properties
  5588. ctx->bc.Instr(asBC_ChkRefS);
  5589. }
  5590. }
  5591. }
  5592. }
  5593. else
  5594. {
  5595. asCString str;
  5596. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, prop->name.AddressOf());
  5597. Error(str.AddressOf(), errNode);
  5598. return -1;
  5599. }
  5600. }
  5601. }
  5602. }
  5603. // Is it the name of a global function?
  5604. if( !noFunction && !found && !objType )
  5605. {
  5606. asCArray<int> funcs;
  5607. asCString ns = scope == "::" ? "" : scope;
  5608. if( ns == "" )
  5609. {
  5610. if( outFunc->nameSpace != "" )
  5611. ns = outFunc->nameSpace;
  5612. else if( outFunc->objectType && outFunc->objectType->nameSpace != "" )
  5613. ns = outFunc->objectType->nameSpace;
  5614. }
  5615. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  5616. if( funcs.GetLength() > 1 )
  5617. {
  5618. // TODO: funcdef: If multiple functions are found, then the compiler should defer the decision
  5619. // to which one it should use until the value is actually used.
  5620. //
  5621. // - assigning the function pointer to a variable
  5622. // - performing an explicit cast
  5623. // - passing the function pointer to a function as parameter
  5624. asCString str;
  5625. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, name.AddressOf());
  5626. Error(str.AddressOf(), errNode);
  5627. return -1;
  5628. }
  5629. else if( funcs.GetLength() == 1 )
  5630. {
  5631. found = true;
  5632. // A shared object may not access global functions unless they too are shared (e.g. registered functions)
  5633. if( !builder->GetFunctionDescription(funcs[0])->IsShared() &&
  5634. outFunc->IsShared() )
  5635. {
  5636. asCString msg;
  5637. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, builder->GetFunctionDescription(funcs[0])->GetDeclaration());
  5638. Error(msg.AddressOf(), errNode);
  5639. return -1;
  5640. }
  5641. // Push the function pointer on the stack
  5642. ctx->bc.InstrPTR(asBC_FuncPtr, builder->GetFunctionDescription(funcs[0]));
  5643. ctx->type.Set(asCDataType::CreateFuncDef(builder->GetFunctionDescription(funcs[0])));
  5644. }
  5645. }
  5646. // Is it an enum value?
  5647. if( !found && !objType )
  5648. {
  5649. // The enum type may be declared in a namespace too
  5650. asCObjectType *scopeType = 0;
  5651. if( scope != "" && scope != "::" )
  5652. {
  5653. // Use the last scope name as the enum type
  5654. asCString enumType = scope;
  5655. asCString ns;
  5656. int p = scope.FindLast("::");
  5657. if( p != -1 )
  5658. {
  5659. enumType = scope.SubString(p+2);
  5660. ns = scope.SubString(0, p);
  5661. }
  5662. // resolve the type before the scope
  5663. scopeType = builder->GetObjectType(enumType.AddressOf(), ns);
  5664. }
  5665. asDWORD value = 0;
  5666. asCDataType dt;
  5667. if( scopeType && builder->GetEnumValueFromObjectType(scopeType, name.AddressOf(), dt, value) )
  5668. {
  5669. // scoped enum value found
  5670. found = true;
  5671. }
  5672. else if( !engine->ep.requireEnumScope )
  5673. {
  5674. // Look for the enum value without explicitly informing the enum type
  5675. asCString ns = scope == "::" ? "" : scope;
  5676. if( ns == "" )
  5677. {
  5678. // Use implicit scope from the current function that is being compiled
  5679. // TODO: cleanup: This is repeated in a lot of places. Should use function for it
  5680. if( outFunc->nameSpace != "" )
  5681. ns = outFunc->nameSpace;
  5682. else if( outFunc->objectType && outFunc->objectType->nameSpace != "" )
  5683. ns = outFunc->objectType->nameSpace;
  5684. }
  5685. int e = builder->GetEnumValue(name.AddressOf(), dt, value, ns);
  5686. if( e )
  5687. {
  5688. found = true;
  5689. if( e == 2 )
  5690. {
  5691. Error(TXT_FOUND_MULTIPLE_ENUM_VALUES, errNode);
  5692. }
  5693. }
  5694. }
  5695. if( found )
  5696. {
  5697. // Even if the enum type is not shared, and we're compiling a shared object,
  5698. // the use of the values are still allowed, since they are treated as constants.
  5699. // an enum value was resolved
  5700. ctx->type.SetConstantDW(dt, value);
  5701. }
  5702. }
  5703. // The name doesn't match any variable
  5704. if( !found )
  5705. {
  5706. // Give dummy value
  5707. ctx->type.SetDummy();
  5708. if( !isOptional )
  5709. {
  5710. // Prepend the scope to the name for the error message
  5711. asCString ename;
  5712. if( scope != "" && scope != "::" )
  5713. ename = scope + "::";
  5714. else
  5715. ename = scope;
  5716. ename += name;
  5717. asCString str;
  5718. str.Format(TXT_s_NOT_DECLARED, ename.AddressOf());
  5719. Error(str.AddressOf(), errNode);
  5720. // Declare the variable now so that it will not be reported again
  5721. variables->DeclareVariable(name.AddressOf(), asCDataType::CreatePrimitive(ttInt, false), 0x7FFF, true);
  5722. // Mark the variable as initialized so that the user will not be bother by it again
  5723. sVariable *v = variables->GetVariable(name.AddressOf());
  5724. asASSERT(v);
  5725. if( v ) v->isInitialized = true;
  5726. }
  5727. // Return -1 to signal that the variable wasn't found
  5728. return -1;
  5729. }
  5730. return 0;
  5731. }
  5732. int asCCompiler::CompileExpressionValue(asCScriptNode *node, asSExprContext *ctx)
  5733. {
  5734. // Shouldn't receive any byte code
  5735. asASSERT(ctx->bc.GetLastInstr() == -1);
  5736. asCScriptNode *vnode = node->firstChild;
  5737. ctx->exprNode = vnode;
  5738. if( vnode->nodeType == snVariableAccess )
  5739. {
  5740. // Determine the scope resolution of the variable
  5741. asCString scope = builder->GetScopeFromNode(vnode->firstChild, script, &vnode);
  5742. // Determine the name of the variable
  5743. asASSERT(vnode->nodeType == snIdentifier );
  5744. asCString name(&script->code[vnode->tokenPos], vnode->tokenLength);
  5745. return CompileVariableAccess(name, scope, ctx, node);
  5746. }
  5747. else if( vnode->nodeType == snConstant )
  5748. {
  5749. if( vnode->tokenType == ttIntConstant )
  5750. {
  5751. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5752. asQWORD val = asStringScanUInt64(value.AddressOf(), 10, 0);
  5753. // Do we need 64 bits?
  5754. if( val>>32 )
  5755. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  5756. else
  5757. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  5758. }
  5759. else if( vnode->tokenType == ttBitsConstant )
  5760. {
  5761. asCString value(&script->code[vnode->tokenPos+2], vnode->tokenLength-2);
  5762. // TODO: Check for overflow
  5763. asQWORD val = asStringScanUInt64(value.AddressOf(), 16, 0);
  5764. // Do we need 64 bits?
  5765. if( val>>32 )
  5766. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  5767. else
  5768. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  5769. }
  5770. else if( vnode->tokenType == ttFloatConstant )
  5771. {
  5772. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5773. // TODO: Check for overflow
  5774. size_t numScanned;
  5775. float v = float(asStringScanDouble(value.AddressOf(), &numScanned));
  5776. ctx->type.SetConstantF(asCDataType::CreatePrimitive(ttFloat, true), v);
  5777. #ifndef AS_USE_DOUBLE_AS_FLOAT
  5778. // Don't check this if we have double as float, because then the whole token would be scanned (i.e. no f suffix)
  5779. asASSERT(numScanned == vnode->tokenLength - 1);
  5780. #endif
  5781. }
  5782. else if( vnode->tokenType == ttDoubleConstant )
  5783. {
  5784. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5785. // TODO: Check for overflow
  5786. size_t numScanned;
  5787. double v = asStringScanDouble(value.AddressOf(), &numScanned);
  5788. ctx->type.SetConstantD(asCDataType::CreatePrimitive(ttDouble, true), v);
  5789. asASSERT(numScanned == vnode->tokenLength);
  5790. }
  5791. else if( vnode->tokenType == ttTrue ||
  5792. vnode->tokenType == ttFalse )
  5793. {
  5794. #if AS_SIZEOF_BOOL == 1
  5795. ctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  5796. #else
  5797. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  5798. #endif
  5799. }
  5800. else if( vnode->tokenType == ttStringConstant ||
  5801. vnode->tokenType == ttMultilineStringConstant ||
  5802. vnode->tokenType == ttHeredocStringConstant )
  5803. {
  5804. asCString str;
  5805. asCScriptNode *snode = vnode->firstChild;
  5806. if( script->code[snode->tokenPos] == '\'' && engine->ep.useCharacterLiterals )
  5807. {
  5808. // Treat the single quoted string as a single character literal
  5809. str.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5810. asDWORD val = 0;
  5811. if( str.GetLength() && (unsigned char)str[0] > 127 && engine->ep.scanner == 1 )
  5812. {
  5813. // This is the start of a UTF8 encoded character. We need to decode it
  5814. val = asStringDecodeUTF8(str.AddressOf(), 0);
  5815. if( val == (asDWORD)-1 )
  5816. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  5817. }
  5818. else
  5819. {
  5820. val = ProcessStringConstant(str, snode);
  5821. if( val == (asDWORD)-1 )
  5822. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  5823. }
  5824. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), val);
  5825. }
  5826. else
  5827. {
  5828. // Process the string constants
  5829. while( snode )
  5830. {
  5831. asCString cat;
  5832. if( snode->tokenType == ttStringConstant )
  5833. {
  5834. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5835. ProcessStringConstant(cat, snode);
  5836. }
  5837. else if( snode->tokenType == ttMultilineStringConstant )
  5838. {
  5839. if( !engine->ep.allowMultilineStrings )
  5840. Error(TXT_MULTILINE_STRINGS_NOT_ALLOWED, snode);
  5841. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5842. ProcessStringConstant(cat, snode);
  5843. }
  5844. else if( snode->tokenType == ttHeredocStringConstant )
  5845. {
  5846. cat.Assign(&script->code[snode->tokenPos+3], snode->tokenLength-6);
  5847. ProcessHeredocStringConstant(cat, snode);
  5848. }
  5849. str += cat;
  5850. snode = snode->next;
  5851. }
  5852. // Call the string factory function to create a string object
  5853. asCScriptFunction *descr = engine->stringFactory;
  5854. if( descr == 0 )
  5855. {
  5856. // Error
  5857. Error(TXT_STRINGS_NOT_RECOGNIZED, vnode);
  5858. // Give dummy value
  5859. ctx->type.SetDummy();
  5860. return -1;
  5861. }
  5862. else
  5863. {
  5864. // Register the constant string with the engine
  5865. int id = engine->AddConstantString(str.AddressOf(), str.GetLength());
  5866. ctx->bc.InstrWORD(asBC_STR, (asWORD)id);
  5867. bool useVariable = false;
  5868. int stackOffset = 0;
  5869. if( descr->DoesReturnOnStack() )
  5870. {
  5871. useVariable = true;
  5872. stackOffset = AllocateVariable(descr->returnType, true);
  5873. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  5874. }
  5875. PerformFunctionCall(descr->id, ctx, false, 0, 0, useVariable, stackOffset);
  5876. }
  5877. }
  5878. }
  5879. else if( vnode->tokenType == ttNull )
  5880. {
  5881. ctx->bc.Instr(asBC_PshNull);
  5882. ctx->type.SetNullConstant();
  5883. }
  5884. else
  5885. asASSERT(false);
  5886. }
  5887. else if( vnode->nodeType == snFunctionCall )
  5888. {
  5889. // Determine the scope resolution
  5890. asCString scope = builder->GetScopeFromNode(vnode->firstChild, script);
  5891. return CompileFunctionCall(vnode, ctx, 0, false, scope);
  5892. }
  5893. else if( vnode->nodeType == snConstructCall )
  5894. {
  5895. CompileConstructCall(vnode, ctx);
  5896. }
  5897. else if( vnode->nodeType == snAssignment )
  5898. {
  5899. asSExprContext e(engine);
  5900. int r = CompileAssignment(vnode, &e);
  5901. if( r < 0 )
  5902. {
  5903. ctx->type.SetDummy();
  5904. return r;
  5905. }
  5906. MergeExprBytecodeAndType(ctx, &e);
  5907. }
  5908. else if( vnode->nodeType == snCast )
  5909. {
  5910. // Implement the cast operator
  5911. CompileConversion(vnode, ctx);
  5912. }
  5913. else
  5914. asASSERT(false);
  5915. return 0;
  5916. }
  5917. asUINT asCCompiler::ProcessStringConstant(asCString &cstr, asCScriptNode *node, bool processEscapeSequences)
  5918. {
  5919. int charLiteral = -1;
  5920. // Process escape sequences
  5921. asCArray<char> str((int)cstr.GetLength());
  5922. for( asUINT n = 0; n < cstr.GetLength(); n++ )
  5923. {
  5924. #ifdef AS_DOUBLEBYTE_CHARSET
  5925. // Double-byte charset is only allowed for ASCII and not UTF16 encoded strings
  5926. if( (cstr[n] & 0x80) && engine->ep.scanner == 0 && engine->ep.stringEncoding != 1 )
  5927. {
  5928. // This is the lead character of a double byte character
  5929. // include the trail character without checking it's value.
  5930. str.PushLast(cstr[n]);
  5931. n++;
  5932. str.PushLast(cstr[n]);
  5933. continue;
  5934. }
  5935. #endif
  5936. asUINT val;
  5937. if( processEscapeSequences && cstr[n] == '\\' )
  5938. {
  5939. ++n;
  5940. if( n == cstr.GetLength() )
  5941. {
  5942. if( charLiteral == -1 ) charLiteral = 0;
  5943. return charLiteral;
  5944. }
  5945. // Hexadecimal escape sequences will allow the construction of
  5946. // invalid unicode sequences, but the string should also work as
  5947. // a bytearray so we must support this. The code for working with
  5948. // unicode text must be prepared to handle invalid unicode sequences
  5949. if( cstr[n] == 'x' || cstr[n] == 'X' )
  5950. {
  5951. ++n;
  5952. if( n == cstr.GetLength() ) break;
  5953. val = 0;
  5954. int c = engine->ep.stringEncoding == 1 ? 4 : 2;
  5955. for( ; c > 0 && n < cstr.GetLength(); c--, n++ )
  5956. {
  5957. if( cstr[n] >= '0' && cstr[n] <= '9' )
  5958. val = val*16 + cstr[n] - '0';
  5959. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  5960. val = val*16 + cstr[n] - 'a' + 10;
  5961. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  5962. val = val*16 + cstr[n] - 'A' + 10;
  5963. else
  5964. break;
  5965. }
  5966. // Rewind one, since the loop will increment it again
  5967. n--;
  5968. // Hexadecimal escape sequences produce exact value, even if it is not proper unicode chars
  5969. if( engine->ep.stringEncoding == 0 )
  5970. {
  5971. str.PushLast((asBYTE)val);
  5972. }
  5973. else
  5974. {
  5975. #ifndef AS_BIG_ENDIAN
  5976. str.PushLast((asBYTE)val);
  5977. str.PushLast((asBYTE)(val>>8));
  5978. #else
  5979. str.PushLast((asBYTE)(val>>8));
  5980. str.PushLast((asBYTE)val);
  5981. #endif
  5982. }
  5983. if( charLiteral == -1 ) charLiteral = val;
  5984. continue;
  5985. }
  5986. else if( cstr[n] == 'u' || cstr[n] == 'U' )
  5987. {
  5988. // \u expects 4 hex digits
  5989. // \U expects 8 hex digits
  5990. bool expect2 = cstr[n] == 'u';
  5991. int c = expect2 ? 4 : 8;
  5992. val = 0;
  5993. for( ; c > 0; c-- )
  5994. {
  5995. ++n;
  5996. if( n == cstr.GetLength() ) break;
  5997. if( cstr[n] >= '0' && cstr[n] <= '9' )
  5998. val = val*16 + cstr[n] - '0';
  5999. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  6000. val = val*16 + cstr[n] - 'a' + 10;
  6001. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  6002. val = val*16 + cstr[n] - 'A' + 10;
  6003. else
  6004. break;
  6005. }
  6006. if( c != 0 )
  6007. {
  6008. // Give warning about invalid code point
  6009. // TODO: Need code position for warning
  6010. asCString msg;
  6011. msg.Format(TXT_INVALID_UNICODE_FORMAT_EXPECTED_d, expect2 ? 4 : 8);
  6012. Warning(msg.AddressOf(), node);
  6013. continue;
  6014. }
  6015. }
  6016. else
  6017. {
  6018. if( cstr[n] == '"' )
  6019. val = '"';
  6020. else if( cstr[n] == '\'' )
  6021. val = '\'';
  6022. else if( cstr[n] == 'n' )
  6023. val = '\n';
  6024. else if( cstr[n] == 'r' )
  6025. val = '\r';
  6026. else if( cstr[n] == 't' )
  6027. val = '\t';
  6028. else if( cstr[n] == '0' )
  6029. val = '\0';
  6030. else if( cstr[n] == '\\' )
  6031. val = '\\';
  6032. else
  6033. {
  6034. // Invalid escape sequence
  6035. Warning(TXT_INVALID_ESCAPE_SEQUENCE, node);
  6036. continue;
  6037. }
  6038. }
  6039. }
  6040. else
  6041. {
  6042. if( engine->ep.scanner == 1 && (cstr[n] & 0x80) )
  6043. {
  6044. unsigned int len;
  6045. val = asStringDecodeUTF8(&cstr[n], &len);
  6046. if( val == 0xFFFFFFFF )
  6047. {
  6048. // Incorrect UTF8 encoding. Use only the first byte
  6049. // TODO: Need code position for warning
  6050. Warning(TXT_INVALID_UNICODE_SEQUENCE_IN_SRC, node);
  6051. val = (unsigned char)cstr[n];
  6052. }
  6053. else
  6054. n += len-1;
  6055. }
  6056. else
  6057. val = (unsigned char)cstr[n];
  6058. }
  6059. // Add the character to the final string
  6060. char encodedValue[5];
  6061. int len;
  6062. if( engine->ep.scanner == 1 && engine->ep.stringEncoding == 0 )
  6063. {
  6064. // Convert to UTF8 encoded
  6065. len = asStringEncodeUTF8(val, encodedValue);
  6066. }
  6067. else if( engine->ep.stringEncoding == 1 )
  6068. {
  6069. // Convert to 16bit wide character string (even if the script is scanned as ASCII)
  6070. len = asStringEncodeUTF16(val, encodedValue);
  6071. }
  6072. else
  6073. {
  6074. // Do not convert ASCII characters
  6075. encodedValue[0] = (asBYTE)val;
  6076. len = 1;
  6077. }
  6078. if( len < 0 )
  6079. {
  6080. // Give warning about invalid code point
  6081. // TODO: Need code position for warning
  6082. Warning(TXT_INVALID_UNICODE_VALUE, node);
  6083. }
  6084. else
  6085. {
  6086. // Add the encoded value to the final string
  6087. str.Concatenate(encodedValue, len);
  6088. if( charLiteral == -1 ) charLiteral = val;
  6089. }
  6090. }
  6091. cstr.Assign(str.AddressOf(), str.GetLength());
  6092. return charLiteral;
  6093. }
  6094. void asCCompiler::ProcessHeredocStringConstant(asCString &str, asCScriptNode *node)
  6095. {
  6096. // Remove first line if it only contains whitespace
  6097. int start;
  6098. for( start = 0; start < (int)str.GetLength(); start++ )
  6099. {
  6100. if( str[start] == '\n' )
  6101. {
  6102. // Remove the linebreak as well
  6103. start++;
  6104. break;
  6105. }
  6106. if( str[start] != ' ' &&
  6107. str[start] != '\t' &&
  6108. str[start] != '\r' )
  6109. {
  6110. // Don't remove anything
  6111. start = 0;
  6112. break;
  6113. }
  6114. }
  6115. // Remove last line break and the line after that if it only contains whitespaces
  6116. int end;
  6117. for( end = (int)str.GetLength() - 1; end >= 0; end-- )
  6118. {
  6119. if( str[end] == '\n' )
  6120. break;
  6121. if( str[end] != ' ' &&
  6122. str[end] != '\t' &&
  6123. str[end] != '\r' )
  6124. {
  6125. // Don't remove anything
  6126. end = (int)str.GetLength();
  6127. break;
  6128. }
  6129. }
  6130. if( end < 0 ) end = 0;
  6131. asCString tmp;
  6132. if( end > start )
  6133. tmp.Assign(&str[start], end-start);
  6134. ProcessStringConstant(tmp, node, false);
  6135. str = tmp;
  6136. }
  6137. void asCCompiler::CompileConversion(asCScriptNode *node, asSExprContext *ctx)
  6138. {
  6139. asSExprContext expr(engine);
  6140. asCDataType to;
  6141. bool anyErrors = false;
  6142. EImplicitConv convType;
  6143. if( node->nodeType == snConstructCall )
  6144. {
  6145. convType = asIC_EXPLICIT_VAL_CAST;
  6146. // Verify that there is only one argument
  6147. if( node->lastChild->firstChild == 0 ||
  6148. node->lastChild->firstChild != node->lastChild->lastChild )
  6149. {
  6150. Error(TXT_ONLY_ONE_ARGUMENT_IN_CAST, node->lastChild);
  6151. expr.type.SetDummy();
  6152. anyErrors = true;
  6153. }
  6154. else
  6155. {
  6156. // Compile the expression
  6157. int r = CompileAssignment(node->lastChild->firstChild, &expr);
  6158. if( r < 0 )
  6159. anyErrors = true;
  6160. }
  6161. // Determine the requested type
  6162. // TODO: namespace: Use correct implicit namespace from function
  6163. to = builder->CreateDataTypeFromNode(node->firstChild, script, "");
  6164. to.MakeReadOnly(true); // Default to const
  6165. asASSERT(to.IsPrimitive());
  6166. }
  6167. else
  6168. {
  6169. convType = asIC_EXPLICIT_REF_CAST;
  6170. // Compile the expression
  6171. int r = CompileAssignment(node->lastChild, &expr);
  6172. if( r < 0 )
  6173. anyErrors = true;
  6174. // Determine the requested type
  6175. // TODO: namespace: Use correct implicit namespace from function
  6176. to = builder->CreateDataTypeFromNode(node->firstChild, script, "");
  6177. to = builder->ModifyDataTypeFromNode(to, node->firstChild->next, script, 0, 0);
  6178. // If the type support object handles, then use it
  6179. if( to.SupportHandles() )
  6180. {
  6181. to.MakeHandle(true);
  6182. }
  6183. else if( !to.IsObjectHandle() )
  6184. {
  6185. // The cast<type> operator can only be used for reference casts
  6186. Error(TXT_ILLEGAL_TARGET_TYPE_FOR_REF_CAST, node->firstChild);
  6187. anyErrors = true;
  6188. }
  6189. }
  6190. // Do not allow casting to non shared type if we're compiling a shared method
  6191. if( outFunc->IsShared() &&
  6192. to.GetObjectType() && !to.GetObjectType()->IsShared() )
  6193. {
  6194. asCString msg;
  6195. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, to.GetObjectType()->name.AddressOf());
  6196. Error(msg.AddressOf(), node);
  6197. anyErrors = true;
  6198. }
  6199. if( anyErrors )
  6200. {
  6201. // Assume that the error can be fixed and allow the compilation to continue
  6202. ctx->type.SetConstantDW(to, 0);
  6203. return;
  6204. }
  6205. ProcessPropertyGetAccessor(&expr, node);
  6206. // We don't want a reference
  6207. if( expr.type.dataType.IsReference() )
  6208. {
  6209. if( expr.type.dataType.IsObject() )
  6210. Dereference(&expr, true);
  6211. else
  6212. ConvertToVariable(&expr);
  6213. }
  6214. ImplicitConversion(&expr, to, node, convType);
  6215. IsVariableInitialized(&expr.type, node);
  6216. // If no type conversion is really tried ignore it
  6217. if( to == expr.type.dataType )
  6218. {
  6219. // This will keep information about constant type
  6220. MergeExprBytecode(ctx, &expr);
  6221. ctx->type = expr.type;
  6222. return;
  6223. }
  6224. if( to.IsEqualExceptConst(expr.type.dataType) && to.IsPrimitive() )
  6225. {
  6226. MergeExprBytecode(ctx, &expr);
  6227. ctx->type = expr.type;
  6228. ctx->type.dataType.MakeReadOnly(true);
  6229. return;
  6230. }
  6231. // The implicit conversion already does most of the conversions permitted,
  6232. // here we'll only treat those conversions that require an explicit cast.
  6233. bool conversionOK = false;
  6234. if( !expr.type.isConstant )
  6235. {
  6236. if( !expr.type.dataType.IsObject() )
  6237. ConvertToTempVariable(&expr);
  6238. if( to.IsObjectHandle() &&
  6239. expr.type.dataType.IsObjectHandle() &&
  6240. !(!to.IsHandleToConst() && expr.type.dataType.IsHandleToConst()) )
  6241. {
  6242. conversionOK = CompileRefCast(&expr, to, true, node);
  6243. MergeExprBytecode(ctx, &expr);
  6244. ctx->type = expr.type;
  6245. }
  6246. }
  6247. if( conversionOK )
  6248. return;
  6249. // Conversion not available
  6250. ctx->type.SetDummy();
  6251. asCString strTo, strFrom;
  6252. strTo = to.Format();
  6253. strFrom = expr.type.dataType.Format();
  6254. asCString msg;
  6255. msg.Format(TXT_NO_CONVERSION_s_TO_s, strFrom.AddressOf(), strTo.AddressOf());
  6256. Error(msg.AddressOf(), node);
  6257. }
  6258. void asCCompiler::AfterFunctionCall(int funcID, asCArray<asSExprContext*> &args, asSExprContext *ctx, bool deferAll)
  6259. {
  6260. asCScriptFunction *descr = builder->GetFunctionDescription(funcID);
  6261. // Parameters that are sent by reference should be assigned
  6262. // to the evaluated expression if it is an lvalue
  6263. // Evaluate the arguments from last to first
  6264. int n = (int)descr->parameterTypes.GetLength() - 1;
  6265. for( ; n >= 0; n-- )
  6266. {
  6267. if( (descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] & asTM_OUTREF)) ||
  6268. (descr->parameterTypes[n].IsObject() && deferAll) )
  6269. {
  6270. asASSERT( !(descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] == asTM_OUTREF)) || args[n]->origExpr );
  6271. // For &inout, only store the argument if it is for a temporary variable
  6272. if( engine->ep.allowUnsafeReferences ||
  6273. descr->inOutFlags[n] != asTM_INOUTREF || args[n]->type.isTemporary )
  6274. {
  6275. // Store the argument for later processing
  6276. asSDeferredParam outParam;
  6277. outParam.argNode = args[n]->exprNode;
  6278. outParam.argType = args[n]->type;
  6279. outParam.argInOutFlags = descr->inOutFlags[n];
  6280. outParam.origExpr = args[n]->origExpr;
  6281. ctx->deferredParams.PushLast(outParam);
  6282. }
  6283. }
  6284. else
  6285. {
  6286. // Release the temporary variable now
  6287. ReleaseTemporaryVariable(args[n]->type, &ctx->bc);
  6288. }
  6289. // Move the argument's deferred expressions over to the final expression
  6290. for( asUINT m = 0; m < args[n]->deferredParams.GetLength(); m++ )
  6291. {
  6292. ctx->deferredParams.PushLast(args[n]->deferredParams[m]);
  6293. args[n]->deferredParams[m].origExpr = 0;
  6294. }
  6295. args[n]->deferredParams.SetLength(0);
  6296. }
  6297. }
  6298. void asCCompiler::ProcessDeferredParams(asSExprContext *ctx)
  6299. {
  6300. if( isProcessingDeferredParams ) return;
  6301. isProcessingDeferredParams = true;
  6302. for( asUINT n = 0; n < ctx->deferredParams.GetLength(); n++ )
  6303. {
  6304. asSDeferredParam outParam = ctx->deferredParams[n];
  6305. if( outParam.argInOutFlags < asTM_OUTREF ) // &in, or not reference
  6306. {
  6307. // Just release the variable
  6308. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6309. }
  6310. else if( outParam.argInOutFlags == asTM_OUTREF )
  6311. {
  6312. asSExprContext *expr = outParam.origExpr;
  6313. outParam.origExpr = 0;
  6314. if( outParam.argType.dataType.IsObjectHandle() )
  6315. {
  6316. // Implicitly convert the value to a handle
  6317. if( expr->type.dataType.IsObjectHandle() )
  6318. expr->type.isExplicitHandle = true;
  6319. }
  6320. // Verify that the expression result in a lvalue, or a property accessor
  6321. if( IsLValue(expr->type) || expr->property_get || expr->property_set )
  6322. {
  6323. asSExprContext rctx(engine);
  6324. rctx.type = outParam.argType;
  6325. if( rctx.type.dataType.IsPrimitive() )
  6326. rctx.type.dataType.MakeReference(false);
  6327. else
  6328. {
  6329. rctx.bc.InstrSHORT(asBC_PSF, outParam.argType.stackOffset);
  6330. rctx.type.dataType.MakeReference(IsVariableOnHeap(outParam.argType.stackOffset));
  6331. if( expr->type.isExplicitHandle )
  6332. rctx.type.isExplicitHandle = true;
  6333. }
  6334. asSExprContext o(engine);
  6335. DoAssignment(&o, expr, &rctx, outParam.argNode, outParam.argNode, ttAssignment, outParam.argNode);
  6336. if( !o.type.dataType.IsPrimitive() ) o.bc.Instr(asBC_PopPtr);
  6337. MergeExprBytecode(ctx, &o);
  6338. }
  6339. else
  6340. {
  6341. // We must still evaluate the expression
  6342. MergeExprBytecode(ctx, expr);
  6343. if( !expr->type.isConstant || expr->type.IsNullConstant() )
  6344. ctx->bc.Instr(asBC_PopPtr);
  6345. // Give a warning, except if the argument is null or 0 which indicate the argument is really to be ignored
  6346. if( !expr->type.IsNullConstant() && !(expr->type.isConstant && expr->type.qwordValue == 0) )
  6347. Warning(TXT_ARG_NOT_LVALUE, outParam.argNode);
  6348. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6349. }
  6350. ReleaseTemporaryVariable(expr->type, &ctx->bc);
  6351. // Delete the original expression context
  6352. asDELETE(expr,asSExprContext);
  6353. }
  6354. else // &inout
  6355. {
  6356. if( outParam.argType.isTemporary )
  6357. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6358. else if( !outParam.argType.isVariable )
  6359. {
  6360. if( outParam.argType.dataType.IsObject() &&
  6361. ((outParam.argType.dataType.GetBehaviour()->addref &&
  6362. outParam.argType.dataType.GetBehaviour()->release) ||
  6363. (outParam.argType.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) )
  6364. {
  6365. // Release the object handle that was taken to guarantee the reference
  6366. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6367. }
  6368. }
  6369. }
  6370. }
  6371. ctx->deferredParams.SetLength(0);
  6372. isProcessingDeferredParams = false;
  6373. }
  6374. void asCCompiler::CompileConstructCall(asCScriptNode *node, asSExprContext *ctx)
  6375. {
  6376. // The first node is a datatype node
  6377. asCString name;
  6378. asCTypeInfo tempObj;
  6379. bool onHeap = true;
  6380. asCArray<int> funcs;
  6381. // It is possible that the name is really a constructor
  6382. asCDataType dt;
  6383. // TODO: namespace: Use correct implicit namespace from function
  6384. dt = builder->CreateDataTypeFromNode(node->firstChild, script, "");
  6385. if( dt.IsPrimitive() )
  6386. {
  6387. // This is a cast to a primitive type
  6388. CompileConversion(node, ctx);
  6389. return;
  6390. }
  6391. // Do not allow constructing non-shared types in shared functions
  6392. if( outFunc->IsShared() &&
  6393. dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  6394. {
  6395. asCString msg;
  6396. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  6397. Error(msg.AddressOf(), node);
  6398. }
  6399. // Compile the arguments
  6400. asCArray<asSExprContext *> args;
  6401. asCArray<asCTypeInfo> temporaryVariables;
  6402. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6403. {
  6404. // Check for a value cast behaviour
  6405. if( args.GetLength() == 1 && args[0]->type.dataType.GetObjectType() )
  6406. {
  6407. asSExprContext conv(engine);
  6408. conv.type = args[0]->type;
  6409. ImplicitConversion(&conv, dt, node->lastChild, asIC_EXPLICIT_VAL_CAST, false);
  6410. if( conv.type.dataType.IsEqualExceptRef(dt) )
  6411. {
  6412. ImplicitConversion(args[0], dt, node->lastChild, asIC_EXPLICIT_VAL_CAST);
  6413. ctx->bc.AddCode(&args[0]->bc);
  6414. ctx->type = args[0]->type;
  6415. asDELETE(args[0],asSExprContext);
  6416. return;
  6417. }
  6418. }
  6419. // Check for possible constructor/factory
  6420. name = dt.Format();
  6421. asSTypeBehaviour *beh = dt.GetBehaviour();
  6422. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6423. {
  6424. funcs = beh->constructors;
  6425. // Value types and script types are allocated through the constructor
  6426. tempObj.dataType = dt;
  6427. tempObj.stackOffset = (short)AllocateVariable(dt, true);
  6428. tempObj.dataType.MakeReference(true);
  6429. tempObj.isTemporary = true;
  6430. tempObj.isVariable = true;
  6431. onHeap = IsVariableOnHeap(tempObj.stackOffset);
  6432. // Push the address of the object on the stack
  6433. if( onHeap )
  6434. ctx->bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  6435. }
  6436. else
  6437. {
  6438. funcs = beh->factories;
  6439. }
  6440. // Special case: Allow calling func(void) with a void expression.
  6441. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6442. {
  6443. // Evaluate the expression before the function call
  6444. MergeExprBytecode(ctx, args[0]);
  6445. asDELETE(args[0],asSExprContext);
  6446. args.SetLength(0);
  6447. }
  6448. // Special case: If this is an object constructor and there are no arguments use the default constructor.
  6449. // If none has been registered, just allocate the variable and push it on the stack.
  6450. if( args.GetLength() == 0 )
  6451. {
  6452. asSTypeBehaviour *beh = tempObj.dataType.GetBehaviour();
  6453. if( beh && beh->construct == 0 && !(dt.GetObjectType()->flags & asOBJ_REF) )
  6454. {
  6455. // Call the default constructor
  6456. ctx->type = tempObj;
  6457. if( onHeap )
  6458. {
  6459. asASSERT(ctx->bc.GetLastInstr() == asBC_VAR);
  6460. ctx->bc.RemoveLastInstr();
  6461. }
  6462. CallDefaultConstructor(tempObj.dataType, tempObj.stackOffset, IsVariableOnHeap(tempObj.stackOffset), &ctx->bc, node);
  6463. // Push the reference on the stack
  6464. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6465. return;
  6466. }
  6467. }
  6468. MatchFunctions(funcs, args, node, name.AddressOf(), NULL, false);
  6469. if( funcs.GetLength() != 1 )
  6470. {
  6471. // The error was reported by MatchFunctions()
  6472. // Dummy value
  6473. ctx->type.SetDummy();
  6474. }
  6475. else
  6476. {
  6477. int r = asSUCCESS;
  6478. // Add the default values for arguments not explicitly supplied
  6479. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  6480. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  6481. r = CompileDefaultArgs(node, args, func);
  6482. if( r == asSUCCESS )
  6483. {
  6484. asCByteCode objBC(engine);
  6485. PrepareFunctionCall(funcs[0], &ctx->bc, args);
  6486. MoveArgsToStack(funcs[0], &ctx->bc, args, false);
  6487. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6488. {
  6489. // If the object is allocated on the stack, then call the constructor as a normal function
  6490. if( onHeap )
  6491. {
  6492. int offset = 0;
  6493. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  6494. for( asUINT n = 0; n < args.GetLength(); n++ )
  6495. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  6496. ctx->bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  6497. }
  6498. else
  6499. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6500. PerformFunctionCall(funcs[0], ctx, onHeap, &args, tempObj.dataType.GetObjectType());
  6501. // Add tag that the object has been initialized
  6502. ctx->bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  6503. // The constructor doesn't return anything,
  6504. // so we have to manually inform the type of
  6505. // the return value
  6506. ctx->type = tempObj;
  6507. if( !onHeap )
  6508. ctx->type.dataType.MakeReference(false);
  6509. // Push the address of the object on the stack again
  6510. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6511. }
  6512. else
  6513. {
  6514. // Call the factory to create the reference type
  6515. PerformFunctionCall(funcs[0], ctx, false, &args);
  6516. }
  6517. }
  6518. }
  6519. }
  6520. else
  6521. {
  6522. // Failed to compile the argument list, set the result to the dummy type
  6523. ctx->type.SetDummy();
  6524. }
  6525. // Cleanup
  6526. for( asUINT n = 0; n < args.GetLength(); n++ )
  6527. if( args[n] )
  6528. {
  6529. asDELETE(args[n],asSExprContext);
  6530. }
  6531. }
  6532. int asCCompiler::CompileFunctionCall(asCScriptNode *node, asSExprContext *ctx, asCObjectType *objectType, bool objIsConst, const asCString &scope)
  6533. {
  6534. asCString name;
  6535. asCTypeInfo tempObj;
  6536. asCArray<int> funcs;
  6537. int r = -1;
  6538. asCScriptNode *nm = node->lastChild->prev;
  6539. name.Assign(&script->code[nm->tokenPos], nm->tokenLength);
  6540. // If we're compiling a class method, then the call may be to a class method
  6541. // even though it looks like an ordinary call to a global function. If it is
  6542. // to a class method it is necessary to implicitly add the this pointer.
  6543. if( objectType == 0 && outFunc && outFunc->objectType && scope != "::" )
  6544. {
  6545. // The special keyword 'super' may be used in constructors to invoke the base
  6546. // class' constructor. This can only be used without any scoping operator
  6547. if( m_isConstructor && name == SUPER_TOKEN && scope == "" )
  6548. {
  6549. // We are calling the base class' constructor, so set the objectType
  6550. objectType = outFunc->objectType;
  6551. }
  6552. else
  6553. {
  6554. // Are there any class methods that may match?
  6555. // TODO: namespace: Should really make sure the scope also match. Because the scope
  6556. // may match a base class, or it may match a global namespace. If it is
  6557. // matching a global scope then we're not calling a class method even
  6558. // if there is a method with the same name.
  6559. asCArray<int> funcs;
  6560. builder->GetObjectMethodDescriptions(name.AddressOf(), outFunc->objectType, funcs, false);
  6561. if( funcs.GetLength() )
  6562. {
  6563. // We're calling a class method, so set the objectType
  6564. objectType = outFunc->objectType;
  6565. }
  6566. }
  6567. // If a class method is being called then implicitly add the this pointer for the call
  6568. if( objectType )
  6569. {
  6570. asCDataType dt = asCDataType::CreateObject(objectType, false);
  6571. // The object pointer is located at stack position 0
  6572. ctx->bc.InstrSHORT(asBC_PSF, 0);
  6573. ctx->type.SetVariable(dt, 0, false);
  6574. ctx->type.dataType.MakeReference(true);
  6575. Dereference(ctx, true);
  6576. }
  6577. }
  6578. // First check for a local variable of a function type
  6579. // Must not allow function names, nor global variables to be returned in this instance
  6580. asSExprContext funcPtr(engine);
  6581. if( objectType == 0 )
  6582. r = CompileVariableAccess(name, scope, &funcPtr, node, true, true);
  6583. if( r < 0 )
  6584. {
  6585. if( objectType )
  6586. {
  6587. // If we're compiling a constructor and the name of the function is super then
  6588. // the constructor of the base class is being called.
  6589. // super cannot be prefixed with a scope operator
  6590. if( scope == "" && m_isConstructor && name == SUPER_TOKEN )
  6591. {
  6592. // If the class is not derived from anyone else, calling super should give an error
  6593. if( objectType->derivedFrom )
  6594. funcs = objectType->derivedFrom->beh.constructors;
  6595. // Must not allow calling base class' constructor multiple times
  6596. if( continueLabels.GetLength() > 0 )
  6597. {
  6598. // If a continue label is set we are in a loop
  6599. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_LOOPS, node);
  6600. }
  6601. else if( breakLabels.GetLength() > 0 )
  6602. {
  6603. // TODO: inheritance: Should eventually allow constructors in switch statements
  6604. // If a break label is set we are either in a loop or a switch statements
  6605. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_SWITCH, node);
  6606. }
  6607. else if( m_isConstructorCalled )
  6608. {
  6609. Error(TXT_CANNOT_CALL_CONSTRUCTOR_TWICE, node);
  6610. }
  6611. m_isConstructorCalled = true;
  6612. }
  6613. else
  6614. {
  6615. // The scope is can be used to specify the base class
  6616. builder->GetObjectMethodDescriptions(name.AddressOf(), objectType, funcs, objIsConst, scope);
  6617. }
  6618. // It is still possible that there is a class member of a function type
  6619. if( funcs.GetLength() == 0 )
  6620. CompileVariableAccess(name, scope, &funcPtr, node, true, true, objectType);
  6621. }
  6622. else
  6623. {
  6624. // The scope is used to define the namespace
  6625. asCString ns = scope == "::" ? "" : scope;
  6626. if( ns == "" )
  6627. {
  6628. if( outFunc->nameSpace != "" )
  6629. ns = outFunc->nameSpace;
  6630. else if( outFunc->objectType && outFunc->objectType->nameSpace != "" )
  6631. ns = outFunc->objectType->nameSpace;
  6632. }
  6633. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  6634. // TODO: funcdef: It is still possible that there is a global variable of a function type
  6635. }
  6636. }
  6637. else if( !funcPtr.type.dataType.GetFuncDef() )
  6638. {
  6639. // The variable is not a function
  6640. asCString msg;
  6641. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  6642. Error(msg.AddressOf(), node);
  6643. return -1;
  6644. }
  6645. if( funcs.GetLength() == 0 && funcPtr.type.dataType.GetFuncDef() )
  6646. {
  6647. funcs.PushLast(funcPtr.type.dataType.GetFuncDef()->id);
  6648. }
  6649. // Compile the arguments
  6650. asCArray<asSExprContext *> args;
  6651. asCArray<asCTypeInfo> temporaryVariables;
  6652. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6653. {
  6654. // Special case: Allow calling func(void) with a void expression.
  6655. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6656. {
  6657. // Evaluate the expression before the function call
  6658. MergeExprBytecode(ctx, args[0]);
  6659. asDELETE(args[0],asSExprContext);
  6660. args.SetLength(0);
  6661. }
  6662. MatchFunctions(funcs, args, node, name.AddressOf(), objectType, objIsConst, false, true, scope);
  6663. if( funcs.GetLength() != 1 )
  6664. {
  6665. // The error was reported by MatchFunctions()
  6666. // Dummy value
  6667. ctx->type.SetDummy();
  6668. }
  6669. else
  6670. {
  6671. int r = asSUCCESS;
  6672. // Add the default values for arguments not explicitly supplied
  6673. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  6674. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  6675. r = CompileDefaultArgs(node, args, func);
  6676. // TODO: funcdef: Do we have to make sure the handle is stored in a temporary variable, or
  6677. // is it enough to make sure it is in a local variable?
  6678. // For function pointer we must guarantee that the function is safe, i.e.
  6679. // by first storing the function pointer in a local variable (if it isn't already in one)
  6680. if( r == asSUCCESS )
  6681. {
  6682. if( (funcs[0] & 0xFFFF0000) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  6683. {
  6684. if( objectType )
  6685. {
  6686. Dereference(ctx, true); // Dereference the object pointer to access the member
  6687. // The actual function should be called as if a global function
  6688. objectType = 0;
  6689. }
  6690. Dereference(&funcPtr, true);
  6691. ConvertToVariable(&funcPtr);
  6692. ctx->bc.AddCode(&funcPtr.bc);
  6693. if( !funcPtr.type.isTemporary )
  6694. ctx->bc.Instr(asBC_PopPtr);
  6695. }
  6696. MakeFunctionCall(ctx, funcs[0], objectType, args, node, false, 0, funcPtr.type.stackOffset);
  6697. // If the function pointer was copied to a local variable for the call, then
  6698. // release it again (temporary local variable)
  6699. if( (funcs[0] & 0xFFFF0000) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  6700. {
  6701. ReleaseTemporaryVariable(funcPtr.type, &ctx->bc);
  6702. }
  6703. }
  6704. }
  6705. }
  6706. else
  6707. {
  6708. // Failed to compile the argument list, set the dummy type and continue compilation
  6709. ctx->type.SetDummy();
  6710. }
  6711. // Cleanup
  6712. for( asUINT n = 0; n < args.GetLength(); n++ )
  6713. if( args[n] )
  6714. {
  6715. asDELETE(args[n],asSExprContext);
  6716. }
  6717. return 0;
  6718. }
  6719. int asCCompiler::CompileExpressionPreOp(asCScriptNode *node, asSExprContext *ctx)
  6720. {
  6721. int op = node->tokenType;
  6722. IsVariableInitialized(&ctx->type, node);
  6723. if( op == ttHandle )
  6724. {
  6725. // Verify that the type allow its handle to be taken
  6726. if( ctx->type.isExplicitHandle ||
  6727. !ctx->type.dataType.IsObject() ||
  6728. !(((ctx->type.dataType.GetObjectType()->beh.addref && ctx->type.dataType.GetObjectType()->beh.release) || (ctx->type.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) ||
  6729. (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  6730. {
  6731. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  6732. return -1;
  6733. }
  6734. // Objects that are not local variables are not references
  6735. // Objects allocated on the stack are also not marked as references
  6736. if( !ctx->type.dataType.IsReference() &&
  6737. !(ctx->type.dataType.IsObject() && !ctx->type.isVariable) &&
  6738. !(ctx->type.isVariable && !IsVariableOnHeap(ctx->type.stackOffset)) )
  6739. {
  6740. Error(TXT_NOT_VALID_REFERENCE, node);
  6741. return -1;
  6742. }
  6743. // If this is really an object then the handle created is a const handle
  6744. bool makeConst = !ctx->type.dataType.IsObjectHandle() && !(ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE);
  6745. // Mark the type as an object handle
  6746. ctx->type.dataType.MakeHandle(true);
  6747. ctx->type.isExplicitHandle = true;
  6748. if( makeConst )
  6749. ctx->type.dataType.MakeReadOnly(true);
  6750. }
  6751. else if( (op == ttMinus || op == ttBitNot || op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  6752. {
  6753. // Look for the appropriate method
  6754. const char *opName = 0;
  6755. switch( op )
  6756. {
  6757. case ttMinus: opName = "opNeg"; break;
  6758. case ttBitNot: opName = "opCom"; break;
  6759. case ttInc: opName = "opPreInc"; break;
  6760. case ttDec: opName = "opPreDec"; break;
  6761. }
  6762. if( opName )
  6763. {
  6764. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  6765. ProcessPropertyGetAccessor(ctx, node);
  6766. // Is it a const value?
  6767. bool isConst = false;
  6768. if( ctx->type.dataType.IsObjectHandle() )
  6769. isConst = ctx->type.dataType.IsHandleToConst();
  6770. else
  6771. isConst = ctx->type.dataType.IsReadOnly();
  6772. // 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
  6773. // Find the correct method
  6774. asCArray<int> funcs;
  6775. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  6776. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  6777. {
  6778. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  6779. if( func->name == opName &&
  6780. func->parameterTypes.GetLength() == 0 &&
  6781. (!isConst || func->isReadOnly) )
  6782. {
  6783. funcs.PushLast(func->id);
  6784. }
  6785. }
  6786. // Did we find the method?
  6787. if( funcs.GetLength() == 1 )
  6788. {
  6789. asCTypeInfo objType = ctx->type;
  6790. asCArray<asSExprContext *> args;
  6791. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  6792. ReleaseTemporaryVariable(objType, &ctx->bc);
  6793. return 0;
  6794. }
  6795. else if( funcs.GetLength() == 0 )
  6796. {
  6797. asCString str;
  6798. str = asCString(opName) + "()";
  6799. if( isConst )
  6800. str += " const";
  6801. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  6802. Error(str.AddressOf(), node);
  6803. ctx->type.SetDummy();
  6804. return -1;
  6805. }
  6806. else if( funcs.GetLength() > 1 )
  6807. {
  6808. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  6809. PrintMatchingFuncs(funcs, node);
  6810. ctx->type.SetDummy();
  6811. return -1;
  6812. }
  6813. }
  6814. }
  6815. else if( op == ttPlus || op == ttMinus )
  6816. {
  6817. ProcessPropertyGetAccessor(ctx, node);
  6818. asCDataType to = ctx->type.dataType;
  6819. // TODO: The case -2147483648 gives an unecessary warning of changed sign for implicit conversion
  6820. if( ctx->type.dataType.IsUnsignedType() || ctx->type.dataType.IsEnumType() )
  6821. {
  6822. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  6823. to = asCDataType::CreatePrimitive(ttInt8, false);
  6824. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  6825. to = asCDataType::CreatePrimitive(ttInt16, false);
  6826. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  6827. to = asCDataType::CreatePrimitive(ttInt, false);
  6828. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  6829. to = asCDataType::CreatePrimitive(ttInt64, false);
  6830. else
  6831. {
  6832. Error(TXT_INVALID_TYPE, node);
  6833. return -1;
  6834. }
  6835. }
  6836. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  6837. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  6838. if( !ctx->type.isConstant )
  6839. {
  6840. ConvertToTempVariable(ctx);
  6841. asASSERT(!ctx->type.isLValue);
  6842. if( op == ttMinus )
  6843. {
  6844. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6845. ctx->bc.InstrSHORT(asBC_NEGi, ctx->type.stackOffset);
  6846. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  6847. ctx->bc.InstrSHORT(asBC_NEGi64, ctx->type.stackOffset);
  6848. else if( ctx->type.dataType.IsFloatType() )
  6849. ctx->bc.InstrSHORT(asBC_NEGf, ctx->type.stackOffset);
  6850. else if( ctx->type.dataType.IsDoubleType() )
  6851. ctx->bc.InstrSHORT(asBC_NEGd, ctx->type.stackOffset);
  6852. else
  6853. {
  6854. Error(TXT_ILLEGAL_OPERATION, node);
  6855. return -1;
  6856. }
  6857. return 0;
  6858. }
  6859. }
  6860. else
  6861. {
  6862. if( op == ttMinus )
  6863. {
  6864. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6865. ctx->type.intValue = -ctx->type.intValue;
  6866. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  6867. ctx->type.qwordValue = -(asINT64)ctx->type.qwordValue;
  6868. else if( ctx->type.dataType.IsFloatType() )
  6869. ctx->type.floatValue = -ctx->type.floatValue;
  6870. else if( ctx->type.dataType.IsDoubleType() )
  6871. ctx->type.doubleValue = -ctx->type.doubleValue;
  6872. else
  6873. {
  6874. Error(TXT_ILLEGAL_OPERATION, node);
  6875. return -1;
  6876. }
  6877. return 0;
  6878. }
  6879. }
  6880. if( op == ttPlus )
  6881. {
  6882. if( !ctx->type.dataType.IsIntegerType() &&
  6883. !ctx->type.dataType.IsFloatType() &&
  6884. !ctx->type.dataType.IsDoubleType() )
  6885. {
  6886. Error(TXT_ILLEGAL_OPERATION, node);
  6887. return -1;
  6888. }
  6889. }
  6890. }
  6891. else if( op == ttNot )
  6892. {
  6893. if( ctx->type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  6894. {
  6895. if( ctx->type.isConstant )
  6896. {
  6897. ctx->type.dwordValue = (ctx->type.dwordValue == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  6898. return 0;
  6899. }
  6900. ProcessPropertyGetAccessor(ctx, node);
  6901. ConvertToTempVariable(ctx);
  6902. asASSERT(!ctx->type.isLValue);
  6903. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  6904. }
  6905. else
  6906. {
  6907. Error(TXT_ILLEGAL_OPERATION, node);
  6908. return -1;
  6909. }
  6910. }
  6911. else if( op == ttBitNot )
  6912. {
  6913. ProcessPropertyGetAccessor(ctx, node);
  6914. asCDataType to = ctx->type.dataType;
  6915. if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType() )
  6916. {
  6917. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  6918. to = asCDataType::CreatePrimitive(ttUInt8, false);
  6919. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  6920. to = asCDataType::CreatePrimitive(ttUInt16, false);
  6921. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  6922. to = asCDataType::CreatePrimitive(ttUInt, false);
  6923. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  6924. to = asCDataType::CreatePrimitive(ttUInt64, false);
  6925. else
  6926. {
  6927. Error(TXT_INVALID_TYPE, node);
  6928. return -1;
  6929. }
  6930. }
  6931. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  6932. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  6933. if( ctx->type.dataType.IsUnsignedType() )
  6934. {
  6935. if( ctx->type.isConstant )
  6936. {
  6937. ctx->type.qwordValue = ~ctx->type.qwordValue;
  6938. return 0;
  6939. }
  6940. ConvertToTempVariable(ctx);
  6941. asASSERT(!ctx->type.isLValue);
  6942. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6943. ctx->bc.InstrSHORT(asBC_BNOT, ctx->type.stackOffset);
  6944. else
  6945. ctx->bc.InstrSHORT(asBC_BNOT64, ctx->type.stackOffset);
  6946. }
  6947. else
  6948. {
  6949. Error(TXT_ILLEGAL_OPERATION, node);
  6950. return -1;
  6951. }
  6952. }
  6953. else if( op == ttInc || op == ttDec )
  6954. {
  6955. // Need a reference to the primitive that will be updated
  6956. // The result of this expression is the same reference as before
  6957. // Make sure the reference isn't a temporary variable
  6958. if( ctx->type.isTemporary )
  6959. {
  6960. Error(TXT_REF_IS_TEMP, node);
  6961. return -1;
  6962. }
  6963. if( ctx->type.dataType.IsReadOnly() )
  6964. {
  6965. Error(TXT_REF_IS_READ_ONLY, node);
  6966. return -1;
  6967. }
  6968. if( ctx->property_get || ctx->property_set )
  6969. {
  6970. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  6971. return -1;
  6972. }
  6973. if( !ctx->type.isLValue )
  6974. {
  6975. Error(TXT_NOT_LVALUE, node);
  6976. return -1;
  6977. }
  6978. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  6979. ConvertToReference(ctx);
  6980. else if( !ctx->type.dataType.IsReference() )
  6981. {
  6982. Error(TXT_NOT_VALID_REFERENCE, node);
  6983. return -1;
  6984. }
  6985. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  6986. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  6987. {
  6988. if( op == ttInc )
  6989. ctx->bc.Instr(asBC_INCi64);
  6990. else
  6991. ctx->bc.Instr(asBC_DECi64);
  6992. }
  6993. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt, false)) ||
  6994. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt, false)) )
  6995. {
  6996. if( op == ttInc )
  6997. ctx->bc.Instr(asBC_INCi);
  6998. else
  6999. ctx->bc.Instr(asBC_DECi);
  7000. }
  7001. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  7002. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  7003. {
  7004. if( op == ttInc )
  7005. ctx->bc.Instr(asBC_INCi16);
  7006. else
  7007. ctx->bc.Instr(asBC_DECi16);
  7008. }
  7009. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  7010. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  7011. {
  7012. if( op == ttInc )
  7013. ctx->bc.Instr(asBC_INCi8);
  7014. else
  7015. ctx->bc.Instr(asBC_DECi8);
  7016. }
  7017. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttFloat, false)) )
  7018. {
  7019. if( op == ttInc )
  7020. ctx->bc.Instr(asBC_INCf);
  7021. else
  7022. ctx->bc.Instr(asBC_DECf);
  7023. }
  7024. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttDouble, false)) )
  7025. {
  7026. if( op == ttInc )
  7027. ctx->bc.Instr(asBC_INCd);
  7028. else
  7029. ctx->bc.Instr(asBC_DECd);
  7030. }
  7031. else
  7032. {
  7033. Error(TXT_ILLEGAL_OPERATION, node);
  7034. return -1;
  7035. }
  7036. }
  7037. else
  7038. {
  7039. // Unknown operator
  7040. asASSERT(false);
  7041. return -1;
  7042. }
  7043. return 0;
  7044. }
  7045. void asCCompiler::ConvertToReference(asSExprContext *ctx)
  7046. {
  7047. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  7048. {
  7049. ctx->bc.InstrSHORT(asBC_LDV, ctx->type.stackOffset);
  7050. ctx->type.dataType.MakeReference(true);
  7051. ctx->type.SetVariable(ctx->type.dataType, ctx->type.stackOffset, ctx->type.isTemporary);
  7052. }
  7053. }
  7054. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asCScriptNode *node, bool isThisAccess)
  7055. {
  7056. return FindPropertyAccessor(name, ctx, 0, node, isThisAccess);
  7057. }
  7058. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node, bool isThisAccess)
  7059. {
  7060. if( engine->ep.propertyAccessorMode == 0 )
  7061. {
  7062. // Property accessors have been disabled by the application
  7063. return 0;
  7064. }
  7065. int getId = 0, setId = 0;
  7066. asCString getName = "get_" + name;
  7067. asCString setName = "set_" + name;
  7068. asCArray<int> multipleGetFuncs, multipleSetFuncs;
  7069. if( ctx->type.dataType.IsObject() )
  7070. {
  7071. // Check if the object has any methods with the corresponding accessor name(s)
  7072. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  7073. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7074. {
  7075. asCScriptFunction *f = engine->scriptFunctions[ot->methods[n]];
  7076. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  7077. if( f->name == getName && (int)f->parameterTypes.GetLength() == (arg?1:0) )
  7078. {
  7079. if( getId == 0 )
  7080. getId = ot->methods[n];
  7081. else
  7082. {
  7083. if( multipleGetFuncs.GetLength() == 0 )
  7084. multipleGetFuncs.PushLast(getId);
  7085. multipleGetFuncs.PushLast(ot->methods[n]);
  7086. }
  7087. }
  7088. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  7089. if( f->name == setName && (int)f->parameterTypes.GetLength() == (arg?2:1) )
  7090. {
  7091. if( setId == 0 )
  7092. setId = ot->methods[n];
  7093. else
  7094. {
  7095. if( multipleSetFuncs.GetLength() == 0 )
  7096. multipleSetFuncs.PushLast(setId);
  7097. multipleSetFuncs.PushLast(ot->methods[n]);
  7098. }
  7099. }
  7100. }
  7101. }
  7102. else
  7103. {
  7104. // Look for appropriate global functions.
  7105. asCArray<int> funcs;
  7106. asUINT n;
  7107. // TODO: namespace: use the proper namespace
  7108. builder->GetFunctionDescriptions(getName.AddressOf(), funcs, "");
  7109. for( n = 0; n < funcs.GetLength(); n++ )
  7110. {
  7111. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  7112. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  7113. if( (int)f->parameterTypes.GetLength() == (arg?1:0) )
  7114. {
  7115. if( getId == 0 )
  7116. getId = funcs[n];
  7117. else
  7118. {
  7119. if( multipleGetFuncs.GetLength() == 0 )
  7120. multipleGetFuncs.PushLast(getId);
  7121. multipleGetFuncs.PushLast(funcs[n]);
  7122. }
  7123. }
  7124. }
  7125. funcs.SetLength(0);
  7126. // TODO: namespace: use the proper namespace
  7127. builder->GetFunctionDescriptions(setName.AddressOf(), funcs, "");
  7128. for( n = 0; n < funcs.GetLength(); n++ )
  7129. {
  7130. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  7131. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  7132. if( (int)f->parameterTypes.GetLength() == (arg?2:1) )
  7133. {
  7134. if( setId == 0 )
  7135. setId = funcs[n];
  7136. else
  7137. {
  7138. if( multipleSetFuncs.GetLength() == 0 )
  7139. multipleSetFuncs.PushLast(getId);
  7140. multipleSetFuncs.PushLast(funcs[n]);
  7141. }
  7142. }
  7143. }
  7144. }
  7145. bool isConst = false;
  7146. if( ctx->type.dataType.IsObjectHandle() )
  7147. isConst = ctx->type.dataType.IsHandleToConst();
  7148. else
  7149. isConst = ctx->type.dataType.IsReadOnly();
  7150. // Check for multiple matches
  7151. if( multipleGetFuncs.GetLength() > 0 )
  7152. {
  7153. // Filter the list by constness
  7154. FilterConst(multipleGetFuncs, !isConst);
  7155. if( multipleGetFuncs.GetLength() > 1 )
  7156. {
  7157. asCString str;
  7158. str.Format(TXT_MULTIPLE_PROP_GET_ACCESSOR_FOR_s, name.AddressOf());
  7159. Error(str.AddressOf(), node);
  7160. PrintMatchingFuncs(multipleGetFuncs, node);
  7161. return -1;
  7162. }
  7163. else
  7164. {
  7165. // The id may have changed
  7166. getId = multipleGetFuncs[0];
  7167. }
  7168. }
  7169. if( multipleSetFuncs.GetLength() > 0 )
  7170. {
  7171. // Filter the list by constness
  7172. FilterConst(multipleSetFuncs, !isConst);
  7173. if( multipleSetFuncs.GetLength() > 1 )
  7174. {
  7175. asCString str;
  7176. str.Format(TXT_MULTIPLE_PROP_SET_ACCESSOR_FOR_s, name.AddressOf());
  7177. Error(str.AddressOf(), node);
  7178. PrintMatchingFuncs(multipleSetFuncs, node);
  7179. return -1;
  7180. }
  7181. else
  7182. {
  7183. // The id may have changed
  7184. setId = multipleSetFuncs[0];
  7185. }
  7186. }
  7187. // Check for type compatibility between get and set accessor
  7188. if( getId && setId )
  7189. {
  7190. asCScriptFunction *getFunc = builder->GetFunctionDescription(getId);
  7191. asCScriptFunction *setFunc = builder->GetFunctionDescription(setId);
  7192. // It is permitted for a getter to return a handle and the setter to take a reference
  7193. int idx = (arg?1:0);
  7194. if( !getFunc->returnType.IsEqualExceptRefAndConst(setFunc->parameterTypes[idx]) &&
  7195. !((getFunc->returnType.IsObjectHandle() && !setFunc->parameterTypes[idx].IsObjectHandle()) &&
  7196. (getFunc->returnType.GetObjectType() == setFunc->parameterTypes[idx].GetObjectType())) )
  7197. {
  7198. asCString str;
  7199. str.Format(TXT_GET_SET_ACCESSOR_TYPE_MISMATCH_FOR_s, name.AddressOf());
  7200. Error(str.AddressOf(), node);
  7201. asCArray<int> funcs;
  7202. funcs.PushLast(getId);
  7203. funcs.PushLast(setId);
  7204. PrintMatchingFuncs(funcs, node);
  7205. return -1;
  7206. }
  7207. }
  7208. // Check if we are within one of the accessors
  7209. int realGetId = getId;
  7210. int realSetId = setId;
  7211. if( outFunc->objectType && isThisAccess )
  7212. {
  7213. // The property accessors would be virtual functions, so we need to find the real implementation
  7214. asCScriptFunction *getFunc = getId ? builder->GetFunctionDescription(getId) : 0;
  7215. if( getFunc &&
  7216. getFunc->funcType == asFUNC_VIRTUAL &&
  7217. outFunc->objectType->DerivesFrom(getFunc->objectType) )
  7218. realGetId = outFunc->objectType->virtualFunctionTable[getFunc->vfTableIdx]->id;
  7219. asCScriptFunction *setFunc = setId ? builder->GetFunctionDescription(setId) : 0;
  7220. if( setFunc &&
  7221. setFunc->funcType == asFUNC_VIRTUAL &&
  7222. outFunc->objectType->DerivesFrom(setFunc->objectType) )
  7223. realSetId = outFunc->objectType->virtualFunctionTable[setFunc->vfTableIdx]->id;
  7224. }
  7225. // Avoid recursive call, by not treating this as a property accessor call.
  7226. // This will also allow having the real property with the same name as the accessors.
  7227. if( (isThisAccess || outFunc->objectType == 0) &&
  7228. ((realGetId && realGetId == outFunc->id) ||
  7229. (realSetId && realSetId == outFunc->id)) )
  7230. {
  7231. getId = 0;
  7232. setId = 0;
  7233. }
  7234. // Check if the application has disabled script written property accessors
  7235. if( engine->ep.propertyAccessorMode == 1 )
  7236. {
  7237. if( getId && builder->GetFunctionDescription(getId)->funcType != asFUNC_SYSTEM )
  7238. getId = 0;
  7239. if( setId && builder->GetFunctionDescription(setId)->funcType != asFUNC_SYSTEM )
  7240. setId = 0;
  7241. }
  7242. if( getId || setId )
  7243. {
  7244. // Property accessors were found, but we don't know which is to be used yet, so
  7245. // we just prepare the bytecode for the method call, and then store the function ids
  7246. // so that the right one can be used when we get there.
  7247. ctx->property_get = getId;
  7248. ctx->property_set = setId;
  7249. if( ctx->type.dataType.IsObject() )
  7250. {
  7251. // If the object is read-only then we need to remember that
  7252. if( (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) ||
  7253. (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) )
  7254. ctx->property_const = true;
  7255. else
  7256. ctx->property_const = false;
  7257. // If the object is a handle then we need to remember that
  7258. ctx->property_handle = ctx->type.dataType.IsObjectHandle();
  7259. ctx->property_ref = ctx->type.dataType.IsReference();
  7260. }
  7261. // The setter's parameter type is used as the property type,
  7262. // unless only the getter is available
  7263. asCDataType dt;
  7264. if( setId )
  7265. dt = builder->GetFunctionDescription(setId)->parameterTypes[(arg?1:0)];
  7266. else
  7267. dt = builder->GetFunctionDescription(getId)->returnType;
  7268. // Just change the type, the context must still maintain information
  7269. // about previous variable offset and the indicator of temporary variable.
  7270. int offset = ctx->type.stackOffset;
  7271. bool isTemp = ctx->type.isTemporary;
  7272. ctx->type.Set(dt);
  7273. ctx->type.stackOffset = (short)offset;
  7274. ctx->type.isTemporary = isTemp;
  7275. ctx->exprNode = node;
  7276. // Store the argument for later use
  7277. if( arg )
  7278. {
  7279. ctx->property_arg = asNEW(asSExprContext)(engine);
  7280. MergeExprBytecodeAndType(ctx->property_arg, arg);
  7281. }
  7282. return 1;
  7283. }
  7284. // No accessor was found
  7285. return 0;
  7286. }
  7287. int asCCompiler::ProcessPropertySetAccessor(asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node)
  7288. {
  7289. // TODO: A lot of this code is similar to ProcessPropertyGetAccessor. Can we unify them?
  7290. if( !ctx->property_set )
  7291. {
  7292. Error(TXT_PROPERTY_HAS_NO_SET_ACCESSOR, node);
  7293. return -1;
  7294. }
  7295. asCTypeInfo objType = ctx->type;
  7296. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_set);
  7297. // Make sure the arg match the property
  7298. asCArray<int> funcs;
  7299. funcs.PushLast(ctx->property_set);
  7300. asCArray<asSExprContext *> args;
  7301. if( ctx->property_arg )
  7302. args.PushLast(ctx->property_arg);
  7303. args.PushLast(arg);
  7304. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  7305. if( funcs.GetLength() == 0 )
  7306. {
  7307. // MatchFunctions already reported the error
  7308. if( ctx->property_arg )
  7309. {
  7310. asDELETE(ctx->property_arg, asSExprContext);
  7311. ctx->property_arg = 0;
  7312. }
  7313. return -1;
  7314. }
  7315. if( func->objectType )
  7316. {
  7317. // Setup the context with the original type so the method call gets built correctly
  7318. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7319. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7320. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7321. // Don't allow the call if the object is read-only and the property accessor is not const
  7322. if( ctx->property_const && !func->isReadOnly )
  7323. {
  7324. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  7325. asCArray<int> funcs;
  7326. funcs.PushLast(ctx->property_set);
  7327. PrintMatchingFuncs(funcs, node);
  7328. }
  7329. }
  7330. // Call the accessor
  7331. MakeFunctionCall(ctx, ctx->property_set, func->objectType, args, node);
  7332. if( func->objectType )
  7333. {
  7334. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  7335. if( !objType.isTemporary ||
  7336. !ctx->type.dataType.IsReference() ||
  7337. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7338. {
  7339. // As the method didn't return a reference to a member
  7340. // we can safely release the original object now
  7341. ReleaseTemporaryVariable(objType, &ctx->bc);
  7342. }
  7343. }
  7344. ctx->property_get = 0;
  7345. ctx->property_set = 0;
  7346. if( ctx->property_arg )
  7347. {
  7348. asDELETE(ctx->property_arg, asSExprContext);
  7349. ctx->property_arg = 0;
  7350. }
  7351. return 0;
  7352. }
  7353. void asCCompiler::ProcessPropertyGetAccessor(asSExprContext *ctx, asCScriptNode *node)
  7354. {
  7355. // If no property accessor has been prepared then don't do anything
  7356. if( !ctx->property_get && !ctx->property_set )
  7357. return;
  7358. if( !ctx->property_get )
  7359. {
  7360. // Raise error on missing accessor
  7361. Error(TXT_PROPERTY_HAS_NO_GET_ACCESSOR, node);
  7362. ctx->type.SetDummy();
  7363. return;
  7364. }
  7365. asCTypeInfo objType = ctx->type;
  7366. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_get);
  7367. // Make sure the arg match the property
  7368. asCArray<int> funcs;
  7369. funcs.PushLast(ctx->property_get);
  7370. asCArray<asSExprContext *> args;
  7371. if( ctx->property_arg )
  7372. args.PushLast(ctx->property_arg);
  7373. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  7374. if( funcs.GetLength() == 0 )
  7375. {
  7376. // MatchFunctions already reported the error
  7377. if( ctx->property_arg )
  7378. {
  7379. asDELETE(ctx->property_arg, asSExprContext);
  7380. ctx->property_arg = 0;
  7381. }
  7382. ctx->type.SetDummy();
  7383. return;
  7384. }
  7385. if( func->objectType )
  7386. {
  7387. // Setup the context with the original type so the method call gets built correctly
  7388. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7389. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7390. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7391. // Don't allow the call if the object is read-only and the property accessor is not const
  7392. if( ctx->property_const && !func->isReadOnly )
  7393. {
  7394. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  7395. asCArray<int> funcs;
  7396. funcs.PushLast(ctx->property_get);
  7397. PrintMatchingFuncs(funcs, node);
  7398. }
  7399. }
  7400. // Call the accessor
  7401. MakeFunctionCall(ctx, ctx->property_get, func->objectType, args, node);
  7402. if( func->objectType )
  7403. {
  7404. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  7405. if( !objType.isTemporary ||
  7406. !ctx->type.dataType.IsReference() ||
  7407. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7408. {
  7409. // As the method didn't return a reference to a member
  7410. // we can safely release the original object now
  7411. ReleaseTemporaryVariable(objType, &ctx->bc);
  7412. }
  7413. }
  7414. ctx->property_get = 0;
  7415. ctx->property_set = 0;
  7416. if( ctx->property_arg )
  7417. {
  7418. asDELETE(ctx->property_arg, asSExprContext);
  7419. ctx->property_arg = 0;
  7420. }
  7421. }
  7422. int asCCompiler::CompileExpressionPostOp(asCScriptNode *node, asSExprContext *ctx)
  7423. {
  7424. int op = node->tokenType;
  7425. // Check if the variable is initialized (if it indeed is a variable)
  7426. IsVariableInitialized(&ctx->type, node);
  7427. if( (op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  7428. {
  7429. const char *opName = 0;
  7430. switch( op )
  7431. {
  7432. case ttInc: opName = "opPostInc"; break;
  7433. case ttDec: opName = "opPostDec"; break;
  7434. }
  7435. if( opName )
  7436. {
  7437. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  7438. ProcessPropertyGetAccessor(ctx, node);
  7439. // Is it a const value?
  7440. bool isConst = false;
  7441. if( ctx->type.dataType.IsObjectHandle() )
  7442. isConst = ctx->type.dataType.IsHandleToConst();
  7443. else
  7444. isConst = ctx->type.dataType.IsReadOnly();
  7445. // 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
  7446. // Find the correct method
  7447. asCArray<int> funcs;
  7448. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  7449. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7450. {
  7451. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  7452. if( func->name == opName &&
  7453. func->parameterTypes.GetLength() == 0 &&
  7454. (!isConst || func->isReadOnly) )
  7455. {
  7456. funcs.PushLast(func->id);
  7457. }
  7458. }
  7459. // Did we find the method?
  7460. if( funcs.GetLength() == 1 )
  7461. {
  7462. asCTypeInfo objType = ctx->type;
  7463. asCArray<asSExprContext *> args;
  7464. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  7465. ReleaseTemporaryVariable(objType, &ctx->bc);
  7466. return 0;
  7467. }
  7468. else if( funcs.GetLength() == 0 )
  7469. {
  7470. asCString str;
  7471. str = asCString(opName) + "()";
  7472. if( isConst )
  7473. str += " const";
  7474. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  7475. Error(str.AddressOf(), node);
  7476. ctx->type.SetDummy();
  7477. return -1;
  7478. }
  7479. else if( funcs.GetLength() > 1 )
  7480. {
  7481. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  7482. PrintMatchingFuncs(funcs, node);
  7483. ctx->type.SetDummy();
  7484. return -1;
  7485. }
  7486. }
  7487. }
  7488. else if( op == ttInc || op == ttDec )
  7489. {
  7490. // Make sure the reference isn't a temporary variable
  7491. if( ctx->type.isTemporary )
  7492. {
  7493. Error(TXT_REF_IS_TEMP, node);
  7494. return -1;
  7495. }
  7496. if( ctx->type.dataType.IsReadOnly() )
  7497. {
  7498. Error(TXT_REF_IS_READ_ONLY, node);
  7499. return -1;
  7500. }
  7501. if( ctx->property_get || ctx->property_set )
  7502. {
  7503. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  7504. return -1;
  7505. }
  7506. if( !ctx->type.isLValue )
  7507. {
  7508. Error(TXT_NOT_LVALUE, node);
  7509. return -1;
  7510. }
  7511. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  7512. ConvertToReference(ctx);
  7513. else if( !ctx->type.dataType.IsReference() )
  7514. {
  7515. Error(TXT_NOT_VALID_REFERENCE, node);
  7516. return -1;
  7517. }
  7518. // Copy the value to a temp before changing it
  7519. ConvertToTempVariable(ctx);
  7520. asASSERT(!ctx->type.isLValue);
  7521. // Increment the value pointed to by the reference still in the register
  7522. asEBCInstr iInc = asBC_INCi, iDec = asBC_DECi;
  7523. if( ctx->type.dataType.IsDoubleType() )
  7524. {
  7525. iInc = asBC_INCd;
  7526. iDec = asBC_DECd;
  7527. }
  7528. else if( ctx->type.dataType.IsFloatType() )
  7529. {
  7530. iInc = asBC_INCf;
  7531. iDec = asBC_DECf;
  7532. }
  7533. else if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() )
  7534. {
  7535. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  7536. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  7537. {
  7538. iInc = asBC_INCi16;
  7539. iDec = asBC_DECi16;
  7540. }
  7541. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  7542. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  7543. {
  7544. iInc = asBC_INCi8;
  7545. iDec = asBC_DECi8;
  7546. }
  7547. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  7548. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  7549. {
  7550. iInc = asBC_INCi64;
  7551. iDec = asBC_DECi64;
  7552. }
  7553. }
  7554. else
  7555. {
  7556. Error(TXT_ILLEGAL_OPERATION, node);
  7557. return -1;
  7558. }
  7559. if( op == ttInc ) ctx->bc.Instr(iInc); else ctx->bc.Instr(iDec);
  7560. }
  7561. else if( op == ttDot )
  7562. {
  7563. if( node->firstChild->nodeType == snIdentifier )
  7564. {
  7565. ProcessPropertyGetAccessor(ctx, node);
  7566. // Get the property name
  7567. asCString name(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  7568. // We need to look for get/set property accessors.
  7569. // If found, the context stores information on the get/set accessors
  7570. // until it is known which is to be used.
  7571. int r = 0;
  7572. if( node->next && node->next->tokenType == ttOpenBracket )
  7573. {
  7574. // The property accessor should take an index arg
  7575. asSExprContext dummyArg(engine);
  7576. r = FindPropertyAccessor(name, ctx, &dummyArg, node);
  7577. }
  7578. if( r == 0 )
  7579. r = FindPropertyAccessor(name, ctx, node);
  7580. if( r != 0 )
  7581. return r;
  7582. if( !ctx->type.dataType.IsPrimitive() )
  7583. Dereference(ctx, true);
  7584. if( ctx->type.dataType.IsObjectHandle() )
  7585. {
  7586. // Convert the handle to a normal object
  7587. asCDataType dt = ctx->type.dataType;
  7588. dt.MakeHandle(false);
  7589. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  7590. // The handle may not have been an lvalue, but the dereferenced object is
  7591. ctx->type.isLValue = true;
  7592. }
  7593. // Find the property offset and type
  7594. if( ctx->type.dataType.IsObject() )
  7595. {
  7596. bool isConst = ctx->type.dataType.IsReadOnly();
  7597. asCObjectProperty *prop = builder->GetObjectProperty(ctx->type.dataType, name.AddressOf());
  7598. if( prop )
  7599. {
  7600. // Is the property access allowed?
  7601. if( prop->isPrivate && (!outFunc || outFunc->objectType != ctx->type.dataType.GetObjectType()) )
  7602. {
  7603. asCString msg;
  7604. msg.Format(TXT_PRIVATE_PROP_ACCESS_s, name.AddressOf());
  7605. Error(msg.AddressOf(), node);
  7606. }
  7607. // Put the offset on the stack
  7608. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(ctx->type.dataType.GetObjectType(), false)));
  7609. if( prop->type.IsReference() )
  7610. ctx->bc.Instr(asBC_RDSPtr);
  7611. // Reference to primitive must be stored in the temp register
  7612. if( prop->type.IsPrimitive() )
  7613. {
  7614. ctx->bc.Instr(asBC_PopRPtr);
  7615. }
  7616. // Keep information about temporary variables as deferred expression
  7617. if( ctx->type.isTemporary )
  7618. {
  7619. // Add the release of this reference, as a deferred expression
  7620. asSDeferredParam deferred;
  7621. deferred.origExpr = 0;
  7622. deferred.argInOutFlags = asTM_INREF;
  7623. deferred.argNode = 0;
  7624. deferred.argType.SetVariable(ctx->type.dataType, ctx->type.stackOffset, true);
  7625. ctx->deferredParams.PushLast(deferred);
  7626. }
  7627. // Set the new type and make sure it is not treated as a variable anymore
  7628. ctx->type.dataType = prop->type;
  7629. ctx->type.dataType.MakeReference(true);
  7630. ctx->type.isVariable = false;
  7631. ctx->type.isTemporary = false;
  7632. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  7633. {
  7634. // Objects that are members are not references
  7635. ctx->type.dataType.MakeReference(false);
  7636. }
  7637. ctx->type.dataType.MakeReadOnly(isConst ? true : prop->type.IsReadOnly());
  7638. }
  7639. else
  7640. {
  7641. asCString str;
  7642. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  7643. Error(str.AddressOf(), node);
  7644. return -1;
  7645. }
  7646. }
  7647. else
  7648. {
  7649. asCString str;
  7650. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  7651. Error(str.AddressOf(), node);
  7652. return -1;
  7653. }
  7654. }
  7655. else
  7656. {
  7657. // Make sure it is an object we are accessing
  7658. if( !ctx->type.dataType.IsObject() )
  7659. {
  7660. asCString str;
  7661. str.Format(TXT_ILLEGAL_OPERATION_ON_s, ctx->type.dataType.Format().AddressOf());
  7662. Error(str.AddressOf(), node);
  7663. return -1;
  7664. }
  7665. // Process the get property accessor
  7666. ProcessPropertyGetAccessor(ctx, node);
  7667. bool isConst = false;
  7668. if( ctx->type.dataType.IsObjectHandle() )
  7669. isConst = ctx->type.dataType.IsHandleToConst();
  7670. else
  7671. isConst = ctx->type.dataType.IsReadOnly();
  7672. asCObjectType *trueObj = ctx->type.dataType.GetObjectType();
  7673. asCTypeInfo objType = ctx->type;
  7674. // Compile function call
  7675. int r = CompileFunctionCall(node->firstChild, ctx, trueObj, isConst);
  7676. if( r < 0 ) return r;
  7677. // If the method returned a reference, then we can't release the original
  7678. // object yet, because the reference may be to a member of it
  7679. if( !objType.isTemporary ||
  7680. !(ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) ||
  7681. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7682. {
  7683. // As the method didn't return a reference to a member
  7684. // we can safely release the original object now
  7685. ReleaseTemporaryVariable(objType, &ctx->bc);
  7686. }
  7687. }
  7688. }
  7689. else if( op == ttOpenBracket )
  7690. {
  7691. // If the property access takes an index arg, then we should use that instead of processing it now
  7692. asCString propertyName;
  7693. if( (ctx->property_get && builder->GetFunctionDescription(ctx->property_get)->GetParamCount() == 1) ||
  7694. (ctx->property_set && builder->GetFunctionDescription(ctx->property_set)->GetParamCount() == 2) )
  7695. {
  7696. // Determine the name of the property accessor
  7697. asCScriptFunction *func = 0;
  7698. if( ctx->property_get )
  7699. func = builder->GetFunctionDescription(ctx->property_get);
  7700. else
  7701. func = builder->GetFunctionDescription(ctx->property_set);
  7702. propertyName = func->GetName();
  7703. propertyName = propertyName.SubString(4);
  7704. // Set the original type of the expression so we can re-evaluate the property accessor
  7705. if( func->objectType )
  7706. {
  7707. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7708. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7709. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7710. }
  7711. else
  7712. {
  7713. ctx->type.SetDummy();
  7714. }
  7715. ctx->property_get = ctx->property_set = 0;
  7716. if( ctx->property_arg )
  7717. {
  7718. asDELETE(ctx->property_arg, asSExprContext);
  7719. ctx->property_arg = 0;
  7720. }
  7721. }
  7722. else
  7723. {
  7724. if( !ctx->type.dataType.IsObject() )
  7725. {
  7726. asCString str;
  7727. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  7728. Error(str.AddressOf(), node);
  7729. return -1;
  7730. }
  7731. ProcessPropertyGetAccessor(ctx, node);
  7732. }
  7733. Dereference(ctx, true);
  7734. // Compile the expression
  7735. asSExprContext expr(engine);
  7736. CompileAssignment(node->firstChild, &expr);
  7737. // Check for the existence of the opIndex method
  7738. asSExprContext lctx(engine);
  7739. MergeExprBytecodeAndType(&lctx, ctx);
  7740. int r = 0;
  7741. if( propertyName == "" )
  7742. r = CompileOverloadedDualOperator2(node, "opIndex", &lctx, &expr, ctx);
  7743. if( r == 0 )
  7744. {
  7745. // Check for accessors methods for the opIndex
  7746. r = FindPropertyAccessor(propertyName == "" ? "opIndex" : propertyName.AddressOf(), &lctx, &expr, node);
  7747. if( r == 0 )
  7748. {
  7749. asCString str;
  7750. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  7751. Error(str.AddressOf(), node);
  7752. return -1;
  7753. }
  7754. else if( r < 0 )
  7755. return -1;
  7756. MergeExprBytecodeAndType(ctx, &lctx);
  7757. }
  7758. }
  7759. return 0;
  7760. }
  7761. int asCCompiler::GetPrecedence(asCScriptNode *op)
  7762. {
  7763. // x * y, x / y, x % y
  7764. // x + y, x - y
  7765. // x <= y, x < y, x >= y, x > y
  7766. // x = =y, x != y, x xor y, x is y, x !is y
  7767. // x and y
  7768. // x or y
  7769. // The following are not used in this function,
  7770. // but should have lower precedence than the above
  7771. // x ? y : z
  7772. // x = y
  7773. // The expression term have the highest precedence
  7774. if( op->nodeType == snExprTerm )
  7775. return 1;
  7776. // Evaluate operators by token
  7777. int tokenType = op->tokenType;
  7778. if( tokenType == ttStar || tokenType == ttSlash || tokenType == ttPercent )
  7779. return 0;
  7780. if( tokenType == ttPlus || tokenType == ttMinus )
  7781. return -1;
  7782. if( tokenType == ttBitShiftLeft ||
  7783. tokenType == ttBitShiftRight ||
  7784. tokenType == ttBitShiftRightArith )
  7785. return -2;
  7786. if( tokenType == ttAmp )
  7787. return -3;
  7788. if( tokenType == ttBitXor )
  7789. return -4;
  7790. if( tokenType == ttBitOr )
  7791. return -5;
  7792. if( tokenType == ttLessThanOrEqual ||
  7793. tokenType == ttLessThan ||
  7794. tokenType == ttGreaterThanOrEqual ||
  7795. tokenType == ttGreaterThan )
  7796. return -6;
  7797. if( tokenType == ttEqual || tokenType == ttNotEqual || tokenType == ttXor || tokenType == ttIs || tokenType == ttNotIs )
  7798. return -7;
  7799. if( tokenType == ttAnd )
  7800. return -8;
  7801. if( tokenType == ttOr )
  7802. return -9;
  7803. // Unknown operator
  7804. asASSERT(false);
  7805. return 0;
  7806. }
  7807. asUINT asCCompiler::MatchArgument(asCArray<int> &funcs, asCArray<int> &matches, const asCTypeInfo *argType, int paramNum, bool allowObjectConstruct)
  7808. {
  7809. asUINT bestCost = asUINT(-1);
  7810. matches.SetLength(0);
  7811. for( asUINT n = 0; n < funcs.GetLength(); n++ )
  7812. {
  7813. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  7814. // Does the function have arguments enough?
  7815. if( (int)desc->parameterTypes.GetLength() <= paramNum )
  7816. continue;
  7817. // Can we make the match by implicit conversion?
  7818. asSExprContext ti(engine);
  7819. ti.type = *argType;
  7820. if( argType->dataType.IsPrimitive() ) ti.type.dataType.MakeReference(false);
  7821. asUINT cost = ImplicitConversion(&ti, desc->parameterTypes[paramNum], 0, asIC_IMPLICIT_CONV, false, allowObjectConstruct);
  7822. // If the function parameter is an inout-reference then it must not be possible to call the
  7823. // function with an incorrect argument type, even though the type can normally be converted.
  7824. if( desc->parameterTypes[paramNum].IsReference() &&
  7825. desc->inOutFlags[paramNum] == asTM_INOUTREF &&
  7826. desc->parameterTypes[paramNum].GetTokenType() != ttQuestion )
  7827. {
  7828. if( desc->parameterTypes[paramNum].IsPrimitive() &&
  7829. desc->parameterTypes[paramNum].GetTokenType() != argType->dataType.GetTokenType() )
  7830. continue;
  7831. if( desc->parameterTypes[paramNum].IsEnumType() &&
  7832. desc->parameterTypes[paramNum].GetObjectType() != argType->dataType.GetObjectType() )
  7833. continue;
  7834. }
  7835. // How well does the argument match the function parameter?
  7836. if( desc->parameterTypes[paramNum].IsEqualExceptRef(ti.type.dataType) )
  7837. {
  7838. if( cost < bestCost )
  7839. {
  7840. matches.SetLength(0);
  7841. bestCost = cost;
  7842. }
  7843. if( cost == bestCost )
  7844. matches.PushLast(funcs[n]);
  7845. }
  7846. }
  7847. return bestCost;
  7848. }
  7849. void asCCompiler::PrepareArgument2(asSExprContext *ctx, asSExprContext *arg, asCDataType *paramType, bool isFunction, int refType, bool isMakingCopy)
  7850. {
  7851. // Reference parameters whose value won't be used don't evaluate the expression
  7852. if( paramType->IsReference() && !(refType & asTM_INREF) )
  7853. {
  7854. // Store the original bytecode so that it can be reused when processing the deferred output parameter
  7855. asSExprContext *orig = asNEW(asSExprContext)(engine);
  7856. MergeExprBytecodeAndType(orig, arg);
  7857. arg->origExpr = orig;
  7858. }
  7859. PrepareArgument(paramType, arg, arg->exprNode, isFunction, refType, isMakingCopy);
  7860. // arg still holds the original expression for output parameters
  7861. ctx->bc.AddCode(&arg->bc);
  7862. }
  7863. bool asCCompiler::CompileOverloadedDualOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  7864. {
  7865. ctx->exprNode = node;
  7866. // What type of operator is it?
  7867. int token = node->tokenType;
  7868. if( token == ttUnrecognizedToken )
  7869. {
  7870. // This happens when the compiler is inferring an assignment
  7871. // operation from another action, for example in preparing a value
  7872. // as a function argument
  7873. token = ttAssignment;
  7874. }
  7875. // boolean operators are not overloadable
  7876. if( token == ttAnd ||
  7877. token == ttOr ||
  7878. token == ttXor )
  7879. return false;
  7880. // Dual operators can also be implemented as class methods
  7881. if( token == ttEqual ||
  7882. token == ttNotEqual )
  7883. {
  7884. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7885. // Find the matching opEquals method
  7886. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  7887. if( r == 0 )
  7888. {
  7889. // Try again by switching the order of the operands
  7890. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  7891. }
  7892. if( r == 1 )
  7893. {
  7894. if( token == ttNotEqual )
  7895. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  7896. // Success, don't continue
  7897. return true;
  7898. }
  7899. else if( r < 0 )
  7900. {
  7901. // Compiler error, don't continue
  7902. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  7903. return true;
  7904. }
  7905. }
  7906. if( token == ttEqual ||
  7907. token == ttNotEqual ||
  7908. token == ttLessThan ||
  7909. token == ttLessThanOrEqual ||
  7910. token == ttGreaterThan ||
  7911. token == ttGreaterThanOrEqual )
  7912. {
  7913. bool swappedOrder = false;
  7914. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7915. // Find the matching opCmp method
  7916. int r = CompileOverloadedDualOperator2(node, "opCmp", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  7917. if( r == 0 )
  7918. {
  7919. // Try again by switching the order of the operands
  7920. swappedOrder = true;
  7921. r = CompileOverloadedDualOperator2(node, "opCmp", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  7922. }
  7923. if( r == 1 )
  7924. {
  7925. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  7926. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  7927. ctx->bc.InstrW_DW(asBC_CMPIi, ctx->type.stackOffset, 0);
  7928. if( token == ttEqual )
  7929. ctx->bc.Instr(asBC_TZ);
  7930. else if( token == ttNotEqual )
  7931. ctx->bc.Instr(asBC_TNZ);
  7932. else if( (token == ttLessThan && !swappedOrder) ||
  7933. (token == ttGreaterThan && swappedOrder) )
  7934. ctx->bc.Instr(asBC_TS);
  7935. else if( (token == ttLessThanOrEqual && !swappedOrder) ||
  7936. (token == ttGreaterThanOrEqual && swappedOrder) )
  7937. ctx->bc.Instr(asBC_TNP);
  7938. else if( (token == ttGreaterThan && !swappedOrder) ||
  7939. (token == ttLessThan && swappedOrder) )
  7940. ctx->bc.Instr(asBC_TP);
  7941. else if( (token == ttGreaterThanOrEqual && !swappedOrder) ||
  7942. (token == ttLessThanOrEqual && swappedOrder) )
  7943. ctx->bc.Instr(asBC_TNS);
  7944. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  7945. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), a, true);
  7946. // Success, don't continue
  7947. return true;
  7948. }
  7949. else if( r < 0 )
  7950. {
  7951. // Compiler error, don't continue
  7952. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  7953. return true;
  7954. }
  7955. }
  7956. // The rest of the operators are not commutative, and doesn't require specific return type
  7957. const char *op = 0, *op_r = 0;
  7958. switch( token )
  7959. {
  7960. case ttPlus: op = "opAdd"; op_r = "opAdd_r"; break;
  7961. case ttMinus: op = "opSub"; op_r = "opSub_r"; break;
  7962. case ttStar: op = "opMul"; op_r = "opMul_r"; break;
  7963. case ttSlash: op = "opDiv"; op_r = "opDiv_r"; break;
  7964. case ttPercent: op = "opMod"; op_r = "opMod_r"; break;
  7965. case ttBitOr: op = "opOr"; op_r = "opOr_r"; break;
  7966. case ttAmp: op = "opAnd"; op_r = "opAnd_r"; break;
  7967. case ttBitXor: op = "opXor"; op_r = "opXor_r"; break;
  7968. case ttBitShiftLeft: op = "opShl"; op_r = "opShl_r"; break;
  7969. case ttBitShiftRight: op = "opShr"; op_r = "opShr_r"; break;
  7970. case ttBitShiftRightArith: op = "opUShr"; op_r = "opUShr_r"; break;
  7971. }
  7972. // TODO: Might be interesting to support a concatenation operator, e.g. ~
  7973. if( op && op_r )
  7974. {
  7975. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7976. // Find the matching operator method
  7977. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  7978. if( r == 0 )
  7979. {
  7980. // Try again by switching the order of the operands, and using the reversed operator
  7981. r = CompileOverloadedDualOperator2(node, op_r, rctx, lctx, ctx);
  7982. }
  7983. if( r == 1 )
  7984. {
  7985. // Success, don't continue
  7986. return true;
  7987. }
  7988. else if( r < 0 )
  7989. {
  7990. // Compiler error, don't continue
  7991. ctx->type.SetDummy();
  7992. return true;
  7993. }
  7994. }
  7995. // Assignment operators
  7996. op = 0;
  7997. switch( token )
  7998. {
  7999. case ttAssignment: op = "opAssign"; break;
  8000. case ttAddAssign: op = "opAddAssign"; break;
  8001. case ttSubAssign: op = "opSubAssign"; break;
  8002. case ttMulAssign: op = "opMulAssign"; break;
  8003. case ttDivAssign: op = "opDivAssign"; break;
  8004. case ttModAssign: op = "opModAssign"; break;
  8005. case ttOrAssign: op = "opOrAssign"; break;
  8006. case ttAndAssign: op = "opAndAssign"; break;
  8007. case ttXorAssign: op = "opXorAssign"; break;
  8008. case ttShiftLeftAssign: op = "opShlAssign"; break;
  8009. case ttShiftRightLAssign: op = "opShrAssign"; break;
  8010. case ttShiftRightAAssign: op = "opUShrAssign"; break;
  8011. }
  8012. if( op )
  8013. {
  8014. // TODO: Shouldn't accept const lvalue with the assignment operators
  8015. // Find the matching operator method
  8016. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  8017. if( r == 1 )
  8018. {
  8019. // Success, don't continue
  8020. return true;
  8021. }
  8022. else if( r < 0 )
  8023. {
  8024. // Compiler error, don't continue
  8025. ctx->type.SetDummy();
  8026. return true;
  8027. }
  8028. }
  8029. // No suitable operator was found
  8030. return false;
  8031. }
  8032. // Returns negative on compile error
  8033. // zero on no matching operator
  8034. // one on matching operator
  8035. int asCCompiler::CompileOverloadedDualOperator2(asCScriptNode *node, const char *methodName, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx, bool specificReturn, const asCDataType &returnType)
  8036. {
  8037. // Find the matching method
  8038. if( lctx->type.dataType.IsObject() &&
  8039. (!lctx->type.isExplicitHandle ||
  8040. lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  8041. {
  8042. // Is the left value a const?
  8043. bool isConst = false;
  8044. if( lctx->type.dataType.IsObjectHandle() )
  8045. isConst = lctx->type.dataType.IsHandleToConst();
  8046. else
  8047. isConst = lctx->type.dataType.IsReadOnly();
  8048. asCArray<int> funcs;
  8049. asCObjectType *ot = lctx->type.dataType.GetObjectType();
  8050. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  8051. {
  8052. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  8053. if( func->name == methodName &&
  8054. (!specificReturn || func->returnType == returnType) &&
  8055. func->parameterTypes.GetLength() == 1 &&
  8056. (!isConst || func->isReadOnly) )
  8057. {
  8058. // Make sure the method is accessible by the module
  8059. if( builder->module->accessMask & func->accessMask )
  8060. {
  8061. funcs.PushLast(func->id);
  8062. }
  8063. }
  8064. }
  8065. // Which is the best matching function?
  8066. asCArray<int> ops;
  8067. MatchArgument(funcs, ops, &rctx->type, 0);
  8068. // If the object is not const, then we need to prioritize non-const methods
  8069. if( !isConst )
  8070. FilterConst(ops);
  8071. // Did we find an operator?
  8072. if( ops.GetLength() == 1 )
  8073. {
  8074. // Process the lctx expression as get accessor
  8075. ProcessPropertyGetAccessor(lctx, node);
  8076. // Merge the bytecode so that it forms lvalue.methodName(rvalue)
  8077. asCTypeInfo objType = lctx->type;
  8078. asCArray<asSExprContext *> args;
  8079. args.PushLast(rctx);
  8080. MergeExprBytecode(ctx, lctx);
  8081. ctx->type = lctx->type;
  8082. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  8083. // If the method returned a reference, then we can't release the original
  8084. // object yet, because the reference may be to a member of it
  8085. if( !objType.isTemporary ||
  8086. !(ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) ||
  8087. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not to a member
  8088. {
  8089. // As the index operator didn't return a reference to a
  8090. // member we can release the original object now
  8091. ReleaseTemporaryVariable(objType, &ctx->bc);
  8092. }
  8093. // Found matching operator
  8094. return 1;
  8095. }
  8096. else if( ops.GetLength() > 1 )
  8097. {
  8098. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  8099. PrintMatchingFuncs(ops, node);
  8100. ctx->type.SetDummy();
  8101. // Compiler error
  8102. return -1;
  8103. }
  8104. }
  8105. // No matching operator
  8106. return 0;
  8107. }
  8108. void asCCompiler::MakeFunctionCall(asSExprContext *ctx, int funcId, asCObjectType *objectType, asCArray<asSExprContext*> &args, asCScriptNode * /*node*/, bool useVariable, int stackOffset, int funcPtrVar)
  8109. {
  8110. if( objectType )
  8111. {
  8112. Dereference(ctx, true);
  8113. // This following warning was removed as there may be valid reasons
  8114. // for calling non-const methods on temporary objects, and we shouldn't
  8115. // warn when there is no way of removing the warning.
  8116. /*
  8117. // Warn if the method is non-const and the object is temporary
  8118. // since the changes will be lost when the object is destroyed.
  8119. // If the object is accessed through a handle, then it is assumed
  8120. // the object is not temporary, even though the handle is.
  8121. if( ctx->type.isTemporary &&
  8122. !ctx->type.dataType.IsObjectHandle() &&
  8123. !engine->scriptFunctions[funcId]->isReadOnly )
  8124. {
  8125. Warning("A non-const method is called on temporary object. Changes to the object may be lost.", node);
  8126. Information(engine->scriptFunctions[funcId]->GetDeclaration(), node);
  8127. }
  8128. */ }
  8129. asCByteCode objBC(engine);
  8130. objBC.AddCode(&ctx->bc);
  8131. PrepareFunctionCall(funcId, &ctx->bc, args);
  8132. // Verify if any of the args variable offsets are used in the other code.
  8133. // If they are exchange the offset for a new one
  8134. asUINT n;
  8135. for( n = 0; n < args.GetLength(); n++ )
  8136. {
  8137. if( args[n]->type.isTemporary && objBC.IsVarUsed(args[n]->type.stackOffset) )
  8138. {
  8139. // Release the current temporary variable
  8140. ReleaseTemporaryVariable(args[n]->type, 0);
  8141. asCDataType dt = args[n]->type.dataType;
  8142. dt.MakeReference(false);
  8143. int l = int(reservedVariables.GetLength());
  8144. objBC.GetVarsUsed(reservedVariables);
  8145. ctx->bc.GetVarsUsed(reservedVariables);
  8146. int newOffset = AllocateVariable(dt, true, IsVariableOnHeap(args[n]->type.stackOffset));
  8147. reservedVariables.SetLength(l);
  8148. asASSERT( IsVariableOnHeap(args[n]->type.stackOffset) == IsVariableOnHeap(newOffset) );
  8149. ctx->bc.ExchangeVar(args[n]->type.stackOffset, newOffset);
  8150. args[n]->type.stackOffset = (short)newOffset;
  8151. args[n]->type.isTemporary = true;
  8152. args[n]->type.isVariable = true;
  8153. }
  8154. }
  8155. // If the function will return a value type on the stack, then we must allocate space
  8156. // for that here and push the address on the stack as a hidden argument to the function
  8157. asCScriptFunction *func = builder->GetFunctionDescription(funcId);
  8158. if( func->DoesReturnOnStack() )
  8159. {
  8160. asASSERT(!useVariable);
  8161. useVariable = true;
  8162. stackOffset = AllocateVariable(func->returnType, true);
  8163. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  8164. }
  8165. ctx->bc.AddCode(&objBC);
  8166. MoveArgsToStack(funcId, &ctx->bc, args, objectType ? true : false);
  8167. PerformFunctionCall(funcId, ctx, false, &args, 0, useVariable, stackOffset, funcPtrVar);
  8168. }
  8169. int asCCompiler::CompileOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8170. {
  8171. IsVariableInitialized(&lctx->type, node);
  8172. IsVariableInitialized(&rctx->type, node);
  8173. if( lctx->type.isExplicitHandle || rctx->type.isExplicitHandle ||
  8174. node->tokenType == ttIs || node->tokenType == ttNotIs )
  8175. {
  8176. CompileOperatorOnHandles(node, lctx, rctx, ctx);
  8177. return 0;
  8178. }
  8179. else
  8180. {
  8181. // Compile an overloaded operator for the two operands
  8182. if( CompileOverloadedDualOperator(node, lctx, rctx, ctx) )
  8183. return 0;
  8184. // If both operands are objects, then we shouldn't continue
  8185. if( lctx->type.dataType.IsObject() && rctx->type.dataType.IsObject() )
  8186. {
  8187. asCString str;
  8188. str.Format(TXT_NO_MATCHING_OP_FOUND_FOR_TYPES_s_AND_s, lctx->type.dataType.Format().AddressOf(), rctx->type.dataType.Format().AddressOf());
  8189. Error(str.AddressOf(), node);
  8190. ctx->type.SetDummy();
  8191. return -1;
  8192. }
  8193. // Process the property get accessors (if any)
  8194. ProcessPropertyGetAccessor(lctx, node);
  8195. ProcessPropertyGetAccessor(rctx, node);
  8196. // Make sure we have two variables or constants
  8197. if( lctx->type.dataType.IsReference() ) ConvertToVariableNotIn(lctx, rctx);
  8198. if( rctx->type.dataType.IsReference() ) ConvertToVariableNotIn(rctx, lctx);
  8199. // Make sure lctx doesn't end up with a variable used in rctx
  8200. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  8201. {
  8202. int offset = AllocateVariableNotIn(lctx->type.dataType, true, false, rctx);
  8203. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  8204. ReleaseTemporaryVariable(offset, 0);
  8205. }
  8206. // Math operators
  8207. // + - * / % += -= *= /= %=
  8208. int op = node->tokenType;
  8209. if( op == ttPlus || op == ttAddAssign ||
  8210. op == ttMinus || op == ttSubAssign ||
  8211. op == ttStar || op == ttMulAssign ||
  8212. op == ttSlash || op == ttDivAssign ||
  8213. op == ttPercent || op == ttModAssign )
  8214. {
  8215. CompileMathOperator(node, lctx, rctx, ctx);
  8216. return 0;
  8217. }
  8218. // Bitwise operators
  8219. // << >> >>> & | ^ <<= >>= >>>= &= |= ^=
  8220. if( op == ttAmp || op == ttAndAssign ||
  8221. op == ttBitOr || op == ttOrAssign ||
  8222. op == ttBitXor || op == ttXorAssign ||
  8223. op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  8224. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  8225. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8226. {
  8227. CompileBitwiseOperator(node, lctx, rctx, ctx);
  8228. return 0;
  8229. }
  8230. // Comparison operators
  8231. // == != < > <= >=
  8232. if( op == ttEqual || op == ttNotEqual ||
  8233. op == ttLessThan || op == ttLessThanOrEqual ||
  8234. op == ttGreaterThan || op == ttGreaterThanOrEqual )
  8235. {
  8236. CompileComparisonOperator(node, lctx, rctx, ctx);
  8237. return 0;
  8238. }
  8239. // Boolean operators
  8240. // && || ^^
  8241. if( op == ttAnd || op == ttOr || op == ttXor )
  8242. {
  8243. CompileBooleanOperator(node, lctx, rctx, ctx);
  8244. return 0;
  8245. }
  8246. }
  8247. asASSERT(false);
  8248. return -1;
  8249. }
  8250. void asCCompiler::ConvertToTempVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  8251. {
  8252. int l = int(reservedVariables.GetLength());
  8253. if( exclude ) exclude->bc.GetVarsUsed(reservedVariables);
  8254. ConvertToTempVariable(ctx);
  8255. reservedVariables.SetLength(l);
  8256. }
  8257. void asCCompiler::ConvertToTempVariable(asSExprContext *ctx)
  8258. {
  8259. // This is only used for primitive types and null handles
  8260. asASSERT( ctx->type.dataType.IsPrimitive() || ctx->type.dataType.IsNullHandle() );
  8261. ConvertToVariable(ctx);
  8262. if( !ctx->type.isTemporary )
  8263. {
  8264. if( ctx->type.dataType.IsPrimitive() )
  8265. {
  8266. // Copy the variable to a temporary variable
  8267. int offset = AllocateVariable(ctx->type.dataType, true);
  8268. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8269. ctx->bc.InstrW_W(asBC_CpyVtoV4, offset, ctx->type.stackOffset);
  8270. else
  8271. ctx->bc.InstrW_W(asBC_CpyVtoV8, offset, ctx->type.stackOffset);
  8272. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8273. }
  8274. else
  8275. {
  8276. // We should never get here
  8277. asASSERT(false);
  8278. }
  8279. }
  8280. }
  8281. void asCCompiler::ConvertToVariable(asSExprContext *ctx)
  8282. {
  8283. // We should never get here while the context is still an unprocessed property accessor
  8284. asASSERT(ctx->property_get == 0 && ctx->property_set == 0);
  8285. int offset;
  8286. if( !ctx->type.isVariable &&
  8287. (ctx->type.dataType.IsObjectHandle() ||
  8288. (ctx->type.dataType.IsObject() && ctx->type.dataType.SupportHandles())) )
  8289. {
  8290. offset = AllocateVariable(ctx->type.dataType, true);
  8291. if( ctx->type.IsNullConstant() )
  8292. {
  8293. if( ctx->bc.GetLastInstr() == asBC_PshNull )
  8294. ctx->bc.Instr(asBC_PopPtr); // Pop the null constant pushed onto the stack
  8295. ctx->bc.InstrSHORT(asBC_ClrVPtr, (short)offset);
  8296. }
  8297. else
  8298. {
  8299. // Copy the object handle to a variable
  8300. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  8301. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  8302. ctx->bc.Instr(asBC_PopPtr);
  8303. }
  8304. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  8305. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8306. ctx->type.dataType.MakeHandle(true);
  8307. }
  8308. else if( (!ctx->type.isVariable || ctx->type.dataType.IsReference()) &&
  8309. ctx->type.dataType.IsPrimitive() )
  8310. {
  8311. if( ctx->type.isConstant )
  8312. {
  8313. offset = AllocateVariable(ctx->type.dataType, true);
  8314. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  8315. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, ctx->type.byteValue);
  8316. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  8317. ctx->bc.InstrSHORT_W(asBC_SetV2, (short)offset, ctx->type.wordValue);
  8318. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  8319. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, ctx->type.dwordValue);
  8320. else
  8321. ctx->bc.InstrSHORT_QW(asBC_SetV8, (short)offset, ctx->type.qwordValue);
  8322. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8323. return;
  8324. }
  8325. else
  8326. {
  8327. asASSERT(ctx->type.dataType.IsPrimitive());
  8328. asASSERT(ctx->type.dataType.IsReference());
  8329. ctx->type.dataType.MakeReference(false);
  8330. offset = AllocateVariable(ctx->type.dataType, true);
  8331. // Read the value from the address in the register directly into the variable
  8332. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  8333. ctx->bc.InstrSHORT(asBC_RDR1, (short)offset);
  8334. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  8335. ctx->bc.InstrSHORT(asBC_RDR2, (short)offset);
  8336. else if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8337. ctx->bc.InstrSHORT(asBC_RDR4, (short)offset);
  8338. else
  8339. ctx->bc.InstrSHORT(asBC_RDR8, (short)offset);
  8340. }
  8341. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  8342. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8343. }
  8344. }
  8345. void asCCompiler::ConvertToVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  8346. {
  8347. int l = int(reservedVariables.GetLength());
  8348. if( exclude ) exclude->bc.GetVarsUsed(reservedVariables);
  8349. ConvertToVariable(ctx);
  8350. reservedVariables.SetLength(l);
  8351. }
  8352. void asCCompiler::CompileMathOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8353. {
  8354. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  8355. // Implicitly convert the operands to a number type
  8356. asCDataType to;
  8357. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  8358. to.SetTokenType(ttDouble);
  8359. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  8360. to.SetTokenType(ttFloat);
  8361. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8362. {
  8363. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() )
  8364. to.SetTokenType(ttInt64);
  8365. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8366. to.SetTokenType(ttUInt64);
  8367. }
  8368. else
  8369. {
  8370. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() ||
  8371. lctx->type.dataType.IsEnumType() || rctx->type.dataType.IsEnumType() )
  8372. to.SetTokenType(ttInt);
  8373. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8374. to.SetTokenType(ttUInt);
  8375. }
  8376. // If doing an operation with double constant and float variable, the constant should be converted to float
  8377. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  8378. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  8379. to.SetTokenType(ttFloat);
  8380. // Do the actual conversion
  8381. int l = int(reservedVariables.GetLength());
  8382. rctx->bc.GetVarsUsed(reservedVariables);
  8383. lctx->bc.GetVarsUsed(reservedVariables);
  8384. if( lctx->type.dataType.IsReference() )
  8385. ConvertToVariable(lctx);
  8386. if( rctx->type.dataType.IsReference() )
  8387. ConvertToVariable(rctx);
  8388. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  8389. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true);
  8390. reservedVariables.SetLength(l);
  8391. // Verify that the conversion was successful
  8392. if( !lctx->type.dataType.IsIntegerType() &&
  8393. !lctx->type.dataType.IsUnsignedType() &&
  8394. !lctx->type.dataType.IsFloatType() &&
  8395. !lctx->type.dataType.IsDoubleType() )
  8396. {
  8397. asCString str;
  8398. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, lctx->type.dataType.Format().AddressOf());
  8399. Error(str.AddressOf(), node);
  8400. ctx->type.SetDummy();
  8401. return;
  8402. }
  8403. if( !rctx->type.dataType.IsIntegerType() &&
  8404. !rctx->type.dataType.IsUnsignedType() &&
  8405. !rctx->type.dataType.IsFloatType() &&
  8406. !rctx->type.dataType.IsDoubleType() )
  8407. {
  8408. asCString str;
  8409. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, rctx->type.dataType.Format().AddressOf());
  8410. Error(str.AddressOf(), node);
  8411. ctx->type.SetDummy();
  8412. return;
  8413. }
  8414. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8415. // Verify if we are dividing with a constant zero
  8416. int op = node->tokenType;
  8417. if( rctx->type.isConstant && rctx->type.qwordValue == 0 &&
  8418. (op == ttSlash || op == ttDivAssign ||
  8419. op == ttPercent || op == ttModAssign) )
  8420. {
  8421. Error(TXT_DIVIDE_BY_ZERO, node);
  8422. }
  8423. if( !isConstant )
  8424. {
  8425. ConvertToVariableNotIn(lctx, rctx);
  8426. ConvertToVariableNotIn(rctx, lctx);
  8427. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8428. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8429. if( op == ttAddAssign || op == ttSubAssign ||
  8430. op == ttMulAssign || op == ttDivAssign ||
  8431. op == ttModAssign )
  8432. {
  8433. // Merge the operands in the different order so that they are evaluated correctly
  8434. MergeExprBytecode(ctx, rctx);
  8435. MergeExprBytecode(ctx, lctx);
  8436. }
  8437. else
  8438. {
  8439. MergeExprBytecode(ctx, lctx);
  8440. MergeExprBytecode(ctx, rctx);
  8441. }
  8442. ProcessDeferredParams(ctx);
  8443. asEBCInstr instruction = asBC_ADDi;
  8444. if( lctx->type.dataType.IsIntegerType() ||
  8445. lctx->type.dataType.IsUnsignedType() )
  8446. {
  8447. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8448. {
  8449. if( op == ttPlus || op == ttAddAssign )
  8450. instruction = asBC_ADDi;
  8451. else if( op == ttMinus || op == ttSubAssign )
  8452. instruction = asBC_SUBi;
  8453. else if( op == ttStar || op == ttMulAssign )
  8454. instruction = asBC_MULi;
  8455. else if( op == ttSlash || op == ttDivAssign )
  8456. {
  8457. if( lctx->type.dataType.IsIntegerType() )
  8458. instruction = asBC_DIVi;
  8459. else
  8460. instruction = asBC_DIVu;
  8461. }
  8462. else if( op == ttPercent || op == ttModAssign )
  8463. {
  8464. if( lctx->type.dataType.IsIntegerType() )
  8465. instruction = asBC_MODi;
  8466. else
  8467. instruction = asBC_MODu;
  8468. }
  8469. }
  8470. else
  8471. {
  8472. if( op == ttPlus || op == ttAddAssign )
  8473. instruction = asBC_ADDi64;
  8474. else if( op == ttMinus || op == ttSubAssign )
  8475. instruction = asBC_SUBi64;
  8476. else if( op == ttStar || op == ttMulAssign )
  8477. instruction = asBC_MULi64;
  8478. else if( op == ttSlash || op == ttDivAssign )
  8479. {
  8480. if( lctx->type.dataType.IsIntegerType() )
  8481. instruction = asBC_DIVi64;
  8482. else
  8483. instruction = asBC_DIVu64;
  8484. }
  8485. else if( op == ttPercent || op == ttModAssign )
  8486. {
  8487. if( lctx->type.dataType.IsIntegerType() )
  8488. instruction = asBC_MODi64;
  8489. else
  8490. instruction = asBC_MODu64;
  8491. }
  8492. }
  8493. }
  8494. else if( lctx->type.dataType.IsFloatType() )
  8495. {
  8496. if( op == ttPlus || op == ttAddAssign )
  8497. instruction = asBC_ADDf;
  8498. else if( op == ttMinus || op == ttSubAssign )
  8499. instruction = asBC_SUBf;
  8500. else if( op == ttStar || op == ttMulAssign )
  8501. instruction = asBC_MULf;
  8502. else if( op == ttSlash || op == ttDivAssign )
  8503. instruction = asBC_DIVf;
  8504. else if( op == ttPercent || op == ttModAssign )
  8505. instruction = asBC_MODf;
  8506. }
  8507. else if( lctx->type.dataType.IsDoubleType() )
  8508. {
  8509. if( op == ttPlus || op == ttAddAssign )
  8510. instruction = asBC_ADDd;
  8511. else if( op == ttMinus || op == ttSubAssign )
  8512. instruction = asBC_SUBd;
  8513. else if( op == ttStar || op == ttMulAssign )
  8514. instruction = asBC_MULd;
  8515. else if( op == ttSlash || op == ttDivAssign )
  8516. instruction = asBC_DIVd;
  8517. else if( op == ttPercent || op == ttModAssign )
  8518. instruction = asBC_MODd;
  8519. }
  8520. else
  8521. {
  8522. // Shouldn't be possible
  8523. asASSERT(false);
  8524. }
  8525. // Do the operation
  8526. int a = AllocateVariable(lctx->type.dataType, true);
  8527. int b = lctx->type.stackOffset;
  8528. int c = rctx->type.stackOffset;
  8529. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8530. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8531. }
  8532. else
  8533. {
  8534. // Both values are constants
  8535. if( lctx->type.dataType.IsIntegerType() ||
  8536. lctx->type.dataType.IsUnsignedType() )
  8537. {
  8538. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8539. {
  8540. int v = 0;
  8541. if( op == ttPlus )
  8542. v = lctx->type.intValue + rctx->type.intValue;
  8543. else if( op == ttMinus )
  8544. v = lctx->type.intValue - rctx->type.intValue;
  8545. else if( op == ttStar )
  8546. v = lctx->type.intValue * rctx->type.intValue;
  8547. else if( op == ttSlash )
  8548. {
  8549. if( rctx->type.intValue == 0 )
  8550. v = 0;
  8551. else
  8552. if( lctx->type.dataType.IsIntegerType() )
  8553. v = lctx->type.intValue / rctx->type.intValue;
  8554. else
  8555. v = lctx->type.dwordValue / rctx->type.dwordValue;
  8556. }
  8557. else if( op == ttPercent )
  8558. {
  8559. if( rctx->type.intValue == 0 )
  8560. v = 0;
  8561. else
  8562. if( lctx->type.dataType.IsIntegerType() )
  8563. v = lctx->type.intValue % rctx->type.intValue;
  8564. else
  8565. v = lctx->type.dwordValue % rctx->type.dwordValue;
  8566. }
  8567. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8568. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  8569. if( lctx->type.dataType.GetTokenType() == ttUInt && op == ttMinus && lctx->type.intValue < rctx->type.intValue )
  8570. ctx->type.dataType.SetTokenType(ttInt);
  8571. }
  8572. else
  8573. {
  8574. asQWORD v = 0;
  8575. if( op == ttPlus )
  8576. v = lctx->type.qwordValue + rctx->type.qwordValue;
  8577. else if( op == ttMinus )
  8578. v = lctx->type.qwordValue - rctx->type.qwordValue;
  8579. else if( op == ttStar )
  8580. v = lctx->type.qwordValue * rctx->type.qwordValue;
  8581. else if( op == ttSlash )
  8582. {
  8583. if( rctx->type.qwordValue == 0 )
  8584. v = 0;
  8585. else
  8586. if( lctx->type.dataType.IsIntegerType() )
  8587. v = asINT64(lctx->type.qwordValue) / asINT64(rctx->type.qwordValue);
  8588. else
  8589. v = lctx->type.qwordValue / rctx->type.qwordValue;
  8590. }
  8591. else if( op == ttPercent )
  8592. {
  8593. if( rctx->type.qwordValue == 0 )
  8594. v = 0;
  8595. else
  8596. if( lctx->type.dataType.IsIntegerType() )
  8597. v = asINT64(lctx->type.qwordValue) % asINT64(rctx->type.qwordValue);
  8598. else
  8599. v = lctx->type.qwordValue % rctx->type.qwordValue;
  8600. }
  8601. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8602. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  8603. if( lctx->type.dataType.GetTokenType() == ttUInt64 && op == ttMinus && lctx->type.qwordValue < rctx->type.qwordValue )
  8604. ctx->type.dataType.SetTokenType(ttInt64);
  8605. }
  8606. }
  8607. else if( lctx->type.dataType.IsFloatType() )
  8608. {
  8609. float v = 0.0f;
  8610. if( op == ttPlus )
  8611. v = lctx->type.floatValue + rctx->type.floatValue;
  8612. else if( op == ttMinus )
  8613. v = lctx->type.floatValue - rctx->type.floatValue;
  8614. else if( op == ttStar )
  8615. v = lctx->type.floatValue * rctx->type.floatValue;
  8616. else if( op == ttSlash )
  8617. {
  8618. if( rctx->type.floatValue == 0 )
  8619. v = 0;
  8620. else
  8621. v = lctx->type.floatValue / rctx->type.floatValue;
  8622. }
  8623. else if( op == ttPercent )
  8624. {
  8625. if( rctx->type.floatValue == 0 )
  8626. v = 0;
  8627. else
  8628. v = fmodf(lctx->type.floatValue, rctx->type.floatValue);
  8629. }
  8630. ctx->type.SetConstantF(lctx->type.dataType, v);
  8631. }
  8632. else if( lctx->type.dataType.IsDoubleType() )
  8633. {
  8634. double v = 0.0;
  8635. if( op == ttPlus )
  8636. v = lctx->type.doubleValue + rctx->type.doubleValue;
  8637. else if( op == ttMinus )
  8638. v = lctx->type.doubleValue - rctx->type.doubleValue;
  8639. else if( op == ttStar )
  8640. v = lctx->type.doubleValue * rctx->type.doubleValue;
  8641. else if( op == ttSlash )
  8642. {
  8643. if( rctx->type.doubleValue == 0 )
  8644. v = 0;
  8645. else
  8646. v = lctx->type.doubleValue / rctx->type.doubleValue;
  8647. }
  8648. else if( op == ttPercent )
  8649. {
  8650. if( rctx->type.doubleValue == 0 )
  8651. v = 0;
  8652. else
  8653. v = fmod(lctx->type.doubleValue, rctx->type.doubleValue);
  8654. }
  8655. ctx->type.SetConstantD(lctx->type.dataType, v);
  8656. }
  8657. else
  8658. {
  8659. // Shouldn't be possible
  8660. asASSERT(false);
  8661. }
  8662. }
  8663. }
  8664. void asCCompiler::CompileBitwiseOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8665. {
  8666. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  8667. int op = node->tokenType;
  8668. if( op == ttAmp || op == ttAndAssign ||
  8669. op == ttBitOr || op == ttOrAssign ||
  8670. op == ttBitXor || op == ttXorAssign )
  8671. {
  8672. // Convert left hand operand to integer if it's not already one
  8673. asCDataType to;
  8674. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 ||
  8675. rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8676. to.SetTokenType(ttUInt64);
  8677. else
  8678. to.SetTokenType(ttUInt);
  8679. // Do the actual conversion
  8680. int l = int(reservedVariables.GetLength());
  8681. rctx->bc.GetVarsUsed(reservedVariables);
  8682. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  8683. reservedVariables.SetLength(l);
  8684. // Verify that the conversion was successful
  8685. if( !lctx->type.dataType.IsUnsignedType() )
  8686. {
  8687. asCString str;
  8688. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8689. Error(str.AddressOf(), node);
  8690. }
  8691. // Convert right hand operand to same type as left hand operand
  8692. l = int(reservedVariables.GetLength());
  8693. lctx->bc.GetVarsUsed(reservedVariables);
  8694. ImplicitConversion(rctx, lctx->type.dataType, node, asIC_IMPLICIT_CONV, true);
  8695. reservedVariables.SetLength(l);
  8696. if( !rctx->type.dataType.IsEqualExceptRef(lctx->type.dataType) )
  8697. {
  8698. asCString str;
  8699. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  8700. Error(str.AddressOf(), node);
  8701. }
  8702. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8703. if( !isConstant )
  8704. {
  8705. ConvertToVariableNotIn(lctx, rctx);
  8706. ConvertToVariableNotIn(rctx, lctx);
  8707. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8708. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8709. if( op == ttAndAssign || op == ttOrAssign || op == ttXorAssign )
  8710. {
  8711. // Compound assignments execute the right hand value first
  8712. MergeExprBytecode(ctx, rctx);
  8713. MergeExprBytecode(ctx, lctx);
  8714. }
  8715. else
  8716. {
  8717. MergeExprBytecode(ctx, lctx);
  8718. MergeExprBytecode(ctx, rctx);
  8719. }
  8720. ProcessDeferredParams(ctx);
  8721. asEBCInstr instruction = asBC_BAND;
  8722. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8723. {
  8724. if( op == ttAmp || op == ttAndAssign )
  8725. instruction = asBC_BAND;
  8726. else if( op == ttBitOr || op == ttOrAssign )
  8727. instruction = asBC_BOR;
  8728. else if( op == ttBitXor || op == ttXorAssign )
  8729. instruction = asBC_BXOR;
  8730. }
  8731. else
  8732. {
  8733. if( op == ttAmp || op == ttAndAssign )
  8734. instruction = asBC_BAND64;
  8735. else if( op == ttBitOr || op == ttOrAssign )
  8736. instruction = asBC_BOR64;
  8737. else if( op == ttBitXor || op == ttXorAssign )
  8738. instruction = asBC_BXOR64;
  8739. }
  8740. // Do the operation
  8741. int a = AllocateVariable(lctx->type.dataType, true);
  8742. int b = lctx->type.stackOffset;
  8743. int c = rctx->type.stackOffset;
  8744. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8745. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8746. }
  8747. else
  8748. {
  8749. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8750. {
  8751. asQWORD v = 0;
  8752. if( op == ttAmp )
  8753. v = lctx->type.qwordValue & rctx->type.qwordValue;
  8754. else if( op == ttBitOr )
  8755. v = lctx->type.qwordValue | rctx->type.qwordValue;
  8756. else if( op == ttBitXor )
  8757. v = lctx->type.qwordValue ^ rctx->type.qwordValue;
  8758. // Remember the result
  8759. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8760. }
  8761. else
  8762. {
  8763. asDWORD v = 0;
  8764. if( op == ttAmp )
  8765. v = lctx->type.dwordValue & rctx->type.dwordValue;
  8766. else if( op == ttBitOr )
  8767. v = lctx->type.dwordValue | rctx->type.dwordValue;
  8768. else if( op == ttBitXor )
  8769. v = lctx->type.dwordValue ^ rctx->type.dwordValue;
  8770. // Remember the result
  8771. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8772. }
  8773. }
  8774. }
  8775. else if( op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  8776. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  8777. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8778. {
  8779. // Don't permit object to primitive conversion, since we don't know which integer type is the correct one
  8780. if( lctx->type.dataType.IsObject() )
  8781. {
  8782. asCString str;
  8783. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  8784. Error(str.AddressOf(), node);
  8785. // Set an integer value and allow the compiler to continue
  8786. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttInt, true), 0);
  8787. return;
  8788. }
  8789. // Convert left hand operand to integer if it's not already one
  8790. asCDataType to = lctx->type.dataType;
  8791. if( lctx->type.dataType.IsUnsignedType() &&
  8792. lctx->type.dataType.GetSizeInMemoryBytes() < 4 )
  8793. {
  8794. to = asCDataType::CreatePrimitive(ttUInt, false);
  8795. }
  8796. else if( !lctx->type.dataType.IsUnsignedType() )
  8797. {
  8798. asCDataType to;
  8799. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8800. to.SetTokenType(ttInt64);
  8801. else
  8802. to.SetTokenType(ttInt);
  8803. }
  8804. // Do the actual conversion
  8805. int l = int(reservedVariables.GetLength());
  8806. rctx->bc.GetVarsUsed(reservedVariables);
  8807. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  8808. reservedVariables.SetLength(l);
  8809. // Verify that the conversion was successful
  8810. if( lctx->type.dataType != to )
  8811. {
  8812. asCString str;
  8813. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8814. Error(str.AddressOf(), node);
  8815. }
  8816. // Right operand must be 32bit uint
  8817. l = int(reservedVariables.GetLength());
  8818. lctx->bc.GetVarsUsed(reservedVariables);
  8819. ImplicitConversion(rctx, asCDataType::CreatePrimitive(ttUInt, true), node, asIC_IMPLICIT_CONV, true);
  8820. reservedVariables.SetLength(l);
  8821. if( !rctx->type.dataType.IsUnsignedType() )
  8822. {
  8823. asCString str;
  8824. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "uint");
  8825. Error(str.AddressOf(), node);
  8826. }
  8827. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8828. if( !isConstant )
  8829. {
  8830. ConvertToVariableNotIn(lctx, rctx);
  8831. ConvertToVariableNotIn(rctx, lctx);
  8832. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8833. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8834. if( op == ttShiftLeftAssign || op == ttShiftRightLAssign || op == ttShiftRightAAssign )
  8835. {
  8836. // Compound assignments execute the right hand value first
  8837. MergeExprBytecode(ctx, rctx);
  8838. MergeExprBytecode(ctx, lctx);
  8839. }
  8840. else
  8841. {
  8842. MergeExprBytecode(ctx, lctx);
  8843. MergeExprBytecode(ctx, rctx);
  8844. }
  8845. ProcessDeferredParams(ctx);
  8846. asEBCInstr instruction = asBC_BSLL;
  8847. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8848. {
  8849. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  8850. instruction = asBC_BSLL;
  8851. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  8852. instruction = asBC_BSRL;
  8853. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8854. instruction = asBC_BSRA;
  8855. }
  8856. else
  8857. {
  8858. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  8859. instruction = asBC_BSLL64;
  8860. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  8861. instruction = asBC_BSRL64;
  8862. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8863. instruction = asBC_BSRA64;
  8864. }
  8865. // Do the operation
  8866. int a = AllocateVariable(lctx->type.dataType, true);
  8867. int b = lctx->type.stackOffset;
  8868. int c = rctx->type.stackOffset;
  8869. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8870. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8871. }
  8872. else
  8873. {
  8874. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8875. {
  8876. asDWORD v = 0;
  8877. if( op == ttBitShiftLeft )
  8878. v = lctx->type.dwordValue << rctx->type.dwordValue;
  8879. else if( op == ttBitShiftRight )
  8880. v = lctx->type.dwordValue >> rctx->type.dwordValue;
  8881. else if( op == ttBitShiftRightArith )
  8882. v = lctx->type.intValue >> rctx->type.dwordValue;
  8883. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8884. }
  8885. else
  8886. {
  8887. asQWORD v = 0;
  8888. if( op == ttBitShiftLeft )
  8889. v = lctx->type.qwordValue << rctx->type.dwordValue;
  8890. else if( op == ttBitShiftRight )
  8891. v = lctx->type.qwordValue >> rctx->type.dwordValue;
  8892. else if( op == ttBitShiftRightArith )
  8893. v = asINT64(lctx->type.qwordValue) >> rctx->type.dwordValue;
  8894. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8895. }
  8896. }
  8897. }
  8898. }
  8899. void asCCompiler::CompileComparisonOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8900. {
  8901. // Both operands must be of the same type
  8902. // Implicitly convert the operands to a number type
  8903. asCDataType to;
  8904. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  8905. to.SetTokenType(ttDouble);
  8906. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  8907. to.SetTokenType(ttFloat);
  8908. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8909. {
  8910. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() )
  8911. to.SetTokenType(ttInt64);
  8912. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8913. to.SetTokenType(ttUInt64);
  8914. }
  8915. else
  8916. {
  8917. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() ||
  8918. lctx->type.dataType.IsEnumType() || rctx->type.dataType.IsEnumType() )
  8919. to.SetTokenType(ttInt);
  8920. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8921. to.SetTokenType(ttUInt);
  8922. else if( lctx->type.dataType.IsBooleanType() || rctx->type.dataType.IsBooleanType() )
  8923. to.SetTokenType(ttBool);
  8924. }
  8925. // If doing an operation with double constant and float variable, the constant should be converted to float
  8926. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  8927. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  8928. to.SetTokenType(ttFloat);
  8929. // Is it an operation on signed values?
  8930. bool signMismatch = false;
  8931. if( !lctx->type.dataType.IsUnsignedType() || !rctx->type.dataType.IsUnsignedType() )
  8932. {
  8933. if( lctx->type.dataType.GetTokenType() == ttUInt64 )
  8934. {
  8935. if( !lctx->type.isConstant )
  8936. signMismatch = true;
  8937. else if( lctx->type.qwordValue & (asQWORD(1)<<63) )
  8938. signMismatch = true;
  8939. }
  8940. if( lctx->type.dataType.GetTokenType() == ttUInt )
  8941. {
  8942. if( !lctx->type.isConstant )
  8943. signMismatch = true;
  8944. else if( lctx->type.dwordValue & (asDWORD(1)<<31) )
  8945. signMismatch = true;
  8946. }
  8947. if( rctx->type.dataType.GetTokenType() == ttUInt64 )
  8948. {
  8949. if( !rctx->type.isConstant )
  8950. signMismatch = true;
  8951. else if( rctx->type.qwordValue & (asQWORD(1)<<63) )
  8952. signMismatch = true;
  8953. }
  8954. if( rctx->type.dataType.GetTokenType() == ttUInt )
  8955. {
  8956. if( !rctx->type.isConstant )
  8957. signMismatch = true;
  8958. else if( rctx->type.dwordValue & (asDWORD(1)<<31) )
  8959. signMismatch = true;
  8960. }
  8961. }
  8962. // Check for signed/unsigned mismatch
  8963. if( signMismatch )
  8964. Warning(TXT_SIGNED_UNSIGNED_MISMATCH, node);
  8965. // Do the actual conversion
  8966. int l = int(reservedVariables.GetLength());
  8967. rctx->bc.GetVarsUsed(reservedVariables);
  8968. if( lctx->type.dataType.IsReference() )
  8969. ConvertToVariable(lctx);
  8970. if( rctx->type.dataType.IsReference() )
  8971. ConvertToVariable(rctx);
  8972. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  8973. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  8974. reservedVariables.SetLength(l);
  8975. // Verify that the conversion was successful
  8976. bool ok = true;
  8977. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  8978. {
  8979. asCString str;
  8980. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8981. Error(str.AddressOf(), node);
  8982. ok = false;
  8983. }
  8984. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  8985. {
  8986. asCString str;
  8987. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8988. Error(str.AddressOf(), node);
  8989. ok = false;
  8990. }
  8991. if( !ok )
  8992. {
  8993. // It wasn't possible to get two valid operands, so we just return
  8994. // a boolean result and let the compiler continue.
  8995. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  8996. return;
  8997. }
  8998. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8999. int op = node->tokenType;
  9000. if( !isConstant )
  9001. {
  9002. if( to.IsBooleanType() )
  9003. {
  9004. int op = node->tokenType;
  9005. if( op == ttEqual || op == ttNotEqual )
  9006. {
  9007. // Must convert to temporary variable, because we are changing the value before comparison
  9008. ConvertToTempVariableNotIn(lctx, rctx);
  9009. ConvertToTempVariableNotIn(rctx, lctx);
  9010. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9011. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9012. // Make sure they are equal if not false
  9013. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  9014. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  9015. MergeExprBytecode(ctx, lctx);
  9016. MergeExprBytecode(ctx, rctx);
  9017. ProcessDeferredParams(ctx);
  9018. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  9019. int b = lctx->type.stackOffset;
  9020. int c = rctx->type.stackOffset;
  9021. if( op == ttEqual )
  9022. {
  9023. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  9024. ctx->bc.Instr(asBC_TZ);
  9025. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9026. }
  9027. else if( op == ttNotEqual )
  9028. {
  9029. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  9030. ctx->bc.Instr(asBC_TNZ);
  9031. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9032. }
  9033. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9034. }
  9035. else
  9036. {
  9037. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  9038. Error(TXT_ILLEGAL_OPERATION, node);
  9039. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 0);
  9040. }
  9041. }
  9042. else
  9043. {
  9044. ConvertToVariableNotIn(lctx, rctx);
  9045. ConvertToVariableNotIn(rctx, lctx);
  9046. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9047. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9048. MergeExprBytecode(ctx, lctx);
  9049. MergeExprBytecode(ctx, rctx);
  9050. ProcessDeferredParams(ctx);
  9051. asEBCInstr iCmp = asBC_CMPi, iT = asBC_TZ;
  9052. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9053. iCmp = asBC_CMPi;
  9054. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9055. iCmp = asBC_CMPu;
  9056. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9057. iCmp = asBC_CMPi64;
  9058. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9059. iCmp = asBC_CMPu64;
  9060. else if( lctx->type.dataType.IsFloatType() )
  9061. iCmp = asBC_CMPf;
  9062. else if( lctx->type.dataType.IsDoubleType() )
  9063. iCmp = asBC_CMPd;
  9064. else
  9065. asASSERT(false);
  9066. if( op == ttEqual )
  9067. iT = asBC_TZ;
  9068. else if( op == ttNotEqual )
  9069. iT = asBC_TNZ;
  9070. else if( op == ttLessThan )
  9071. iT = asBC_TS;
  9072. else if( op == ttLessThanOrEqual )
  9073. iT = asBC_TNP;
  9074. else if( op == ttGreaterThan )
  9075. iT = asBC_TP;
  9076. else if( op == ttGreaterThanOrEqual )
  9077. iT = asBC_TNS;
  9078. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  9079. int b = lctx->type.stackOffset;
  9080. int c = rctx->type.stackOffset;
  9081. ctx->bc.InstrW_W(iCmp, b, c);
  9082. ctx->bc.Instr(iT);
  9083. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9084. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9085. }
  9086. }
  9087. else
  9088. {
  9089. if( to.IsBooleanType() )
  9090. {
  9091. int op = node->tokenType;
  9092. if( op == ttEqual || op == ttNotEqual )
  9093. {
  9094. // Make sure they are equal if not false
  9095. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9096. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9097. asDWORD v = 0;
  9098. if( op == ttEqual )
  9099. {
  9100. v = lctx->type.intValue - rctx->type.intValue;
  9101. if( v == 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9102. }
  9103. else if( op == ttNotEqual )
  9104. {
  9105. v = lctx->type.intValue - rctx->type.intValue;
  9106. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9107. }
  9108. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), v);
  9109. }
  9110. else
  9111. {
  9112. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  9113. Error(TXT_ILLEGAL_OPERATION, node);
  9114. }
  9115. }
  9116. else
  9117. {
  9118. int i = 0;
  9119. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9120. {
  9121. int v = lctx->type.intValue - rctx->type.intValue;
  9122. if( v < 0 ) i = -1;
  9123. if( v > 0 ) i = 1;
  9124. }
  9125. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9126. {
  9127. asDWORD v1 = lctx->type.dwordValue;
  9128. asDWORD v2 = rctx->type.dwordValue;
  9129. if( v1 < v2 ) i = -1;
  9130. if( v1 > v2 ) i = 1;
  9131. }
  9132. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9133. {
  9134. asINT64 v = asINT64(lctx->type.qwordValue) - asINT64(rctx->type.qwordValue);
  9135. if( v < 0 ) i = -1;
  9136. if( v > 0 ) i = 1;
  9137. }
  9138. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9139. {
  9140. asQWORD v1 = lctx->type.qwordValue;
  9141. asQWORD v2 = rctx->type.qwordValue;
  9142. if( v1 < v2 ) i = -1;
  9143. if( v1 > v2 ) i = 1;
  9144. }
  9145. else if( lctx->type.dataType.IsFloatType() )
  9146. {
  9147. float v = lctx->type.floatValue - rctx->type.floatValue;
  9148. if( v < 0 ) i = -1;
  9149. if( v > 0 ) i = 1;
  9150. }
  9151. else if( lctx->type.dataType.IsDoubleType() )
  9152. {
  9153. double v = lctx->type.doubleValue - rctx->type.doubleValue;
  9154. if( v < 0 ) i = -1;
  9155. if( v > 0 ) i = 1;
  9156. }
  9157. if( op == ttEqual )
  9158. i = (i == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9159. else if( op == ttNotEqual )
  9160. i = (i != 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9161. else if( op == ttLessThan )
  9162. i = (i < 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9163. else if( op == ttLessThanOrEqual )
  9164. i = (i <= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9165. else if( op == ttGreaterThan )
  9166. i = (i > 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9167. else if( op == ttGreaterThanOrEqual )
  9168. i = (i >= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9169. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), i);
  9170. }
  9171. }
  9172. }
  9173. void asCCompiler::PushVariableOnStack(asSExprContext *ctx, bool asReference)
  9174. {
  9175. // Put the result on the stack
  9176. if( asReference )
  9177. {
  9178. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  9179. ctx->type.dataType.MakeReference(true);
  9180. }
  9181. else
  9182. {
  9183. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9184. ctx->bc.InstrSHORT(asBC_PshV4, ctx->type.stackOffset);
  9185. else
  9186. ctx->bc.InstrSHORT(asBC_PshV8, ctx->type.stackOffset);
  9187. }
  9188. }
  9189. void asCCompiler::CompileBooleanOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9190. {
  9191. // Both operands must be booleans
  9192. asCDataType to;
  9193. to.SetTokenType(ttBool);
  9194. // Do the actual conversion
  9195. int l = int(reservedVariables.GetLength());
  9196. rctx->bc.GetVarsUsed(reservedVariables);
  9197. lctx->bc.GetVarsUsed(reservedVariables);
  9198. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  9199. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  9200. reservedVariables.SetLength(l);
  9201. // Verify that the conversion was successful
  9202. if( !lctx->type.dataType.IsBooleanType() )
  9203. {
  9204. asCString str;
  9205. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), "bool");
  9206. Error(str.AddressOf(), node);
  9207. // Force the conversion to allow compilation to proceed
  9208. lctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  9209. }
  9210. if( !rctx->type.dataType.IsBooleanType() )
  9211. {
  9212. asCString str;
  9213. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "bool");
  9214. Error(str.AddressOf(), node);
  9215. // Force the conversion to allow compilation to proceed
  9216. rctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  9217. }
  9218. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  9219. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  9220. // What kind of operator is it?
  9221. int op = node->tokenType;
  9222. if( op == ttXor )
  9223. {
  9224. if( !isConstant )
  9225. {
  9226. // Must convert to temporary variable, because we are changing the value before comparison
  9227. ConvertToTempVariableNotIn(lctx, rctx);
  9228. ConvertToTempVariableNotIn(rctx, lctx);
  9229. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9230. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9231. // Make sure they are equal if not false
  9232. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  9233. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  9234. MergeExprBytecode(ctx, lctx);
  9235. MergeExprBytecode(ctx, rctx);
  9236. ProcessDeferredParams(ctx);
  9237. int a = AllocateVariable(ctx->type.dataType, true);
  9238. int b = lctx->type.stackOffset;
  9239. int c = rctx->type.stackOffset;
  9240. ctx->bc.InstrW_W_W(asBC_BXOR,a,b,c);
  9241. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9242. }
  9243. else
  9244. {
  9245. // Make sure they are equal if not false
  9246. #if AS_SIZEOF_BOOL == 1
  9247. if( lctx->type.byteValue != 0 ) lctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  9248. if( rctx->type.byteValue != 0 ) rctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  9249. asBYTE v = 0;
  9250. v = lctx->type.byteValue - rctx->type.byteValue;
  9251. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9252. ctx->type.isConstant = true;
  9253. ctx->type.byteValue = v;
  9254. #else
  9255. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9256. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9257. asDWORD v = 0;
  9258. v = lctx->type.intValue - rctx->type.intValue;
  9259. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9260. ctx->type.isConstant = true;
  9261. ctx->type.dwordValue = v;
  9262. #endif
  9263. }
  9264. }
  9265. else if( op == ttAnd ||
  9266. op == ttOr )
  9267. {
  9268. if( !isConstant )
  9269. {
  9270. // If or-operator and first value is 1 the second value shouldn't be calculated
  9271. // if and-operator and first value is 0 the second value shouldn't be calculated
  9272. ConvertToVariable(lctx);
  9273. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9274. MergeExprBytecode(ctx, lctx);
  9275. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  9276. int label1 = nextLabel++;
  9277. int label2 = nextLabel++;
  9278. if( op == ttAnd )
  9279. {
  9280. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  9281. ctx->bc.Instr(asBC_ClrHi);
  9282. ctx->bc.InstrDWORD(asBC_JNZ, label1);
  9283. ctx->bc.InstrW_DW(asBC_SetV4, (asWORD)offset, 0);
  9284. ctx->bc.InstrINT(asBC_JMP, label2);
  9285. }
  9286. else if( op == ttOr )
  9287. {
  9288. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  9289. ctx->bc.Instr(asBC_ClrHi);
  9290. ctx->bc.InstrDWORD(asBC_JZ, label1);
  9291. #if AS_SIZEOF_BOOL == 1
  9292. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  9293. #else
  9294. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  9295. #endif
  9296. ctx->bc.InstrINT(asBC_JMP, label2);
  9297. }
  9298. ctx->bc.Label((short)label1);
  9299. ConvertToVariable(rctx);
  9300. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9301. rctx->bc.InstrW_W(asBC_CpyVtoV4, offset, rctx->type.stackOffset);
  9302. MergeExprBytecode(ctx, rctx);
  9303. ctx->bc.Label((short)label2);
  9304. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), offset, true);
  9305. }
  9306. else
  9307. {
  9308. #if AS_SIZEOF_BOOL == 1
  9309. asBYTE v = 0;
  9310. if( op == ttAnd )
  9311. v = lctx->type.byteValue && rctx->type.byteValue;
  9312. else if( op == ttOr )
  9313. v = lctx->type.byteValue || rctx->type.byteValue;
  9314. // Remember the result
  9315. ctx->type.isConstant = true;
  9316. ctx->type.byteValue = v;
  9317. #else
  9318. asDWORD v = 0;
  9319. if( op == ttAnd )
  9320. v = lctx->type.dwordValue && rctx->type.dwordValue;
  9321. else if( op == ttOr )
  9322. v = lctx->type.dwordValue || rctx->type.dwordValue;
  9323. // Remember the result
  9324. ctx->type.isConstant = true;
  9325. ctx->type.dwordValue = v;
  9326. #endif
  9327. }
  9328. }
  9329. }
  9330. void asCCompiler::CompileOperatorOnHandles(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9331. {
  9332. // Process the property accessor as get
  9333. ProcessPropertyGetAccessor(lctx, node);
  9334. ProcessPropertyGetAccessor(rctx, node);
  9335. // Make sure lctx doesn't end up with a variable used in rctx
  9336. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  9337. {
  9338. asCArray<int> vars;
  9339. rctx->bc.GetVarsUsed(vars);
  9340. int offset = AllocateVariable(lctx->type.dataType, true);
  9341. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  9342. ReleaseTemporaryVariable(offset, 0);
  9343. }
  9344. // Warn if not both operands are explicit handles
  9345. if( (node->tokenType == ttEqual || node->tokenType == ttNotEqual) &&
  9346. ((!lctx->type.isExplicitHandle && !(lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE))) ||
  9347. (!rctx->type.isExplicitHandle && !(rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE)))) )
  9348. {
  9349. Warning(TXT_HANDLE_COMPARISON, node);
  9350. }
  9351. // If one of the operands is a value type used as handle, we should look for the opEquals method
  9352. if( ((lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) ||
  9353. (rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE))) &&
  9354. (node->tokenType == ttEqual || node->tokenType == ttIs ||
  9355. node->tokenType == ttNotEqual || node->tokenType == ttNotIs) )
  9356. {
  9357. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  9358. // Find the matching opEquals method
  9359. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  9360. if( r == 0 )
  9361. {
  9362. // Try again by switching the order of the operands
  9363. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  9364. }
  9365. if( r == 1 )
  9366. {
  9367. if( node->tokenType == ttNotEqual || node->tokenType == ttNotIs )
  9368. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  9369. // Success, don't continue
  9370. return;
  9371. }
  9372. else if( r == 0 )
  9373. {
  9374. // Couldn't find opEquals method
  9375. Error(TXT_NO_APPROPRIATE_OPEQUALS, node);
  9376. }
  9377. // Compiler error, don't continue
  9378. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  9379. return;
  9380. }
  9381. // Implicitly convert null to the other type
  9382. asCDataType to;
  9383. if( lctx->type.IsNullConstant() )
  9384. to = rctx->type.dataType;
  9385. else if( rctx->type.IsNullConstant() )
  9386. to = lctx->type.dataType;
  9387. else
  9388. {
  9389. // TODO: Use the common base type
  9390. to = lctx->type.dataType;
  9391. }
  9392. // Need to pop the value if it is a null constant
  9393. if( lctx->type.IsNullConstant() )
  9394. lctx->bc.Instr(asBC_PopPtr);
  9395. if( rctx->type.IsNullConstant() )
  9396. rctx->bc.Instr(asBC_PopPtr);
  9397. // Convert both sides to explicit handles
  9398. to.MakeHandle(true);
  9399. to.MakeReference(false);
  9400. // Do the conversion
  9401. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  9402. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  9403. // Both operands must be of the same type
  9404. // Verify that the conversion was successful
  9405. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  9406. {
  9407. asCString str;
  9408. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9409. Error(str.AddressOf(), node);
  9410. }
  9411. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  9412. {
  9413. asCString str;
  9414. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9415. Error(str.AddressOf(), node);
  9416. }
  9417. // Make sure it really is handles that are being compared
  9418. if( !lctx->type.dataType.IsObjectHandle() )
  9419. {
  9420. Error(TXT_OPERANDS_MUST_BE_HANDLES, node);
  9421. }
  9422. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  9423. int op = node->tokenType;
  9424. if( op == ttEqual || op == ttNotEqual || op == ttIs || op == ttNotIs )
  9425. {
  9426. // If the object handle already is in a variable we must manually pop it from the stack
  9427. if( lctx->type.isVariable )
  9428. lctx->bc.Instr(asBC_PopPtr);
  9429. if( rctx->type.isVariable )
  9430. rctx->bc.Instr(asBC_PopPtr);
  9431. // TODO: runtime optimize: don't do REFCPY
  9432. ConvertToVariableNotIn(lctx, rctx);
  9433. ConvertToVariable(rctx);
  9434. MergeExprBytecode(ctx, lctx);
  9435. MergeExprBytecode(ctx, rctx);
  9436. int a = AllocateVariable(ctx->type.dataType, true);
  9437. int b = lctx->type.stackOffset;
  9438. int c = rctx->type.stackOffset;
  9439. ctx->bc.InstrW_W(asBC_CmpPtr, b, c);
  9440. if( op == ttEqual || op == ttIs )
  9441. ctx->bc.Instr(asBC_TZ);
  9442. else if( op == ttNotEqual || op == ttNotIs )
  9443. ctx->bc.Instr(asBC_TNZ);
  9444. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9445. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9446. ReleaseTemporaryVariable(lctx->type, &ctx->bc);
  9447. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  9448. ProcessDeferredParams(ctx);
  9449. }
  9450. else
  9451. {
  9452. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  9453. Error(TXT_ILLEGAL_OPERATION, node);
  9454. }
  9455. }
  9456. void asCCompiler::PerformFunctionCall(int funcId, asSExprContext *ctx, bool isConstructor, asCArray<asSExprContext*> *args, asCObjectType *objType, bool useVariable, int varOffset, int funcPtrVar)
  9457. {
  9458. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  9459. // A shared object may not call non-shared functions
  9460. if( outFunc->IsShared() && !descr->IsShared() )
  9461. {
  9462. asCString msg;
  9463. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, descr->GetDeclarationStr().AddressOf());
  9464. Error(msg.AddressOf(), ctx->exprNode);
  9465. }
  9466. // Check if the function is private
  9467. if( descr->isPrivate && descr->GetObjectType() != outFunc->GetObjectType() )
  9468. {
  9469. asCString msg;
  9470. msg.Format(TXT_PRIVATE_METHOD_CALL_s, descr->GetDeclarationStr().AddressOf());
  9471. Error(msg.AddressOf(), ctx->exprNode);
  9472. }
  9473. int argSize = descr->GetSpaceNeededForArguments();
  9474. if( descr->objectType && descr->returnType.IsReference() &&
  9475. !ctx->type.isVariable && (ctx->type.dataType.IsObjectHandle() || ctx->type.dataType.SupportHandles()) &&
  9476. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_SCOPED) &&
  9477. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_ASHANDLE) )
  9478. {
  9479. // The class method we're calling is returning a reference, which may be to a member of the object.
  9480. // In order to guarantee the lifetime of the reference, we must hold a local reference to the object.
  9481. // TODO: runtime optimize: This can be avoided for local variables (non-handles) as they have a well defined life time
  9482. int tempRef = AllocateVariable(ctx->type.dataType, true);
  9483. ctx->bc.InstrSHORT(asBC_PSF, (short)tempRef);
  9484. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  9485. // Add the release of this reference, as a deferred expression
  9486. asSDeferredParam deferred;
  9487. deferred.origExpr = 0;
  9488. deferred.argInOutFlags = asTM_INREF;
  9489. deferred.argNode = 0;
  9490. deferred.argType.SetVariable(ctx->type.dataType, tempRef, true);
  9491. ctx->deferredParams.PushLast(deferred);
  9492. // Forget the current type
  9493. ctx->type.SetDummy();
  9494. }
  9495. if( isConstructor )
  9496. {
  9497. // Sometimes the value types are allocated on the heap,
  9498. // which is when this way of constructing them is used.
  9499. asASSERT(useVariable == false);
  9500. ctx->bc.Alloc(asBC_ALLOC, objType, descr->id, argSize+AS_PTR_SIZE);
  9501. // The instruction has already moved the returned object to the variable
  9502. ctx->type.Set(asCDataType::CreatePrimitive(ttVoid, false));
  9503. ctx->type.isLValue = false;
  9504. // Clean up arguments
  9505. if( args )
  9506. AfterFunctionCall(funcId, *args, ctx, false);
  9507. ProcessDeferredParams(ctx);
  9508. return;
  9509. }
  9510. else
  9511. {
  9512. if( descr->objectType )
  9513. argSize += AS_PTR_SIZE;
  9514. // If the function returns an object by value the address of the location
  9515. // where the value should be stored is passed as an argument too
  9516. if( descr->DoesReturnOnStack() )
  9517. {
  9518. argSize += AS_PTR_SIZE;
  9519. }
  9520. // TODO: runtime optimize: If it is known that a class method cannot be overridden the call
  9521. // should be made with asBC_CALL as it is faster. Examples where this
  9522. // is known is for example finalled methods where the class doesn't derive
  9523. // from any other, or even non-finalled methods but where it is known
  9524. // at compile time the true type of the object. The first should be
  9525. // quite easy to determine, but the latter will be quite complex and possibly
  9526. // not worth it.
  9527. if( descr->funcType == asFUNC_IMPORTED )
  9528. ctx->bc.Call(asBC_CALLBND , descr->id, argSize);
  9529. // TODO: Maybe we need two different byte codes
  9530. else if( descr->funcType == asFUNC_INTERFACE || descr->funcType == asFUNC_VIRTUAL )
  9531. ctx->bc.Call(asBC_CALLINTF, descr->id, argSize);
  9532. else if( descr->funcType == asFUNC_SCRIPT )
  9533. ctx->bc.Call(asBC_CALL , descr->id, argSize);
  9534. else if( descr->funcType == asFUNC_SYSTEM )
  9535. ctx->bc.Call(asBC_CALLSYS , descr->id, argSize);
  9536. else if( descr->funcType == asFUNC_FUNCDEF )
  9537. ctx->bc.CallPtr(asBC_CallPtr, funcPtrVar, argSize);
  9538. }
  9539. if( descr->returnType.IsObject() && !descr->returnType.IsReference() )
  9540. {
  9541. int returnOffset = 0;
  9542. if( descr->DoesReturnOnStack() )
  9543. {
  9544. asASSERT( useVariable );
  9545. // The variable was allocated before the function was called
  9546. returnOffset = varOffset;
  9547. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  9548. // The variable was initialized by the function, so we need to mark it as initialized here
  9549. ctx->bc.ObjInfo(varOffset, asOBJ_INIT);
  9550. }
  9551. else
  9552. {
  9553. if( useVariable )
  9554. {
  9555. // Use the given variable
  9556. returnOffset = varOffset;
  9557. ctx->type.SetVariable(descr->returnType, returnOffset, false);
  9558. }
  9559. else
  9560. {
  9561. // Allocate a temporary variable for the returned object
  9562. // The returned object will actually be allocated on the heap, so
  9563. // we must force the allocation of the variable to do the same
  9564. returnOffset = AllocateVariable(descr->returnType, true, true);
  9565. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  9566. }
  9567. // Move the pointer from the object register to the temporary variable
  9568. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  9569. }
  9570. ctx->type.dataType.MakeReference(IsVariableOnHeap(returnOffset));
  9571. ctx->type.isLValue = false; // It is a reference, but not an lvalue
  9572. // Clean up arguments
  9573. if( args )
  9574. AfterFunctionCall(funcId, *args, ctx, false);
  9575. ProcessDeferredParams(ctx);
  9576. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  9577. }
  9578. else if( descr->returnType.IsReference() )
  9579. {
  9580. asASSERT(useVariable == false);
  9581. // We cannot clean up the arguments yet, because the
  9582. // reference might be pointing to one of them.
  9583. if( args )
  9584. AfterFunctionCall(funcId, *args, ctx, true);
  9585. // Do not process the output parameters yet, because it
  9586. // might invalidate the returned reference
  9587. // If the context holds a variable that needs cleanup
  9588. // store it as a deferred parameter so it will be cleaned up
  9589. // afterwards.
  9590. if( ctx->type.isTemporary )
  9591. {
  9592. asSDeferredParam defer;
  9593. defer.argNode = 0;
  9594. defer.argType = ctx->type;
  9595. defer.argInOutFlags = asTM_INOUTREF;
  9596. defer.origExpr = 0;
  9597. ctx->deferredParams.PushLast(defer);
  9598. }
  9599. ctx->type.Set(descr->returnType);
  9600. if( !descr->returnType.IsPrimitive() )
  9601. {
  9602. ctx->bc.Instr(asBC_PshRPtr);
  9603. if( descr->returnType.IsObject() &&
  9604. !descr->returnType.IsObjectHandle() )
  9605. {
  9606. // We are getting the pointer to the object
  9607. // not a pointer to a object variable
  9608. ctx->type.dataType.MakeReference(false);
  9609. }
  9610. }
  9611. // A returned reference can be used as lvalue
  9612. ctx->type.isLValue = true;
  9613. }
  9614. else
  9615. {
  9616. asASSERT(useVariable == false);
  9617. if( descr->returnType.GetSizeInMemoryBytes() )
  9618. {
  9619. // Allocate a temporary variable to hold the value, but make sure
  9620. // the temporary variable isn't used in any of the deferred arguments
  9621. int l = int(reservedVariables.GetLength());
  9622. for( asUINT n = 0; args && n < args->GetLength(); n++ )
  9623. {
  9624. asSExprContext *expr = (*args)[n]->origExpr;
  9625. if( expr )
  9626. expr->bc.GetVarsUsed(reservedVariables);
  9627. }
  9628. int offset = AllocateVariable(descr->returnType, true);
  9629. reservedVariables.SetLength(l);
  9630. ctx->type.SetVariable(descr->returnType, offset, true);
  9631. // Move the value from the return register to the variable
  9632. if( descr->returnType.GetSizeOnStackDWords() == 1 )
  9633. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)offset);
  9634. else if( descr->returnType.GetSizeOnStackDWords() == 2 )
  9635. ctx->bc.InstrSHORT(asBC_CpyRtoV8, (short)offset);
  9636. }
  9637. else
  9638. ctx->type.Set(descr->returnType);
  9639. ctx->type.isLValue = false;
  9640. // Clean up arguments
  9641. if( args )
  9642. AfterFunctionCall(funcId, *args, ctx, false);
  9643. ProcessDeferredParams(ctx);
  9644. }
  9645. }
  9646. // This only merges the bytecode, but doesn't modify the type of the final context
  9647. void asCCompiler::MergeExprBytecode(asSExprContext *before, asSExprContext *after)
  9648. {
  9649. before->bc.AddCode(&after->bc);
  9650. for( asUINT n = 0; n < after->deferredParams.GetLength(); n++ )
  9651. {
  9652. before->deferredParams.PushLast(after->deferredParams[n]);
  9653. after->deferredParams[n].origExpr = 0;
  9654. }
  9655. after->deferredParams.SetLength(0);
  9656. }
  9657. // This merges both bytecode and the type of the final context
  9658. void asCCompiler::MergeExprBytecodeAndType(asSExprContext *before, asSExprContext *after)
  9659. {
  9660. MergeExprBytecode(before, after);
  9661. before->type = after->type;
  9662. before->property_get = after->property_get;
  9663. before->property_set = after->property_set;
  9664. before->property_const = after->property_const;
  9665. before->property_handle = after->property_handle;
  9666. before->property_ref = after->property_ref;
  9667. before->property_arg = after->property_arg;
  9668. before->exprNode = after->exprNode;
  9669. after->property_arg = 0;
  9670. // Do not copy the origExpr member
  9671. }
  9672. void asCCompiler::FilterConst(asCArray<int> &funcs, bool removeConst)
  9673. {
  9674. if( funcs.GetLength() == 0 ) return;
  9675. // This is only done for object methods
  9676. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[0]);
  9677. if( desc->objectType == 0 ) return;
  9678. // Check if there are any non-const matches
  9679. asUINT n;
  9680. bool foundNonConst = false;
  9681. for( n = 0; n < funcs.GetLength(); n++ )
  9682. {
  9683. desc = builder->GetFunctionDescription(funcs[n]);
  9684. if( desc->isReadOnly != removeConst )
  9685. {
  9686. foundNonConst = true;
  9687. break;
  9688. }
  9689. }
  9690. if( foundNonConst )
  9691. {
  9692. // Remove all const methods
  9693. for( n = 0; n < funcs.GetLength(); n++ )
  9694. {
  9695. desc = builder->GetFunctionDescription(funcs[n]);
  9696. if( desc->isReadOnly == removeConst )
  9697. {
  9698. if( n == funcs.GetLength() - 1 )
  9699. funcs.PopLast();
  9700. else
  9701. funcs[n] = funcs.PopLast();
  9702. n--;
  9703. }
  9704. }
  9705. }
  9706. }
  9707. END_AS_NAMESPACE
  9708. #endif // AS_NO_COMPILER