as_compiler.cpp 326 KB

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