as_compiler.cpp 432 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2014 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. // Modified by Lasse Oorni for Urho3D
  24. //
  25. // as_compiler.cpp
  26. //
  27. // The class that does the actual compilation of the functions
  28. //
  29. #include <math.h> // fmodf() pow()
  30. #include "as_config.h"
  31. #ifndef AS_NO_COMPILER
  32. #include "as_compiler.h"
  33. #include "as_tokendef.h"
  34. #include "as_tokenizer.h"
  35. #include "as_string_util.h"
  36. #include "as_texts.h"
  37. #include "as_parser.h"
  38. #include "as_debug.h"
  39. #include "as_context.h" // as_powi()
  40. BEGIN_AS_NAMESPACE
  41. //
  42. // The calling convention rules for script functions:
  43. // - If a class method returns a reference, the caller must guarantee the object pointer stays alive until the function returns, and the reference is no longer going to be used
  44. // - If a class method doesn't return a reference, it must guarantee by itself that the this pointer stays alive during the function call. If no outside access is made, then the function is guaranteed to stay alive and nothing needs to be done
  45. // - The object pointer is always passed as the first argument, position 0
  46. // - If the function returns a value type the caller must reserve the memory for this and pass the pointer as the first argument after the object pointer
  47. //
  48. // TODO: I must correct the interpretation of a references to objects in the compiler.
  49. // A reference should mean that a pointer to the object is on the stack.
  50. // No expression should end up as non-references to objects, as the actual object is
  51. // never put on the stack.
  52. // Local variables are declared as non-references, but the expression should be a reference to the variable.
  53. // Function parameters of called functions can also be non-references, but in that case it means the
  54. // object will be passed by value (currently on the heap, which will be moved to the application stack).
  55. //
  56. // The compiler shouldn't use the asCDataType::IsReference. The datatype should always be stored as non-references.
  57. // Instead the compiler should keep track of references in TypeInfo, where it should also state how the reference
  58. // is currently stored, i.e. in variable, in register, on stack, etc.
  59. asCCompiler::asCCompiler(asCScriptEngine *engine) : byteCode(engine)
  60. {
  61. builder = 0;
  62. script = 0;
  63. variables = 0;
  64. isProcessingDeferredParams = false;
  65. isCompilingDefaultArg = false;
  66. noCodeOutput = 0;
  67. }
  68. asCCompiler::~asCCompiler()
  69. {
  70. while( variables )
  71. {
  72. asCVariableScope *var = variables;
  73. variables = variables->parent;
  74. asDELETE(var,asCVariableScope);
  75. }
  76. }
  77. void asCCompiler::Reset(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  78. {
  79. this->builder = builder;
  80. this->engine = builder->engine;
  81. this->script = script;
  82. this->outFunc = outFunc;
  83. hasCompileErrors = false;
  84. m_isConstructor = false;
  85. m_isConstructorCalled = false;
  86. m_classDecl = 0;
  87. nextLabel = 0;
  88. breakLabels.SetLength(0);
  89. continueLabels.SetLength(0);
  90. byteCode.ClearAll();
  91. }
  92. int asCCompiler::CompileDefaultConstructor(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, asCScriptFunction *outFunc, sClassDeclaration *classDecl)
  93. {
  94. Reset(builder, script, outFunc);
  95. m_classDecl = classDecl;
  96. // Insert a JitEntry at the start of the function for JIT compilers
  97. byteCode.InstrPTR(asBC_JitEntry, 0);
  98. // Add a variable scope that might be needed to declare dummy variables
  99. // in case the member initialization refers to undefined symbols.
  100. AddVariableScope();
  101. // Initialize the class members that have no explicit expression first. This will allow the
  102. // base class' constructor to access these members without worry they will be uninitialized.
  103. // This can happen if the base class' constructor calls a method that is overridden by the derived class
  104. CompileMemberInitialization(&byteCode, true);
  105. // If the class is derived from another, then the base class' default constructor must be called
  106. if( outFunc->objectType->derivedFrom )
  107. {
  108. // Make sure the base class really has a default constructor
  109. if( outFunc->objectType->derivedFrom->beh.construct == 0 )
  110. Error(TEXT_BASE_DOESNT_HAVE_DEF_CONSTR, node);
  111. // Call the base class' default constructor
  112. byteCode.InstrSHORT(asBC_PSF, 0);
  113. byteCode.Instr(asBC_RDSPtr);
  114. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  115. }
  116. // Initialize the class members that explicit expressions afterwards. This allow the expressions
  117. // to access the base class members without worry they will be uninitialized
  118. CompileMemberInitialization(&byteCode, false);
  119. byteCode.OptimizeLocally(tempVariableOffsets);
  120. // If there are compile errors, there is no reason to build the final code
  121. if( hasCompileErrors )
  122. return -1;
  123. // Pop the object pointer from the stack
  124. byteCode.Ret(AS_PTR_SIZE);
  125. // Count total variable size
  126. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  127. outFunc->scriptData->variableSpace = varSize;
  128. FinalizeFunction();
  129. #ifdef AS_DEBUG
  130. // DEBUG: output byte code
  131. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + "__defconstr.txt").AddressOf(), engine, outFunc);
  132. #endif
  133. return 0;
  134. }
  135. int asCCompiler::CompileFactory(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  136. {
  137. Reset(builder, script, outFunc);
  138. // Insert a JitEntry at the start of the function for JIT compilers
  139. byteCode.InstrPTR(asBC_JitEntry, 0);
  140. // Find the corresponding constructor
  141. asCDataType dt = asCDataType::CreateObject(outFunc->returnType.GetObjectType(), false);
  142. int constructor = 0;
  143. for( unsigned int n = 0; n < dt.GetBehaviour()->factories.GetLength(); n++ )
  144. {
  145. if( dt.GetBehaviour()->factories[n] == outFunc->id )
  146. {
  147. constructor = dt.GetBehaviour()->constructors[n];
  148. break;
  149. }
  150. }
  151. // Allocate the class and instanciate it with the constructor
  152. int varOffset = AllocateVariable(dt, true);
  153. outFunc->scriptData->variableSpace = AS_PTR_SIZE;
  154. byteCode.InstrSHORT(asBC_PSF, (short)varOffset);
  155. // Copy all arguments to the top of the stack
  156. // TODO: runtime optimize: Might be interesting to have a specific instruction for copying all arguments
  157. int offset = (int)outFunc->GetSpaceNeededForArguments();
  158. for( int a = int(outFunc->parameterTypes.GetLength()) - 1; a >= 0; a-- )
  159. {
  160. if( !outFunc->parameterTypes[a].IsPrimitive() ||
  161. outFunc->parameterTypes[a].IsReference() )
  162. {
  163. offset -= AS_PTR_SIZE;
  164. byteCode.InstrSHORT(asBC_PshVPtr, short(-offset));
  165. }
  166. else
  167. {
  168. if( outFunc->parameterTypes[a].GetSizeOnStackDWords() == 2 )
  169. {
  170. offset -= 2;
  171. byteCode.InstrSHORT(asBC_PshV8, short(-offset));
  172. }
  173. else
  174. {
  175. offset -= 1;
  176. byteCode.InstrSHORT(asBC_PshV4, short(-offset));
  177. }
  178. }
  179. }
  180. int argDwords = (int)outFunc->GetSpaceNeededForArguments();
  181. byteCode.Alloc(asBC_ALLOC, dt.GetObjectType(), constructor, argDwords + AS_PTR_SIZE);
  182. // Return a handle to the newly created object
  183. byteCode.InstrSHORT(asBC_LOADOBJ, (short)varOffset);
  184. byteCode.Ret(argDwords);
  185. FinalizeFunction();
  186. // Tell the virtual machine not to clean up parameters on exception
  187. outFunc->dontCleanUpOnException = true;
  188. /*
  189. #ifdef AS_DEBUG
  190. // DEBUG: output byte code
  191. asCString args;
  192. args.Format("%d", outFunc->parameterTypes.GetLength());
  193. byteCode.DebugOutput(("__" + outFunc->name + "__factory" + args + ".txt").AddressOf(), engine);
  194. #endif
  195. */
  196. return 0;
  197. }
  198. void asCCompiler::FinalizeFunction()
  199. {
  200. TimeIt("asCCompiler::FinalizeFunction");
  201. asASSERT( outFunc->scriptData );
  202. asUINT n;
  203. // Finalize the bytecode
  204. byteCode.Finalize(tempVariableOffsets);
  205. byteCode.ExtractObjectVariableInfo(outFunc);
  206. // Compile the list of object variables for the exception handler
  207. // Start with the variables allocated on the heap, and then the ones allocated on the stack
  208. for( n = 0; n < variableAllocations.GetLength(); n++ )
  209. {
  210. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  211. {
  212. if( variableIsOnHeap[n] )
  213. {
  214. outFunc->scriptData->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  215. outFunc->scriptData->funcVariableTypes.PushLast(variableAllocations[n].GetFuncDef());
  216. outFunc->scriptData->objVariablePos.PushLast(GetVariableOffset(n));
  217. }
  218. }
  219. }
  220. outFunc->scriptData->objVariablesOnHeap = asUINT(outFunc->scriptData->objVariablePos.GetLength());
  221. for( n = 0; n < variableAllocations.GetLength(); n++ )
  222. {
  223. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  224. {
  225. if( !variableIsOnHeap[n] )
  226. {
  227. outFunc->scriptData->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  228. outFunc->scriptData->funcVariableTypes.PushLast(variableAllocations[n].GetFuncDef());
  229. outFunc->scriptData->objVariablePos.PushLast(GetVariableOffset(n));
  230. }
  231. }
  232. }
  233. // Copy byte code to the function
  234. asASSERT( outFunc->scriptData->byteCode.GetLength() == 0 );
  235. outFunc->scriptData->byteCode.SetLength(byteCode.GetSize());
  236. byteCode.Output(outFunc->scriptData->byteCode.AddressOf());
  237. outFunc->AddReferences();
  238. outFunc->scriptData->stackNeeded = byteCode.largestStackUsed + outFunc->scriptData->variableSpace;
  239. outFunc->scriptData->lineNumbers = byteCode.lineNumbers;
  240. // Extract the script section indexes too if there are any entries that are different from the function's script section
  241. int lastIdx = outFunc->scriptData->scriptSectionIdx;
  242. for( n = 0; n < byteCode.sectionIdxs.GetLength(); n++ )
  243. {
  244. if( byteCode.sectionIdxs[n] != lastIdx )
  245. {
  246. lastIdx = byteCode.sectionIdxs[n];
  247. outFunc->scriptData->sectionIdxs.PushLast(byteCode.lineNumbers[n*2]);
  248. outFunc->scriptData->sectionIdxs.PushLast(lastIdx);
  249. }
  250. }
  251. }
  252. // internal
  253. int asCCompiler::SetupParametersAndReturnVariable(asCArray<asCString> &parameterNames, asCScriptNode *func)
  254. {
  255. int stackPos = 0;
  256. if( outFunc->objectType )
  257. stackPos = -AS_PTR_SIZE; // The first parameter is the pointer to the object
  258. // Add the first variable scope, which the parameters and
  259. // variables declared in the outermost statement block is
  260. // part of.
  261. AddVariableScope();
  262. bool isDestructor = false;
  263. asCDataType returnType;
  264. // Examine return type
  265. returnType = outFunc->returnType;
  266. // Check if this is a constructor or destructor
  267. if( returnType.GetTokenType() == ttVoid && outFunc->objectType )
  268. {
  269. if( outFunc->name[0] == '~' )
  270. isDestructor = true;
  271. else if( outFunc->objectType->name == outFunc->name )
  272. m_isConstructor = true;
  273. }
  274. // Is the return type allowed?
  275. if( (!returnType.CanBeInstanciated() && returnType != asCDataType::CreatePrimitive(ttVoid, false)) ||
  276. (returnType.IsReference() && !returnType.CanBeInstanciated()) )
  277. {
  278. // TODO: Hasn't this been validated by the builder already?
  279. asCString str;
  280. str.Format(TXT_RETURN_CANT_BE_s, returnType.Format().AddressOf());
  281. Error(str, func);
  282. }
  283. // If the return type is a value type returned by value the address of the
  284. // location where the value will be stored is pushed on the stack before
  285. // the arguments
  286. if( !(isDestructor || m_isConstructor) && outFunc->DoesReturnOnStack() )
  287. stackPos -= AS_PTR_SIZE;
  288. asCVariableScope vs(0);
  289. // Declare parameters
  290. asUINT n;
  291. for( n = 0; n < parameterNames.GetLength(); n++ )
  292. {
  293. // Get the parameter type
  294. asCDataType &type = outFunc->parameterTypes[n];
  295. asETypeModifiers inoutFlag = n < outFunc->inOutFlags.GetLength() ? outFunc->inOutFlags[n] : asTM_NONE;
  296. // Is the data type allowed?
  297. // TODO: Hasn't this been validated by the builder already?
  298. if( (type.IsReference() && inoutFlag != asTM_INOUTREF && !type.CanBeInstanciated()) ||
  299. (!type.IsReference() && !type.CanBeInstanciated()) )
  300. {
  301. asCString parm = type.Format();
  302. if( inoutFlag == asTM_INREF )
  303. parm += "in";
  304. else if( inoutFlag == asTM_OUTREF )
  305. parm += "out";
  306. asCString str;
  307. str.Format(TXT_PARAMETER_CANT_BE_s, parm.AddressOf());
  308. Error(str, func);
  309. }
  310. // If the parameter has a name then declare it as variable
  311. if( parameterNames[n] != "" )
  312. {
  313. asCString &name = parameterNames[n];
  314. if( vs.DeclareVariable(name.AddressOf(), type, stackPos, true) < 0 )
  315. {
  316. // TODO: It might be an out-of-memory too
  317. Error(TXT_PARAMETER_ALREADY_DECLARED, func);
  318. }
  319. // Add marker for variable declaration
  320. byteCode.VarDecl((int)outFunc->scriptData->variables.GetLength());
  321. outFunc->AddVariable(name, type, stackPos);
  322. }
  323. else
  324. vs.DeclareVariable("", type, stackPos, true);
  325. // Move to next parameter
  326. stackPos -= type.GetSizeOnStackDWords();
  327. }
  328. for( n = asUINT(vs.variables.GetLength()); n-- > 0; )
  329. variables->DeclareVariable(vs.variables[n]->name.AddressOf(), vs.variables[n]->type, vs.variables[n]->stackOffset, vs.variables[n]->onHeap);
  330. variables->DeclareVariable("return", returnType, stackPos, true);
  331. return stackPos;
  332. }
  333. void asCCompiler::CompileMemberInitialization(asCByteCode *byteCode, bool onlyDefaults)
  334. {
  335. asASSERT( m_classDecl );
  336. // Initialize each member in the order they were declared
  337. for( asUINT n = 0; n < outFunc->objectType->properties.GetLength(); n++ )
  338. {
  339. asCObjectProperty *prop = outFunc->objectType->properties[n];
  340. // Check if the property has an initialization expression
  341. asCScriptNode *declNode = 0;
  342. asCScriptNode *initNode = 0;
  343. asCScriptCode *initScript = 0;
  344. for( asUINT m = 0; m < m_classDecl->propInits.GetLength(); m++ )
  345. {
  346. if( m_classDecl->propInits[m].name == prop->name )
  347. {
  348. declNode = m_classDecl->propInits[m].declNode;
  349. initNode = m_classDecl->propInits[m].initNode;
  350. initScript = m_classDecl->propInits[m].file;
  351. break;
  352. }
  353. }
  354. // If declNode is null, the property was inherited in which case
  355. // it was already initialized by the base class' constructor
  356. if( declNode )
  357. {
  358. if( initNode )
  359. {
  360. if( onlyDefaults )
  361. continue;
  362. #ifdef AS_NO_MEMBER_INIT
  363. // Give an error as the initialization in the declaration has been disabled
  364. asCScriptCode *origScript = script;
  365. script = initScript;
  366. Error("Initialization of members in declaration is not supported", initNode);
  367. script = origScript;
  368. // Clear the initialization node
  369. initNode = 0;
  370. initScript = script;
  371. #else
  372. // Re-parse the initialization expression as the parser now knows the types, which it didn't earlier
  373. asCParser parser(builder);
  374. int r = parser.ParseVarInit(initScript, initNode);
  375. if( r < 0 )
  376. continue;
  377. initNode = parser.GetScriptNode();
  378. #endif
  379. }
  380. else
  381. {
  382. if( !onlyDefaults )
  383. continue;
  384. }
  385. #ifdef AS_NO_MEMBER_INIT
  386. // The initialization will be done in the asCScriptObject constructor, so
  387. // here we should just validate that the member has a default constructor
  388. if( prop->type.IsObject() &&
  389. !prop->type.IsObjectHandle() &&
  390. (((prop->type.GetObjectType()->flags & asOBJ_REF) &&
  391. prop->type.GetBehaviour()->factory == 0) ||
  392. ((prop->type.GetObjectType()->flags & asOBJ_VALUE) &&
  393. prop->type.GetBehaviour()->construct == 0 &&
  394. !(prop->type.GetObjectType()->flags & asOBJ_POD))) )
  395. {
  396. // Class has no default factory/constructor.
  397. asCString str;
  398. // TODO: funcdef: asCDataType should have a GetTypeName()
  399. if( prop->type.GetFuncDef() )
  400. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, prop->type.GetFuncDef()->GetName());
  401. else
  402. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, prop->type.GetObjectType()->GetName());
  403. Error(str, declNode);
  404. }
  405. #else
  406. // Temporarily set the script that is being compiled to where the member initialization is declared.
  407. // The script can be different when including mixin classes from a different script section
  408. asCScriptCode *origScript = script;
  409. script = initScript;
  410. // Add a line instruction with the position of the declaration
  411. LineInstr(byteCode, declNode->tokenPos);
  412. // Compile the initialization
  413. asQWORD constantValue;
  414. asCByteCode bc(engine);
  415. CompileInitialization(initNode, &bc, prop->type, declNode, prop->byteOffset, &constantValue, 2);
  416. bc.OptimizeLocally(tempVariableOffsets);
  417. byteCode->AddCode(&bc);
  418. script = origScript;
  419. #endif
  420. }
  421. }
  422. }
  423. // Entry
  424. int asCCompiler::CompileFunction(asCBuilder *builder, asCScriptCode *script, asCArray<asCString> &parameterNames, asCScriptNode *func, asCScriptFunction *outFunc, sClassDeclaration *classDecl)
  425. {
  426. TimeIt("asCCompiler::CompileFunction");
  427. Reset(builder, script, outFunc);
  428. int buildErrors = builder->numErrors;
  429. int stackPos = SetupParametersAndReturnVariable(parameterNames, func);
  430. //--------------------------------------------
  431. // Compile the statement block
  432. if( m_isConstructor )
  433. m_classDecl = classDecl;
  434. // We need to parse the statement block now
  435. asCScriptNode *blockBegin;
  436. // If the function signature was implicit, e.g. virtual property
  437. // accessor, then the received node already is the statement block
  438. if( func->nodeType != snStatementBlock )
  439. blockBegin = func->lastChild;
  440. else
  441. blockBegin = func;
  442. // TODO: memory: We can parse the statement block one statement at a time, thus save even more memory
  443. // TODO: optimize: For large functions, the parsing of the statement block can take a long time. Presumably because a lot of memory needs to be allocated
  444. asCParser parser(builder);
  445. int r = parser.ParseStatementBlock(script, blockBegin);
  446. if( r < 0 ) return -1;
  447. asCScriptNode *block = parser.GetScriptNode();
  448. // Reserve a label for the cleanup code
  449. nextLabel++;
  450. bool hasReturn;
  451. asCByteCode bc(engine);
  452. LineInstr(&bc, blockBegin->tokenPos);
  453. CompileStatementBlock(block, false, &hasReturn, &bc);
  454. LineInstr(&bc, blockBegin->tokenPos + blockBegin->tokenLength);
  455. // Make sure there is a return in all paths (if not return type is void)
  456. // Don't bother with this check if there are compiler errors, e.g. Unreachable code
  457. if( !hasCompileErrors && outFunc->returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  458. {
  459. if( hasReturn == false )
  460. Error(TXT_NOT_ALL_PATHS_RETURN, blockBegin);
  461. }
  462. //------------------------------------------------
  463. // Concatenate the bytecode
  464. // Insert a JitEntry at the start of the function for JIT compilers
  465. byteCode.InstrPTR(asBC_JitEntry, 0);
  466. if( outFunc->objectType )
  467. {
  468. if( m_isConstructor )
  469. {
  470. if( outFunc->objectType->derivedFrom )
  471. {
  472. // Call the base class' default constructor unless called manually in the code
  473. if( !m_isConstructorCalled )
  474. {
  475. if( outFunc->objectType->derivedFrom->beh.construct )
  476. {
  477. // Initialize members without explicit expression first
  478. CompileMemberInitialization(&byteCode, true);
  479. // Call base class' constructor
  480. asCByteCode tmpBC(engine);
  481. tmpBC.InstrSHORT(asBC_PSF, 0);
  482. tmpBC.Instr(asBC_RDSPtr);
  483. tmpBC.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  484. tmpBC.OptimizeLocally(tempVariableOffsets);
  485. byteCode.AddCode(&tmpBC);
  486. // Add the initialization of the members with explicit expressions
  487. CompileMemberInitialization(&byteCode, false);
  488. }
  489. else
  490. Error(TEXT_BASE_DOESNT_HAVE_DEF_CONSTR, blockBegin);
  491. }
  492. else
  493. {
  494. // Only initialize members that don't have an explicit expression
  495. // The members that are explicitly initialized will be initialized after the call to base class' constructor
  496. CompileMemberInitialization(&byteCode, true);
  497. }
  498. }
  499. else
  500. {
  501. // Add the initialization of the members
  502. CompileMemberInitialization(&byteCode, true);
  503. CompileMemberInitialization(&byteCode, false);
  504. }
  505. }
  506. }
  507. // Add the code for the statement block
  508. byteCode.AddCode(&bc);
  509. // Count total variable size
  510. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  511. outFunc->scriptData->variableSpace = varSize;
  512. // Deallocate all local variables
  513. int n;
  514. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  515. {
  516. sVariable *v = variables->variables[n];
  517. if( v->stackOffset > 0 )
  518. {
  519. // Call variables destructors
  520. if( v->name != "return" && v->name != "return address" )
  521. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  522. DeallocateVariable(v->stackOffset);
  523. }
  524. }
  525. // This is the label that return statements jump to
  526. // in order to exit the function
  527. byteCode.Label(0);
  528. // Call destructors for function parameters
  529. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  530. {
  531. sVariable *v = variables->variables[n];
  532. if( v->stackOffset <= 0 )
  533. {
  534. // Call variable destructors here, for variables not yet destroyed
  535. if( v->name != "return" && v->name != "return address" )
  536. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  537. }
  538. // Do not deallocate parameters
  539. }
  540. // Check if the number of labels in the functions isn't too many to be handled
  541. if( nextLabel >= (1<<15) )
  542. Error(TXT_TOO_MANY_JUMP_LABELS, func);
  543. // If there are compile errors, there is no reason to build the final code
  544. if( hasCompileErrors || builder->numErrors != buildErrors )
  545. return -1;
  546. // At this point there should be no variables allocated
  547. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  548. // Remove the variable scope
  549. RemoveVariableScope();
  550. byteCode.Ret(-stackPos);
  551. FinalizeFunction();
  552. #ifdef AS_DEBUG
  553. // DEBUG: output byte code
  554. if( outFunc->objectType )
  555. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  556. else
  557. byteCode.DebugOutput(("__" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  558. #endif
  559. return 0;
  560. }
  561. int asCCompiler::CallCopyConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asSExprContext *arg, asCScriptNode *node, bool isGlobalVar, bool derefDest)
  562. {
  563. if( !type.IsObject() )
  564. return 0;
  565. // CallCopyConstructor should not be called for object handles.
  566. asASSERT( !type.IsObjectHandle() );
  567. asCArray<asSExprContext*> args;
  568. args.PushLast(arg);
  569. // The reference parameter must be pushed on the stack
  570. asASSERT( arg->type.dataType.GetObjectType() == type.GetObjectType() );
  571. // Since we're calling the copy constructor, we have to trust the function to not do
  572. // anything stupid otherwise we will just enter a loop, as we try to make temporary
  573. // copies of the argument in order to guarantee safety.
  574. if( type.GetObjectType()->flags & asOBJ_REF )
  575. {
  576. asSExprContext ctx(engine);
  577. int func = 0;
  578. asSTypeBehaviour *beh = type.GetBehaviour();
  579. if( beh ) func = beh->copyfactory;
  580. if( func > 0 )
  581. {
  582. if( !isGlobalVar )
  583. {
  584. // Call factory and store the handle in the given variable
  585. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType(), true, offset);
  586. // Pop the reference left by the function call
  587. ctx.bc.Instr(asBC_PopPtr);
  588. }
  589. else
  590. {
  591. // Call factory
  592. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType());
  593. // Store the returned handle in the global variable
  594. ctx.bc.Instr(asBC_RDSPtr);
  595. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  596. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  597. ctx.bc.Instr(asBC_PopPtr);
  598. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  599. }
  600. bc->AddCode(&ctx.bc);
  601. return 0;
  602. }
  603. }
  604. else
  605. {
  606. asSTypeBehaviour *beh = type.GetBehaviour();
  607. int func = beh ? beh->copyconstruct : 0;
  608. if( func > 0 )
  609. {
  610. // Push the address where the object will be stored on the stack, before the argument
  611. // TODO: When the context is serializable this probably has to be changed, since this
  612. // pointer can remain on the stack while the context is suspended. There is no
  613. // risk the pointer becomes invalid though, there is just no easy way to serialize it.
  614. asCByteCode tmp(engine);
  615. if( isGlobalVar )
  616. tmp.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  617. else if( isObjectOnHeap )
  618. tmp.InstrSHORT(asBC_PSF, (short)offset);
  619. tmp.AddCode(bc);
  620. bc->AddCode(&tmp);
  621. // When the object is allocated on the stack the object pointer
  622. // must be pushed on the stack after the arguments
  623. if( !isObjectOnHeap )
  624. {
  625. asASSERT( !isGlobalVar );
  626. bc->InstrSHORT(asBC_PSF, (short)offset);
  627. if( derefDest )
  628. {
  629. // The variable is a reference to the real location, so we need to dereference it
  630. bc->Instr(asBC_RDSPtr);
  631. }
  632. }
  633. asSExprContext ctx(engine);
  634. PerformFunctionCall(func, &ctx, isObjectOnHeap, &args, type.GetObjectType());
  635. bc->AddCode(&ctx.bc);
  636. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  637. // Mark the object as initialized
  638. if( !isObjectOnHeap )
  639. bc->ObjInfo(offset, asOBJ_INIT);
  640. return 0;
  641. }
  642. }
  643. // Class has no copy constructor/factory.
  644. asCString str;
  645. str.Format(TXT_NO_COPY_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  646. Error(str, node);
  647. return -1;
  648. }
  649. int asCCompiler::CallDefaultConstructor(const asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asCScriptNode *node, int isVarGlobOrMem, bool derefDest)
  650. {
  651. if( !type.IsObject() || type.IsObjectHandle() )
  652. return 0;
  653. if( type.GetObjectType()->flags & asOBJ_REF )
  654. {
  655. asSExprContext ctx(engine);
  656. ctx.exprNode = node;
  657. int func = 0;
  658. asSTypeBehaviour *beh = type.GetBehaviour();
  659. if( beh )
  660. {
  661. func = beh->factory;
  662. // If no trivial default factory is found, look for a factory where all params have default args
  663. if( func == 0 )
  664. {
  665. for( asUINT n = 0; n < beh->factories.GetLength(); n++ )
  666. {
  667. asCScriptFunction *f = engine->scriptFunctions[beh->factories[n]];
  668. if( f->defaultArgs.GetLength() == f->parameterTypes.GetLength() &&
  669. f->defaultArgs[0] != 0 )
  670. {
  671. func = beh->factories[n];
  672. break;
  673. }
  674. }
  675. }
  676. }
  677. if( func > 0 )
  678. {
  679. asCArray<asSExprContext *> args;
  680. asCScriptFunction *f = engine->scriptFunctions[func];
  681. if( f->parameterTypes.GetLength() )
  682. {
  683. // Add the default values for arguments not explicitly supplied
  684. CompileDefaultAndNamedArgs(node, args, func, type.GetObjectType());
  685. PrepareFunctionCall(func, &ctx.bc, args);
  686. MoveArgsToStack(func, &ctx.bc, args, false);
  687. }
  688. if( isVarGlobOrMem == 0 )
  689. {
  690. // Call factory and store the handle in the given variable
  691. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType(), true, offset);
  692. // Pop the reference left by the function call
  693. ctx.bc.Instr(asBC_PopPtr);
  694. }
  695. else
  696. {
  697. // Call factory
  698. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType());
  699. // TODO: runtime optimize: Should have a way of storing the object pointer directly to the destination
  700. // instead of first storing it in a local variable and then copying it to the
  701. // destination.
  702. if( !(type.GetObjectType()->flags & asOBJ_SCOPED) )
  703. {
  704. // Only dereference the variable if not a scoped type
  705. ctx.bc.Instr(asBC_RDSPtr);
  706. }
  707. if( isVarGlobOrMem == 1 )
  708. {
  709. // Store the returned handle in the global variable
  710. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  711. }
  712. else
  713. {
  714. // Store the returned handle in the class member
  715. ctx.bc.InstrSHORT(asBC_PSF, 0);
  716. ctx.bc.Instr(asBC_RDSPtr);
  717. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  718. }
  719. if( type.GetObjectType()->flags & asOBJ_SCOPED )
  720. {
  721. // For scoped typed we must move the reference from the local
  722. // variable rather than copy it as there is no AddRef behaviour
  723. ctx.bc.InstrSHORT_DW(asBC_COPY, AS_PTR_SIZE, asTYPEID_OBJHANDLE | engine->GetTypeIdFromDataType(type));
  724. // Clear the local variable so the reference isn't released
  725. ctx.bc.InstrSHORT(asBC_ClrVPtr, ctx.type.stackOffset);
  726. }
  727. else
  728. {
  729. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  730. }
  731. ctx.bc.Instr(asBC_PopPtr);
  732. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  733. }
  734. bc->AddCode(&ctx.bc);
  735. // Cleanup
  736. for( asUINT n = 0; n < args.GetLength(); n++ )
  737. if( args[n] )
  738. {
  739. asDELETE(args[n],asSExprContext);
  740. }
  741. return 0;
  742. }
  743. }
  744. else
  745. {
  746. asSExprContext ctx(engine);
  747. ctx.exprNode = node;
  748. asSTypeBehaviour *beh = type.GetBehaviour();
  749. int func = 0;
  750. if( beh )
  751. {
  752. func = beh->construct;
  753. // If no trivial default constructor is found, look for a constructor where all params have default args
  754. if( func == 0 )
  755. {
  756. for( asUINT n = 0; n < beh->constructors.GetLength(); n++ )
  757. {
  758. asCScriptFunction *f = engine->scriptFunctions[beh->constructors[n]];
  759. if( f->defaultArgs.GetLength() == f->parameterTypes.GetLength() &&
  760. f->defaultArgs[0] != 0 )
  761. {
  762. func = beh->constructors[n];
  763. break;
  764. }
  765. }
  766. }
  767. }
  768. // Allocate and initialize with the default constructor
  769. if( func != 0 || (type.GetObjectType()->flags & asOBJ_POD) )
  770. {
  771. asCArray<asSExprContext *> args;
  772. asCScriptFunction *f = engine->scriptFunctions[func];
  773. if( f && f->parameterTypes.GetLength() )
  774. {
  775. // Add the default values for arguments not explicitly supplied
  776. CompileDefaultAndNamedArgs(node, args, func, type.GetObjectType());
  777. PrepareFunctionCall(func, &ctx.bc, args);
  778. MoveArgsToStack(func, &ctx.bc, args, false);
  779. }
  780. if( !isObjectOnHeap )
  781. {
  782. if( isVarGlobOrMem == 0 )
  783. {
  784. // There is nothing to do if there is no function,
  785. // as the memory is already allocated on the stack
  786. if( func )
  787. {
  788. // Call the constructor as a normal function
  789. bc->InstrSHORT(asBC_PSF, (short)offset);
  790. if( derefDest )
  791. bc->Instr(asBC_RDSPtr);
  792. asSExprContext ctx(engine);
  793. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  794. bc->AddCode(&ctx.bc);
  795. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  796. // Mark the object as initialized
  797. bc->ObjInfo(offset, asOBJ_INIT);
  798. }
  799. }
  800. else if( isVarGlobOrMem == 2 )
  801. {
  802. // Only POD types can be allocated inline in script classes
  803. asASSERT( type.GetObjectType()->flags & asOBJ_POD );
  804. if( func )
  805. {
  806. // Call the constructor as a normal function
  807. bc->InstrSHORT(asBC_PSF, 0);
  808. bc->Instr(asBC_RDSPtr);
  809. bc->InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  810. asSExprContext ctx(engine);
  811. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  812. bc->AddCode(&ctx.bc);
  813. }
  814. }
  815. else
  816. {
  817. asASSERT( false );
  818. }
  819. }
  820. else
  821. {
  822. if( isVarGlobOrMem == 0 )
  823. bc->InstrSHORT(asBC_PSF, (short)offset);
  824. else if( isVarGlobOrMem == 1 )
  825. bc->InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  826. else
  827. {
  828. bc->InstrSHORT(asBC_PSF, 0);
  829. bc->Instr(asBC_RDSPtr);
  830. bc->InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  831. }
  832. bc->Alloc(asBC_ALLOC, type.GetObjectType(), func, AS_PTR_SIZE);
  833. }
  834. // Cleanup
  835. for( asUINT n = 0; n < args.GetLength(); n++ )
  836. if( args[n] )
  837. {
  838. asDELETE(args[n],asSExprContext);
  839. }
  840. return 0;
  841. }
  842. }
  843. // Class has no default factory/constructor.
  844. asCString str;
  845. // TODO: funcdef: asCDataType should have a GetTypeName()
  846. if( type.GetFuncDef() )
  847. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetFuncDef()->GetName());
  848. else
  849. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  850. Error(str, node);
  851. return -1;
  852. }
  853. void asCCompiler::CallDestructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc)
  854. {
  855. if( !type.IsReference() )
  856. {
  857. // Call destructor for the data type
  858. if( type.IsObject() )
  859. {
  860. // The null pointer doesn't need to be destroyed
  861. if( type.IsNullHandle() )
  862. return;
  863. // Nothing is done for list pattern types, as this is taken care of by the CompileInitList method
  864. if( type.GetObjectType()->flags & asOBJ_LIST_PATTERN )
  865. return;
  866. if( isObjectOnHeap || type.IsObjectHandle() )
  867. {
  868. // Free the memory
  869. bc->InstrW_PTR(asBC_FREE, (short)offset, type.GetObjectType());
  870. }
  871. else
  872. {
  873. asASSERT( type.GetObjectType()->GetFlags() & asOBJ_VALUE );
  874. if( type.GetBehaviour()->destruct )
  875. {
  876. // Call the destructor as a regular function
  877. asSExprContext ctx(engine);
  878. ctx.bc.InstrSHORT(asBC_PSF, (short)offset);
  879. PerformFunctionCall(type.GetBehaviour()->destruct, &ctx);
  880. ctx.bc.OptimizeLocally(tempVariableOffsets);
  881. bc->AddCode(&ctx.bc);
  882. }
  883. // TODO: Value on stack: This probably needs to be done in PerformFunctionCall
  884. // Mark the object as destroyed
  885. bc->ObjInfo(offset, asOBJ_UNINIT);
  886. }
  887. }
  888. }
  889. }
  890. void asCCompiler::LineInstr(asCByteCode *bc, size_t pos)
  891. {
  892. int r, c;
  893. script->ConvertPosToRowCol(pos, &r, &c);
  894. bc->Line(r, c, script->idx);
  895. }
  896. void asCCompiler::CompileStatementBlock(asCScriptNode *block, bool ownVariableScope, bool *hasReturn, asCByteCode *bc)
  897. {
  898. *hasReturn = false;
  899. bool isFinished = false;
  900. bool hasUnreachableCode = false;
  901. bool hasReturnBefore = false;
  902. if( ownVariableScope )
  903. {
  904. bc->Block(true);
  905. AddVariableScope();
  906. }
  907. asCScriptNode *node = block->firstChild;
  908. while( node )
  909. {
  910. #ifdef AS_DEBUG
  911. // Keep the current line in a variable so it will be easier
  912. // to determine where in a script an assert is occurring.
  913. int currentLine = 0;
  914. script->ConvertPosToRowCol(node->tokenPos, &currentLine, 0);
  915. #endif
  916. if( !hasUnreachableCode && (*hasReturn || isFinished) )
  917. {
  918. // Empty statements don't count
  919. if( node->nodeType != snExpressionStatement || node->firstChild )
  920. {
  921. hasUnreachableCode = true;
  922. Warning(TXT_UNREACHABLE_CODE, node);
  923. }
  924. if( *hasReturn )
  925. hasReturnBefore = true;
  926. }
  927. if( node->nodeType == snBreak || node->nodeType == snContinue )
  928. isFinished = true;
  929. asCByteCode statement(engine);
  930. if( node->nodeType == snDeclaration )
  931. CompileDeclaration(node, &statement);
  932. else
  933. CompileStatement(node, hasReturn, &statement);
  934. // Ignore missing returns in unreachable code paths
  935. if( !(*hasReturn) && hasReturnBefore )
  936. *hasReturn = true;
  937. LineInstr(bc, node->tokenPos);
  938. bc->AddCode(&statement);
  939. if( !hasCompileErrors )
  940. {
  941. asASSERT( tempVariables.GetLength() == 0 );
  942. asASSERT( reservedVariables.GetLength() == 0 );
  943. }
  944. node = node->next;
  945. }
  946. if( ownVariableScope )
  947. {
  948. // Deallocate variables in this block, in reverse order
  949. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  950. {
  951. sVariable *v = variables->variables[n];
  952. // Call variable destructors here, for variables not yet destroyed
  953. // If the block is terminated with a break, continue, or
  954. // return the variables are already destroyed
  955. if( !isFinished && !*hasReturn )
  956. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  957. // Don't deallocate function parameters
  958. if( v->stackOffset > 0 )
  959. DeallocateVariable(v->stackOffset);
  960. }
  961. RemoveVariableScope();
  962. bc->Block(false);
  963. }
  964. }
  965. // Entry
  966. int asCCompiler::CompileGlobalVariable(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, sGlobalVariableDescription *gvar, asCScriptFunction *outFunc)
  967. {
  968. Reset(builder, script, outFunc);
  969. // Add a variable scope (even though variables can't be declared)
  970. AddVariableScope();
  971. gvar->isPureConstant = false;
  972. // Parse the initialization nodes
  973. asCParser parser(builder);
  974. if( node )
  975. {
  976. int r = parser.ParseVarInit(script, node);
  977. if( r < 0 )
  978. return r;
  979. node = parser.GetScriptNode();
  980. }
  981. asSExprContext compiledCtx(engine);
  982. bool preCompiled = false;
  983. if( gvar->datatype.IsAuto() )
  984. preCompiled = CompileAutoType(gvar->datatype, compiledCtx, node, gvar->declaredAtNode);
  985. if( gvar->property == 0 )
  986. {
  987. gvar->property = builder->module->AllocateGlobalProperty(gvar->name.AddressOf(), gvar->datatype, gvar->ns);
  988. gvar->index = gvar->property->id;
  989. }
  990. // Compile the expression
  991. asSExprContext ctx(engine);
  992. asQWORD constantValue = 0;
  993. if( CompileInitialization(node, &ctx.bc, gvar->datatype, gvar->declaredAtNode, gvar->index, &constantValue, 1, preCompiled ? &compiledCtx : 0) )
  994. {
  995. // Should the variable be marked as pure constant?
  996. if( gvar->datatype.IsPrimitive() && gvar->datatype.IsReadOnly() )
  997. {
  998. gvar->isPureConstant = true;
  999. gvar->constantValue = constantValue;
  1000. }
  1001. }
  1002. // Concatenate the bytecode
  1003. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  1004. // Add information on the line number for the global variable
  1005. size_t pos = 0;
  1006. if( gvar->declaredAtNode )
  1007. pos = gvar->declaredAtNode->tokenPos;
  1008. else if( gvar->initializationNode )
  1009. pos = gvar->initializationNode->tokenPos;
  1010. LineInstr(&byteCode, pos);
  1011. // Reserve space for all local variables
  1012. outFunc->scriptData->variableSpace = varSize;
  1013. ctx.bc.OptimizeLocally(tempVariableOffsets);
  1014. byteCode.AddCode(&ctx.bc);
  1015. // Deallocate variables in this block, in reverse order
  1016. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; --n )
  1017. {
  1018. sVariable *v = variables->variables[n];
  1019. // Call variable destructors here, for variables not yet destroyed
  1020. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  1021. DeallocateVariable(v->stackOffset);
  1022. }
  1023. if( hasCompileErrors ) return -1;
  1024. // At this point there should be no variables allocated
  1025. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  1026. // Remove the variable scope again
  1027. RemoveVariableScope();
  1028. byteCode.Ret(0);
  1029. FinalizeFunction();
  1030. #ifdef AS_DEBUG
  1031. // DEBUG: output byte code
  1032. byteCode.DebugOutput(("___init_" + gvar->name + ".txt").AddressOf(), engine, outFunc);
  1033. #endif
  1034. return 0;
  1035. }
  1036. void asCCompiler::DetermineSingleFunc(asSExprContext *ctx, asCScriptNode *node)
  1037. {
  1038. // Don't do anything if this is not a deferred global function
  1039. if( !ctx->IsGlobalFunc() )
  1040. return;
  1041. // Determine the namespace
  1042. asSNameSpace *ns = 0;
  1043. asCString name = "";
  1044. int pos = ctx->methodName.FindLast("::");
  1045. if( pos >= 0 )
  1046. {
  1047. asCString nsName = ctx->methodName.SubString(0, pos+2);
  1048. // Cut off the ::
  1049. if( nsName.GetLength() > 2 )
  1050. nsName.SetLength(nsName.GetLength()-2);
  1051. ns = DetermineNameSpace(nsName);
  1052. name = ctx->methodName.SubString(pos+2);
  1053. }
  1054. else
  1055. {
  1056. DetermineNameSpace("");
  1057. name = ctx->methodName;
  1058. }
  1059. asCArray<int> funcs;
  1060. if( ns )
  1061. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  1062. // CompileVariableAccess should guarantee that at least one function is exists
  1063. asASSERT( funcs.GetLength() > 0 );
  1064. if( funcs.GetLength() > 1 )
  1065. {
  1066. asCString str;
  1067. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, ctx->methodName.AddressOf());
  1068. Error(str, node);
  1069. // Fall through so the compiler can continue as if only one function was matching
  1070. }
  1071. // A shared object may not access global functions unless they too are shared (e.g. registered functions)
  1072. if( !builder->GetFunctionDescription(funcs[0])->IsShared() &&
  1073. outFunc->IsShared() )
  1074. {
  1075. asCString msg;
  1076. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, builder->GetFunctionDescription(funcs[0])->GetDeclaration());
  1077. Error(msg, node);
  1078. // Fall through so the compiler can continue anyway
  1079. }
  1080. // Push the function pointer on the stack
  1081. ctx->bc.InstrPTR(asBC_FuncPtr, builder->GetFunctionDescription(funcs[0]));
  1082. ctx->type.Set(asCDataType::CreateFuncDef(builder->GetFunctionDescription(funcs[0])));
  1083. ctx->type.dataType.MakeHandle(true);
  1084. ctx->type.isExplicitHandle = true;
  1085. ctx->methodName = "";
  1086. }
  1087. void asCCompiler::CompileInitAsCopy(asCDataType &dt, int offset, asCByteCode *bc, asSExprContext *arg, asCScriptNode *node, bool derefDestination)
  1088. {
  1089. asASSERT( dt.GetObjectType() );
  1090. bool isObjectOnHeap = derefDestination ? false : IsVariableOnHeap(offset);
  1091. // Use copy constructor if available.
  1092. if( dt.GetObjectType()->beh.copyconstruct )
  1093. {
  1094. PrepareForAssignment(&dt, arg, node, true);
  1095. int r = CallCopyConstructor(dt, offset, isObjectOnHeap, bc, arg, node, 0, derefDestination);
  1096. if( r < 0 && tempVariables.Exists(offset) )
  1097. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  1098. }
  1099. else
  1100. {
  1101. // TODO: 2.28.1: Need to reserve variables, as the default constructor may need
  1102. // to allocate temporary variables to compute default args
  1103. // Allocate and construct the temporary object before whatever is already in the bytecode
  1104. asCByteCode tmpBC(engine);
  1105. int r = CallDefaultConstructor(dt, offset, isObjectOnHeap, &tmpBC, node, 0, derefDestination);
  1106. if( r < 0 )
  1107. {
  1108. if( tempVariables.Exists(offset) )
  1109. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  1110. return;
  1111. }
  1112. tmpBC.AddCode(bc);
  1113. bc->AddCode(&tmpBC);
  1114. // Assign the evaluated expression to the temporary variable
  1115. PrepareForAssignment(&dt, arg, node, true);
  1116. bc->AddCode(&arg->bc);
  1117. // Call the opAssign method to assign the value to the temporary object
  1118. dt.MakeReference(isObjectOnHeap);
  1119. asCTypeInfo type;
  1120. type.Set(dt);
  1121. type.isTemporary = true;
  1122. type.stackOffset = (short)offset;
  1123. if( dt.IsObjectHandle() )
  1124. type.isExplicitHandle = true;
  1125. bc->InstrSHORT(asBC_PSF, (short)offset);
  1126. if( derefDestination )
  1127. bc->Instr(asBC_RDSPtr);
  1128. r = PerformAssignment(&type, &arg->type, bc, node);
  1129. if( r < 0 )
  1130. {
  1131. if( tempVariables.Exists(offset) )
  1132. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  1133. return;
  1134. }
  1135. // Pop the reference that was pushed on the stack if the result is an object
  1136. if( type.dataType.IsObject() )
  1137. bc->Instr(asBC_PopPtr);
  1138. // If the assignment operator returned an object by value it will
  1139. // be in a temporary variable which we need to destroy now
  1140. if( type.isTemporary && type.stackOffset != (short)offset )
  1141. ReleaseTemporaryVariable(type.stackOffset, bc);
  1142. // Release the original value too in case it is a temporary
  1143. ReleaseTemporaryVariable(arg->type, bc);
  1144. }
  1145. }
  1146. int asCCompiler::PrepareArgument(asCDataType *paramType, asSExprContext *ctx, asCScriptNode *node, bool isFunction, int refType, bool isMakingCopy)
  1147. {
  1148. asCDataType param = *paramType;
  1149. if( paramType->GetTokenType() == ttQuestion )
  1150. {
  1151. // The function is expecting a var type. If the argument is a function name, we must now decide which function it is
  1152. DetermineSingleFunc(ctx, node);
  1153. // Since the function is expecting a var type ?, then we don't want to convert the argument to anything else
  1154. param = ctx->type.dataType;
  1155. param.MakeHandle(ctx->type.isExplicitHandle || ctx->type.IsNullConstant());
  1156. // Treat the void expression like a null handle when working with var types
  1157. if( ctx->type.IsVoidExpression() )
  1158. param = asCDataType::CreateNullHandle();
  1159. // If value assign is disabled for reference types, then make
  1160. // sure to always pass the handle to ? parameters
  1161. if( builder->engine->ep.disallowValueAssignForRefType &&
  1162. ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_REF) && !(ctx->type.dataType.GetObjectType()->flags & asOBJ_SCOPED) )
  1163. {
  1164. param.MakeHandle(true);
  1165. }
  1166. param.MakeReference(paramType->IsReference());
  1167. param.MakeReadOnly(paramType->IsReadOnly());
  1168. }
  1169. else
  1170. param = *paramType;
  1171. asCDataType dt = param;
  1172. // Need to protect arguments by reference
  1173. if( isFunction && dt.IsReference() )
  1174. {
  1175. // Allocate a temporary variable of the same type as the argument
  1176. dt.MakeReference(false);
  1177. dt.MakeReadOnly(false);
  1178. int offset;
  1179. if( refType == 1 ) // &in
  1180. {
  1181. ProcessPropertyGetAccessor(ctx, node);
  1182. // Add the type id as hidden arg if the parameter is a ? type
  1183. if( paramType->GetTokenType() == ttQuestion )
  1184. {
  1185. asCByteCode tmpBC(engine);
  1186. // Place the type id on the stack as a hidden parameter
  1187. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  1188. // Insert the code before the expression code
  1189. tmpBC.AddCode(&ctx->bc);
  1190. ctx->bc.AddCode(&tmpBC);
  1191. }
  1192. if( dt.IsPrimitive() )
  1193. {
  1194. // If the reference is const, then it is not necessary to make a copy if the value already is a variable
  1195. // Even if the same variable is passed in another argument as non-const then there is no problem
  1196. IsVariableInitialized(&ctx->type, node);
  1197. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  1198. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true);
  1199. if( !(param.IsReadOnly() && ctx->type.isVariable) )
  1200. ConvertToTempVariable(ctx);
  1201. PushVariableOnStack(ctx, true);
  1202. ctx->type.dataType.MakeReadOnly(param.IsReadOnly());
  1203. }
  1204. else if( ctx->type.dataType.IsNullHandle() )
  1205. {
  1206. // Need to initialize a local temporary variable to
  1207. // represent the null handle when passed as reference
  1208. asASSERT( ctx->bc.GetLastInstr() == asBC_PshNull );
  1209. ctx->bc.Instr(asBC_PopPtr);
  1210. dt.MakeHandle(true);
  1211. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1212. // Push the reference to the variable on the stack
  1213. ctx->bc.InstrWORD(asBC_PSF, (short)offset);
  1214. ctx->type.SetVariable(dt, offset, true);
  1215. }
  1216. else
  1217. {
  1218. IsVariableInitialized(&ctx->type, node);
  1219. if( !isMakingCopy )
  1220. {
  1221. // Even though the parameter expects a reference, it is only meant to be
  1222. // used as input value and doesn't have to refer to the actual object, so it
  1223. // is OK to do an implicit conversion.
  1224. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true);
  1225. if( !ctx->type.dataType.IsEqualExceptRefAndConst(param) )
  1226. {
  1227. asCString str;
  1228. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), param.Format().AddressOf());
  1229. Error(str, node);
  1230. ctx->type.Set(param);
  1231. return -1;
  1232. }
  1233. // The compiler must guarantee that the object stays alive during the execution
  1234. // of the function, and it must also guarantee that the value isn't modified by
  1235. // the function.
  1236. // If the argument is a temporary local variable then it is safe to be passed to
  1237. // the function as it is, since the local variable will stay alive, and since it
  1238. // is temporary there is no side effect if the function modifies it.
  1239. // If the parameter is read-only and therefor guaranteed not to be modified by the
  1240. // function, then it is enough that the variable is local to guarantee the lifetime.
  1241. if( !ctx->type.isTemporary && !(param.IsReadOnly() && ctx->type.isVariable) )
  1242. {
  1243. if( (ctx->type.dataType.GetObjectType()->flags & asOBJ_REF) && param.IsReadOnly() )
  1244. {
  1245. // If the object is a reference type, and the parameter is a const reference,
  1246. // then it is not necessary to make a copy of the object. The compiler just needs
  1247. // to hold a handle to guarantee the lifetime.
  1248. // Allocate a handle variable
  1249. dt.MakeHandle(true);
  1250. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1251. // Copy the handle
  1252. Dereference(ctx, true);
  1253. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1254. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  1255. ctx->bc.Instr(asBC_PopPtr);
  1256. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1257. // The type should be set to the param type instead of dt to guarantee
  1258. // that the expression keeps the correct type for variable ? args. Otherwise
  1259. // MoveArgsToStack will use the wrong bytecode to move the arg to the stack
  1260. ctx->type.SetVariable(param, offset, true);
  1261. }
  1262. else
  1263. {
  1264. // Allocate and initialize a temporary local object
  1265. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1266. CompileInitAsCopy(dt, offset, &ctx->bc, ctx, node, false);
  1267. // Push the object pointer on the stack
  1268. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1269. if( dt.IsObject() && !dt.IsObjectHandle() )
  1270. ctx->bc.Instr(asBC_RDSPtr);
  1271. // Set the resulting type
  1272. ctx->type.Set(dt);
  1273. ctx->type.isTemporary = true;
  1274. ctx->type.stackOffset = short(offset);
  1275. if( dt.IsObjectHandle() )
  1276. ctx->type.isExplicitHandle = true;
  1277. ctx->type.dataType.MakeReference(false);
  1278. if( paramType->IsReadOnly() )
  1279. ctx->type.dataType.MakeReadOnly(true);
  1280. }
  1281. }
  1282. }
  1283. else
  1284. {
  1285. // We must guarantee that the address to the value is on the stack
  1286. if( ctx->type.dataType.IsObject() &&
  1287. !ctx->type.dataType.IsObjectHandle() &&
  1288. ctx->type.dataType.IsReference() )
  1289. Dereference(ctx, true);
  1290. }
  1291. }
  1292. }
  1293. else if( refType == 2 ) // &out
  1294. {
  1295. // Add the type id as hidden arg if the parameter is a ? type
  1296. if( paramType->GetTokenType() == ttQuestion )
  1297. {
  1298. asCByteCode tmpBC(engine);
  1299. // Place the type id on the stack as a hidden parameter
  1300. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  1301. // Insert the code before the expression code
  1302. tmpBC.AddCode(&ctx->bc);
  1303. ctx->bc.AddCode(&tmpBC);
  1304. }
  1305. // Make sure the variable is not used in the expression
  1306. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1307. if( dt.IsPrimitive() )
  1308. {
  1309. ctx->type.SetVariable(dt, offset, true);
  1310. PushVariableOnStack(ctx, true);
  1311. }
  1312. else
  1313. {
  1314. // TODO: 2.28.1: Need to reserve variables, as the default constructor may need
  1315. // to allocate temporary variables to compute default args
  1316. // Allocate and construct the temporary object
  1317. asCByteCode tmpBC(engine);
  1318. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  1319. // Insert the code before the expression code
  1320. tmpBC.AddCode(&ctx->bc);
  1321. ctx->bc.AddCode(&tmpBC);
  1322. dt.MakeReference(!dt.IsObject() || dt.IsObjectHandle());
  1323. asCTypeInfo type;
  1324. type.Set(dt);
  1325. type.isTemporary = true;
  1326. type.stackOffset = (short)offset;
  1327. ctx->type = type;
  1328. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1329. if( dt.IsObject() && !dt.IsObjectHandle() )
  1330. ctx->bc.Instr(asBC_RDSPtr);
  1331. }
  1332. // After the function returns the temporary variable will
  1333. // be assigned to the expression, if it is a valid lvalue
  1334. }
  1335. else if( refType == asTM_INOUTREF )
  1336. {
  1337. ProcessPropertyGetAccessor(ctx, node);
  1338. // Add the type id as hidden arg if the parameter is a ? type
  1339. if( paramType->GetTokenType() == ttQuestion )
  1340. {
  1341. asCByteCode tmpBC(engine);
  1342. // Place the type id on the stack as a hidden parameter
  1343. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  1344. // Insert the code before the expression code
  1345. tmpBC.AddCode(&ctx->bc);
  1346. ctx->bc.AddCode(&tmpBC);
  1347. }
  1348. // Literal constants cannot be passed to inout ref arguments
  1349. if( !ctx->type.isVariable && ctx->type.isConstant )
  1350. {
  1351. // Unless unsafe references are turned on and the reference is const
  1352. if( param.IsReadOnly() && engine->ep.allowUnsafeReferences )
  1353. {
  1354. // Since the parameter is a const & make a copy.
  1355. ConvertToTempVariable(ctx);
  1356. ctx->type.dataType.MakeReadOnly(true);
  1357. }
  1358. else
  1359. {
  1360. Error(TXT_NOT_VALID_REFERENCE, node);
  1361. return -1;
  1362. }
  1363. }
  1364. // Perform implicit ref cast if necessary, but don't allow the implicit conversion to create new objects
  1365. if( ctx->type.dataType.IsObject() && ctx->type.dataType.GetObjectType() != dt.GetObjectType() )
  1366. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true, false);
  1367. // Only objects that support object handles
  1368. // can be guaranteed to be safe. Local variables are
  1369. // already safe, so there is no need to add an extra
  1370. // references
  1371. if( !engine->ep.allowUnsafeReferences &&
  1372. !ctx->type.isVariable &&
  1373. ctx->type.dataType.IsObject() &&
  1374. !ctx->type.dataType.IsObjectHandle() &&
  1375. ((ctx->type.dataType.GetBehaviour()->addref &&
  1376. ctx->type.dataType.GetBehaviour()->release) ||
  1377. (ctx->type.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) )
  1378. {
  1379. // Store a handle to the object as local variable
  1380. asSExprContext tmp(engine);
  1381. asCDataType dt = ctx->type.dataType;
  1382. dt.MakeHandle(true);
  1383. dt.MakeReference(false);
  1384. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1385. // Copy the handle
  1386. if( !ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReference() )
  1387. ctx->bc.Instr(asBC_RDSPtr);
  1388. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1389. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  1390. ctx->bc.Instr(asBC_PopPtr);
  1391. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1392. dt.MakeHandle(false);
  1393. dt.MakeReference(true);
  1394. // Release previous temporary variable stored in the context (if any)
  1395. if( ctx->type.isTemporary )
  1396. ReleaseTemporaryVariable(ctx->type.stackOffset, &ctx->bc);
  1397. ctx->type.SetVariable(dt, offset, true);
  1398. }
  1399. // Make sure the reference to the value is on the stack
  1400. // For objects, the reference needs to be dereferenced so the pointer on the stack is to the actual object
  1401. // For handles, the reference shouldn't be changed because the pointer on the stack should be to the handle
  1402. if( ctx->type.dataType.IsObject() && ctx->type.dataType.IsReference() && !param.IsObjectHandle() )
  1403. Dereference(ctx, true);
  1404. else if( ctx->type.isVariable && !ctx->type.dataType.IsObject() )
  1405. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  1406. else if( ctx->type.dataType.IsPrimitive() )
  1407. ctx->bc.Instr(asBC_PshRPtr);
  1408. else if( ctx->type.dataType.IsObjectHandle() && !ctx->type.dataType.IsReference() )
  1409. ImplicitConversion(ctx, param, node, asIC_IMPLICIT_CONV, true, false);
  1410. }
  1411. }
  1412. else
  1413. {
  1414. ProcessPropertyGetAccessor(ctx, node);
  1415. if( dt.IsPrimitive() )
  1416. {
  1417. IsVariableInitialized(&ctx->type, node);
  1418. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  1419. // Implicitly convert primitives to the parameter type
  1420. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  1421. if( ctx->type.isVariable )
  1422. {
  1423. PushVariableOnStack(ctx, dt.IsReference());
  1424. }
  1425. else if( ctx->type.isConstant )
  1426. {
  1427. ConvertToVariable(ctx);
  1428. PushVariableOnStack(ctx, dt.IsReference());
  1429. }
  1430. }
  1431. else
  1432. {
  1433. IsVariableInitialized(&ctx->type, node);
  1434. // Implicitly convert primitives to the parameter type
  1435. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  1436. // Was the conversion successful?
  1437. if( !ctx->type.dataType.IsEqualExceptRef(dt) )
  1438. {
  1439. asCString str;
  1440. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), dt.Format().AddressOf());
  1441. Error(str, node);
  1442. ctx->type.Set(dt);
  1443. return -1;
  1444. }
  1445. if( dt.IsObjectHandle() )
  1446. ctx->type.isExplicitHandle = true;
  1447. if( dt.IsObject() && !dt.IsNullHandle() )
  1448. {
  1449. if( !dt.IsReference() )
  1450. {
  1451. // Objects passed by value must be placed in temporary variables
  1452. // so that they are guaranteed to not be referenced anywhere else.
  1453. // The object must also be allocated on the heap, as the memory will
  1454. // be deleted by in as_callfunc_xxx.
  1455. // TODO: value on stack: How can we avoid this unnecessary allocation?
  1456. // Local variables doesn't need to be copied into
  1457. // a temp if we're already compiling an assignment
  1458. if( !isMakingCopy || !ctx->type.dataType.IsObjectHandle() || !ctx->type.isVariable )
  1459. PrepareTemporaryObject(node, ctx, true);
  1460. // The implicit conversion shouldn't convert the object to
  1461. // non-reference yet. It will be dereferenced just before the call.
  1462. // Otherwise the object might be missed by the exception handler.
  1463. dt.MakeReference(true);
  1464. }
  1465. else
  1466. {
  1467. // An object passed by reference should place the pointer to
  1468. // the object on the stack.
  1469. dt.MakeReference(false);
  1470. }
  1471. }
  1472. }
  1473. }
  1474. // Don't put any pointer on the stack yet
  1475. if( param.IsReference() || (param.IsObject() && !param.IsNullHandle()) )
  1476. {
  1477. // &inout parameter may leave the reference on the stack already
  1478. if( refType != 3 )
  1479. {
  1480. asASSERT( ctx->type.isVariable || ctx->type.isTemporary || isMakingCopy );
  1481. if( ctx->type.isVariable || ctx->type.isTemporary )
  1482. {
  1483. ctx->bc.Instr(asBC_PopPtr);
  1484. ctx->bc.InstrSHORT(asBC_VAR, ctx->type.stackOffset);
  1485. ProcessDeferredParams(ctx);
  1486. }
  1487. }
  1488. }
  1489. return 0;
  1490. }
  1491. void asCCompiler::PrepareFunctionCall(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args)
  1492. {
  1493. // When a match has been found, compile the final byte code using correct parameter types
  1494. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1495. // If the function being called is the opAssign or copy constructor for the same type
  1496. // as the argument, then we should avoid making temporary copy of the argument
  1497. bool makingCopy = false;
  1498. if( descr->parameterTypes.GetLength() == 1 &&
  1499. descr->parameterTypes[0].IsEqualExceptRefAndConst(args[0]->type.dataType) &&
  1500. ((descr->name == "opAssign" && descr->objectType && descr->objectType == args[0]->type.dataType.GetObjectType()) ||
  1501. (args[0]->type.dataType.GetObjectType() && descr->name == args[0]->type.dataType.GetObjectType()->name)) )
  1502. makingCopy = true;
  1503. // Add code for arguments
  1504. asSExprContext e(engine);
  1505. for( int n = (int)args.GetLength()-1; n >= 0; n-- )
  1506. {
  1507. // Make sure PrepareArgument doesn't use any variable that is already
  1508. // being used by any of the following argument expressions
  1509. int l = int(reservedVariables.GetLength());
  1510. for( int m = n-1; m >= 0; m-- )
  1511. args[m]->bc.GetVarsUsed(reservedVariables);
  1512. PrepareArgument2(&e, args[n], &descr->parameterTypes[n], true, descr->inOutFlags[n], makingCopy);
  1513. reservedVariables.SetLength(l);
  1514. }
  1515. bc->AddCode(&e.bc);
  1516. }
  1517. void asCCompiler::MoveArgsToStack(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args, bool addOneToOffset)
  1518. {
  1519. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1520. int offset = 0;
  1521. if( addOneToOffset )
  1522. offset += AS_PTR_SIZE;
  1523. // The address of where the return value should be stored is push on top of the arguments
  1524. if( descr->DoesReturnOnStack() )
  1525. offset += AS_PTR_SIZE;
  1526. #ifdef AS_DEBUG
  1527. // If the function being called is the opAssign or copy constructor for the same type
  1528. // as the argument, then we should avoid making temporary copy of the argument
  1529. bool makingCopy = false;
  1530. if( descr->parameterTypes.GetLength() == 1 &&
  1531. descr->parameterTypes[0].IsEqualExceptRefAndConst(args[0]->type.dataType) &&
  1532. ((descr->name == "opAssign" && descr->objectType && descr->objectType == args[0]->type.dataType.GetObjectType()) ||
  1533. (args[0]->type.dataType.GetObjectType() && descr->name == args[0]->type.dataType.GetObjectType()->name)) )
  1534. makingCopy = true;
  1535. #endif
  1536. // Move the objects that are sent by value to the stack just before the call
  1537. for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
  1538. {
  1539. if( descr->parameterTypes[n].IsReference() )
  1540. {
  1541. if( descr->parameterTypes[n].IsObject() && !descr->parameterTypes[n].IsObjectHandle() )
  1542. {
  1543. if( descr->inOutFlags[n] != asTM_INOUTREF )
  1544. {
  1545. #ifdef AS_DEBUG
  1546. asASSERT( args[n]->type.isVariable || args[n]->type.isTemporary || makingCopy );
  1547. #endif
  1548. if( (args[n]->type.isVariable || args[n]->type.isTemporary) )
  1549. {
  1550. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1551. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  1552. // as the value allocated on the stack is guaranteed to be safe
  1553. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1554. else
  1555. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1556. }
  1557. }
  1558. if( args[n]->type.dataType.IsObjectHandle() )
  1559. bc->InstrWORD(asBC_ChkNullS, (asWORD)offset);
  1560. }
  1561. else if( descr->inOutFlags[n] != asTM_INOUTREF )
  1562. {
  1563. if( descr->parameterTypes[n].GetTokenType() == ttQuestion &&
  1564. args[n]->type.dataType.IsObject() && !args[n]->type.dataType.IsObjectHandle() )
  1565. {
  1566. // Send the object as a reference to the object,
  1567. // and not to the variable holding the object
  1568. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1569. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  1570. // as the value allocated on the stack is guaranteed to be safe
  1571. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1572. else
  1573. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1574. }
  1575. else
  1576. {
  1577. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1578. }
  1579. }
  1580. }
  1581. else if( descr->parameterTypes[n].IsObject() )
  1582. {
  1583. // TODO: value on stack: What can we do to avoid this unnecessary allocation?
  1584. // The object must be allocated on the heap, because this memory will be deleted in as_callfunc_xxx
  1585. asASSERT(IsVariableOnHeap(args[n]->type.stackOffset));
  1586. bc->InstrWORD(asBC_GETOBJ, (asWORD)offset);
  1587. // The temporary variable must not be freed as it will no longer hold an object
  1588. DeallocateVariable(args[n]->type.stackOffset);
  1589. args[n]->type.isTemporary = false;
  1590. }
  1591. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  1592. }
  1593. }
  1594. int asCCompiler::CompileArgumentList(asCScriptNode *node, asCArray<asSExprContext*> &args, asCArray<asSNamedArgument> &namedArgs)
  1595. {
  1596. asASSERT(node->nodeType == snArgList);
  1597. // Count arguments
  1598. asCScriptNode *arg = node->firstChild;
  1599. int argCount = 0;
  1600. while( arg )
  1601. {
  1602. if( arg->nodeType != snNamedArgument )
  1603. argCount++;
  1604. arg = arg->next;
  1605. }
  1606. // Prepare the arrays
  1607. args.SetLength(argCount);
  1608. int n;
  1609. for( n = 0; n < argCount; n++ )
  1610. args[n] = 0;
  1611. n = argCount-1;
  1612. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1613. bool anyErrors = false, inPositionalArguments = false;
  1614. arg = node->lastChild;
  1615. while( arg )
  1616. {
  1617. asCScriptNode *asgNode = arg, *namedNode = 0;
  1618. if( asgNode->nodeType == snNamedArgument )
  1619. {
  1620. if( inPositionalArguments )
  1621. {
  1622. Error(TXT_POS_ARG_AFTER_NAMED_ARG, node);
  1623. return -1;
  1624. }
  1625. asgNode = arg->firstChild->next;
  1626. namedNode = arg->firstChild;
  1627. asASSERT( namedNode->nodeType == snIdentifier );
  1628. }
  1629. else
  1630. inPositionalArguments = true;
  1631. asSExprContext expr(engine);
  1632. int r = CompileAssignment(asgNode, &expr);
  1633. if( r < 0 ) anyErrors = true;
  1634. asSExprContext *ctx = asNEW(asSExprContext)(engine);
  1635. if( ctx == 0 )
  1636. {
  1637. // Out of memory
  1638. return -1;
  1639. }
  1640. MergeExprBytecodeAndType(ctx, &expr);
  1641. if( inPositionalArguments )
  1642. {
  1643. args[n] = ctx;
  1644. n--;
  1645. }
  1646. else
  1647. {
  1648. asSNamedArgument namedArg;
  1649. namedArg.name = asCString(&script->code[namedNode->tokenPos], namedNode->tokenLength);
  1650. namedArg.ctx = ctx;
  1651. // Error out when multiple arguments with the same name are passed
  1652. for( asUINT n = 0; n < namedArgs.GetLength(); ++n )
  1653. {
  1654. if( namedArgs[n].name == namedArg.name )
  1655. {
  1656. Error(TXT_DUPLICATE_NAMED_ARG, asgNode);
  1657. anyErrors = true;
  1658. break;
  1659. }
  1660. }
  1661. namedArgs.PushLast(namedArg);
  1662. }
  1663. arg = arg->prev;
  1664. }
  1665. return anyErrors ? -1 : 0;
  1666. }
  1667. int asCCompiler::CompileDefaultAndNamedArgs(asCScriptNode *node, asCArray<asSExprContext*> &args, int funcId, asCObjectType *objectType, asCArray<asSNamedArgument> *namedArgs)
  1668. {
  1669. asCScriptFunction *func = builder->GetFunctionDescription(funcId);
  1670. if( func == 0 || args.GetLength() >= (asUINT)func->GetParamCount() )
  1671. return 0;
  1672. // Make sure to use the real function for virtual functions
  1673. if( func->funcType == asFUNC_VIRTUAL )
  1674. {
  1675. asASSERT( objectType );
  1676. func = objectType->virtualFunctionTable[func->vfTableIdx];
  1677. }
  1678. // Make sure none of the variables used in the previous arguments are reused in the default arguments
  1679. bool anyErrors = false;
  1680. asCArray<int> varsUsed;
  1681. int explicitArgs = (int)args.GetLength();
  1682. for( int p = 0; p < explicitArgs; p++ )
  1683. args[p]->bc.GetVarsUsed(varsUsed);
  1684. // Make space for all the new arguments
  1685. args.SetLength(func->parameterTypes.GetLength());
  1686. for( asUINT c = explicitArgs; c < args.GetLength(); c++ )
  1687. args[c] = 0;
  1688. // Add the named arguments to the argument list in the right position
  1689. if( namedArgs )
  1690. {
  1691. for( asUINT n = 0; n < namedArgs->GetLength(); ++n )
  1692. {
  1693. asSNamedArgument &named = (*namedArgs)[n];
  1694. named.ctx->bc.GetVarsUsed(varsUsed);
  1695. //Find the right spot to put it in
  1696. asUINT index = asUINT(-1);
  1697. for( asUINT j = 0; j < func->parameterTypes.GetLength(); ++j )
  1698. {
  1699. if( func->parameterNames[j] == (*namedArgs)[n].name )
  1700. {
  1701. index = j;
  1702. break;
  1703. }
  1704. }
  1705. asASSERT( index < args.GetLength() );
  1706. args[index] = named.ctx;
  1707. named.ctx = 0;
  1708. }
  1709. }
  1710. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1711. for( int n = (int)func->parameterTypes.GetLength() - 1; n >= explicitArgs; n-- )
  1712. {
  1713. if( args[n] != 0 ) continue;
  1714. if( func->defaultArgs[n] == 0 ) { anyErrors = true; continue; }
  1715. // Parse the default arg string
  1716. asCParser parser(builder);
  1717. asCScriptCode code;
  1718. code.SetCode("default arg", func->defaultArgs[n]->AddressOf(), false);
  1719. int r = parser.ParseExpression(&code);
  1720. if( r < 0 )
  1721. {
  1722. asCString msg;
  1723. msg.Format(TXT_FAILED_TO_COMPILE_DEF_ARG_d_IN_FUNC_s, n, func->GetDeclaration());
  1724. Error(msg, node);
  1725. anyErrors = true;
  1726. continue;
  1727. }
  1728. asCScriptNode *arg = parser.GetScriptNode();
  1729. // Temporarily set the script code to the default arg expression
  1730. asCScriptCode *origScript = script;
  1731. script = &code;
  1732. // Don't allow the expression to access local variables
  1733. // TODO: namespace: The default arg should see the symbols declared in the same scope as the function that is called
  1734. isCompilingDefaultArg = true;
  1735. asSExprContext expr(engine);
  1736. r = CompileExpression(arg, &expr);
  1737. // Don't allow address of class method
  1738. if( expr.methodName != "" )
  1739. {
  1740. // TODO: Improve error message
  1741. Error(TXT_DEF_ARG_TYPE_DOESNT_MATCH, arg);
  1742. r = -1;
  1743. }
  1744. // Make sure the expression can be implicitly converted to the parameter type
  1745. if( r >= 0 )
  1746. {
  1747. asCArray<int> funcs;
  1748. funcs.PushLast(func->id);
  1749. asCArray<asSOverloadCandidate> matches;
  1750. if( MatchArgument(funcs, matches, &expr, n) == 0 )
  1751. {
  1752. Error(TXT_DEF_ARG_TYPE_DOESNT_MATCH, arg);
  1753. r = -1;
  1754. }
  1755. }
  1756. isCompilingDefaultArg = false;
  1757. script = origScript;
  1758. if( r < 0 )
  1759. {
  1760. asCString msg;
  1761. msg.Format(TXT_FAILED_TO_COMPILE_DEF_ARG_d_IN_FUNC_s, n, func->GetDeclaration());
  1762. Error(msg, node);
  1763. anyErrors = true;
  1764. continue;
  1765. }
  1766. args[n] = asNEW(asSExprContext)(engine);
  1767. if( args[n] == 0 )
  1768. {
  1769. // Out of memory
  1770. return -1;
  1771. }
  1772. MergeExprBytecodeAndType(args[n], &expr);
  1773. // Make sure the default arg expression doesn't end up
  1774. // with a variable that is used in a previous expression
  1775. if( args[n]->type.isVariable )
  1776. {
  1777. int offset = args[n]->type.stackOffset;
  1778. if( varsUsed.Exists(offset) )
  1779. {
  1780. // Release the current temporary variable
  1781. ReleaseTemporaryVariable(args[n]->type, 0);
  1782. asCDataType dt = args[n]->type.dataType;
  1783. dt.MakeReference(false);
  1784. // Reserve all variables already used in the expression so none of them will be used
  1785. asCArray<int> used;
  1786. args[n]->bc.GetVarsUsed(used);
  1787. size_t prevReserved = reservedVariables.GetLength();
  1788. reservedVariables.Concatenate(used);
  1789. int newOffset = AllocateVariable(dt, true, IsVariableOnHeap(offset));
  1790. asASSERT( IsVariableOnHeap(offset) == IsVariableOnHeap(newOffset) );
  1791. reservedVariables.SetLength(prevReserved);
  1792. // Replace the variable in the expression
  1793. args[n]->bc.ExchangeVar(offset, newOffset);
  1794. args[n]->type.stackOffset = (short)newOffset;
  1795. args[n]->type.isTemporary = true;
  1796. args[n]->type.isVariable = true;
  1797. }
  1798. }
  1799. }
  1800. return anyErrors ? -1 : 0;
  1801. }
  1802. asUINT asCCompiler::MatchFunctions(asCArray<int> &funcs, asCArray<asSExprContext*> &args, asCScriptNode *node, const char *name, asCArray<asSNamedArgument> *namedArgs, asCObjectType *objectType, bool isConstMethod, bool silent, bool allowObjectConstruct, const asCString &scope)
  1803. {
  1804. asCArray<int> origFuncs = funcs; // Keep the original list for error message
  1805. asUINT cost = 0;
  1806. asUINT n;
  1807. if( funcs.GetLength() > 0 )
  1808. {
  1809. // Check the number of parameters in the found functions
  1810. asUINT totalArgs = (asUINT)args.GetLength();
  1811. if( namedArgs != 0 )
  1812. totalArgs += (asUINT)namedArgs->GetLength();
  1813. for( n = 0; n < funcs.GetLength(); ++n )
  1814. {
  1815. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  1816. if( desc->parameterTypes.GetLength() != totalArgs )
  1817. {
  1818. bool noMatch = true;
  1819. if( totalArgs < desc->parameterTypes.GetLength() )
  1820. {
  1821. // For virtual functions, the default args are defined in the real function of the object
  1822. if( desc->funcType == asFUNC_VIRTUAL )
  1823. desc = objectType->virtualFunctionTable[desc->vfTableIdx];
  1824. // Count the number of default args
  1825. asUINT defaultArgs = 0;
  1826. for( asUINT d = 0; d < desc->defaultArgs.GetLength(); d++ )
  1827. if( desc->defaultArgs[d] )
  1828. defaultArgs++;
  1829. if( totalArgs >= desc->parameterTypes.GetLength() - defaultArgs )
  1830. noMatch = false;
  1831. }
  1832. if( noMatch )
  1833. {
  1834. // remove it from the list
  1835. if( n == funcs.GetLength()-1 )
  1836. funcs.PopLast();
  1837. else
  1838. funcs[n] = funcs.PopLast();
  1839. n--;
  1840. }
  1841. }
  1842. }
  1843. // Match functions with the parameters, and discard those that do not match
  1844. asCArray<asSOverloadCandidate> matchingFuncs;
  1845. matchingFuncs.SetLengthNoConstruct( funcs.GetLength() );
  1846. for ( n = 0; n < funcs.GetLength(); ++n )
  1847. {
  1848. matchingFuncs[n].funcId = funcs[n];
  1849. matchingFuncs[n].cost = 0;
  1850. }
  1851. // Match positionally passed arguments
  1852. for( n = 0; n < args.GetLength(); ++n )
  1853. {
  1854. asCArray<asSOverloadCandidate> tempFuncs;
  1855. MatchArgument(funcs, tempFuncs, args[n], n, allowObjectConstruct);
  1856. // Intersect the found functions with the list of matching functions
  1857. for( asUINT f = 0; f < matchingFuncs.GetLength(); f++ )
  1858. {
  1859. asUINT c;
  1860. for( c = 0; c < tempFuncs.GetLength(); c++ )
  1861. {
  1862. if( matchingFuncs[f].funcId == tempFuncs[c].funcId )
  1863. {
  1864. // Sum argument cost
  1865. matchingFuncs[f].cost += tempFuncs[c].cost;
  1866. break;
  1867. } // End if match
  1868. }
  1869. // Was the function a match?
  1870. if( c == tempFuncs.GetLength() )
  1871. {
  1872. // No, remove it from the list
  1873. if( f == matchingFuncs.GetLength()-1 )
  1874. matchingFuncs.PopLast();
  1875. else
  1876. matchingFuncs[f] = matchingFuncs.PopLast();
  1877. f--;
  1878. }
  1879. }
  1880. }
  1881. // Match named arguments
  1882. if( namedArgs != 0 )
  1883. {
  1884. for( asUINT i = 0; i < matchingFuncs.GetLength(); ++i )
  1885. {
  1886. asCScriptFunction *desc = builder->GetFunctionDescription(matchingFuncs[i].funcId);
  1887. if( desc->funcType == asFUNC_VIRTUAL )
  1888. desc = objectType->virtualFunctionTable[desc->vfTableIdx];
  1889. //Match every named argument to an argument in the function
  1890. for( n = 0; n < namedArgs->GetLength(); ++n )
  1891. (*namedArgs)[n].match = asUINT(-1);
  1892. bool matchedAll = true;
  1893. for( asUINT j = 0; j < desc->parameterTypes.GetLength(); ++j )
  1894. {
  1895. asUINT match = asUINT(-1);
  1896. for( n = 0; n < namedArgs->GetLength(); ++n )
  1897. {
  1898. asSNamedArgument &namedArg = (*namedArgs)[n];
  1899. if( desc->parameterNames[j] == namedArg.name )
  1900. {
  1901. namedArg.match = j;
  1902. match = n;
  1903. break;
  1904. }
  1905. }
  1906. // Check that every position is filled somehow
  1907. if( j >= args.GetLength() )
  1908. {
  1909. if( match == asUINT(-1) && !desc->defaultArgs[j] )
  1910. {
  1911. // No argument was found for this, and there is no
  1912. // default, so it doesn't work.
  1913. matchedAll = false;
  1914. break;
  1915. }
  1916. }
  1917. else
  1918. {
  1919. if( match != asUINT(-1) )
  1920. {
  1921. // Can't name an argument that was already passed
  1922. matchedAll = false;
  1923. break;
  1924. }
  1925. }
  1926. }
  1927. //Check that every named argument was matched
  1928. if( matchedAll )
  1929. {
  1930. for( n = 0; n < namedArgs->GetLength(); ++n )
  1931. {
  1932. asSNamedArgument &named = (*namedArgs)[n];
  1933. if( named.match == asUINT(-1) )
  1934. {
  1935. matchedAll = false;
  1936. break;
  1937. }
  1938. // Add to the cost
  1939. asUINT cost = MatchArgument(desc, named.ctx, named.match, allowObjectConstruct);
  1940. if( cost == asUINT(-1) )
  1941. {
  1942. matchedAll = false;
  1943. break;
  1944. }
  1945. matchingFuncs[i].cost += cost;
  1946. }
  1947. }
  1948. if( !matchedAll )
  1949. {
  1950. // Remove the function, we didn't match all the arguments.
  1951. if( i == matchingFuncs.GetLength()-1 )
  1952. matchingFuncs.PopLast();
  1953. else
  1954. matchingFuncs[i] = matchingFuncs.PopLast();
  1955. i--;
  1956. }
  1957. }
  1958. }
  1959. // Select the overload(s) with the lowest overall cost
  1960. funcs.SetLength(0);
  1961. asUINT bestCost = asUINT(-1);
  1962. for( n = 0; n < matchingFuncs.GetLength(); ++n )
  1963. {
  1964. cost = matchingFuncs[n].cost;
  1965. if( cost < bestCost )
  1966. {
  1967. funcs.SetLength(0);
  1968. bestCost = cost;
  1969. }
  1970. if( cost == bestCost )
  1971. funcs.PushLast( matchingFuncs[n].funcId );
  1972. }
  1973. // Cost returned is equivalent to the best cost discovered
  1974. cost = bestCost;
  1975. }
  1976. if( !isConstMethod )
  1977. FilterConst(funcs);
  1978. if( funcs.GetLength() != 1 && !silent )
  1979. {
  1980. // Build a readable string of the function with parameter types
  1981. bool attemptsPassingClassMethod = false;
  1982. asCString str;
  1983. if( scope != "" )
  1984. {
  1985. if( scope == "::" )
  1986. str = scope;
  1987. else
  1988. str = scope + "::";
  1989. }
  1990. str += name;
  1991. str += "(";
  1992. for( n = 0; n < args.GetLength(); n++ )
  1993. {
  1994. if( n > 0 )
  1995. str += ", ";
  1996. if( args[n]->methodName != "" )
  1997. {
  1998. if( args[n]->IsClassMethod() )
  1999. {
  2000. attemptsPassingClassMethod = true;
  2001. str += args[n]->type.dataType.GetObjectType()->GetName();
  2002. str += "::";
  2003. }
  2004. str += args[n]->methodName;
  2005. }
  2006. else
  2007. str += args[n]->type.dataType.Format();
  2008. }
  2009. if( namedArgs != 0 )
  2010. {
  2011. for( n = 0; n < namedArgs->GetLength(); n++ )
  2012. {
  2013. if( n > 0 || args.GetLength() )
  2014. str += ", ";
  2015. asSNamedArgument &named = (*namedArgs)[n];
  2016. str += named.name;
  2017. str += "=";
  2018. if( named.ctx->methodName != "" )
  2019. str += named.ctx->methodName;
  2020. else
  2021. str += named.ctx->type.dataType.Format();
  2022. }
  2023. }
  2024. str += ")";
  2025. if( isConstMethod )
  2026. str += " const";
  2027. if( objectType && scope == "" )
  2028. str = objectType->name + "::" + str;
  2029. if( funcs.GetLength() == 0 )
  2030. {
  2031. str.Format(TXT_NO_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  2032. Error(str, node);
  2033. if( attemptsPassingClassMethod )
  2034. {
  2035. // Class methods must use delegate objects
  2036. Error(TXT_CANNOT_PASS_CLASS_METHOD_AS_ARG, node);
  2037. }
  2038. else
  2039. {
  2040. // Print the list of candidates
  2041. if( origFuncs.GetLength() > 0 )
  2042. {
  2043. int r = 0, c = 0;
  2044. asASSERT( node );
  2045. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2046. builder->WriteInfo(script->name.AddressOf(), TXT_CANDIDATES_ARE, r, c, false);
  2047. PrintMatchingFuncs(origFuncs, node, objectType);
  2048. }
  2049. }
  2050. }
  2051. else
  2052. {
  2053. asASSERT( attemptsPassingClassMethod == false );
  2054. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  2055. Error(str, node);
  2056. PrintMatchingFuncs(funcs, node, objectType);
  2057. }
  2058. }
  2059. return cost;
  2060. }
  2061. bool asCCompiler::CompileAutoType(asCDataType &type, asSExprContext &compiledCtx, asCScriptNode *node, asCScriptNode *errNode)
  2062. {
  2063. if( node && node->nodeType == snAssignment )
  2064. {
  2065. int r = CompileAssignment(node, &compiledCtx);
  2066. if( r >= 0 )
  2067. {
  2068. asCDataType newType = compiledCtx.type.dataType;
  2069. bool success = true;
  2070. // Handle const qualifier on auto
  2071. if( type.IsReadOnly() )
  2072. newType.MakeReadOnly(true);
  2073. else if( newType.IsPrimitive() )
  2074. newType.MakeReadOnly(false);
  2075. // Handle reference/value stuff
  2076. newType.MakeReference(false);
  2077. if( !newType.IsObjectHandle() )
  2078. {
  2079. // We got a value object or an object reference.
  2080. // Turn the variable into a handle if specified
  2081. // as auto@, otherwise make it a 'value'.
  2082. if( type.IsHandleToAuto() )
  2083. {
  2084. if( newType.MakeHandle(true) < 0 )
  2085. {
  2086. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, errNode);
  2087. success = false;
  2088. }
  2089. }
  2090. }
  2091. if(success)
  2092. type = newType;
  2093. else
  2094. type = asCDataType::CreatePrimitive(ttInt, false);
  2095. return true;
  2096. }
  2097. return false;
  2098. }
  2099. else
  2100. {
  2101. Error(TXT_CANNOT_RESOLVE_AUTO, errNode);
  2102. type = asCDataType::CreatePrimitive(ttInt, false);
  2103. return false;
  2104. }
  2105. }
  2106. void asCCompiler::CompileDeclaration(asCScriptNode *decl, asCByteCode *bc)
  2107. {
  2108. // Get the data type
  2109. asCDataType type = builder->CreateDataTypeFromNode(decl->firstChild, script, outFunc->nameSpace);
  2110. // Declare all variables in this declaration
  2111. asCScriptNode *node = decl->firstChild->next;
  2112. while( node )
  2113. {
  2114. // If this is an auto type, we have to compile the assignment now to figure out the type
  2115. asSExprContext compiledCtx(engine);
  2116. bool preCompiled = false;
  2117. if( type.IsAuto() )
  2118. preCompiled = CompileAutoType(type, compiledCtx, node->next, node);
  2119. // Is the type allowed?
  2120. if( !type.CanBeInstanciated() )
  2121. {
  2122. asCString str;
  2123. // TODO: Change to "'type' cannot be declared as variable"
  2124. str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format().AddressOf());
  2125. Error(str, node);
  2126. // Use int instead to avoid further problems
  2127. type = asCDataType::CreatePrimitive(ttInt, false);
  2128. }
  2129. // A shared object may not declare variables of non-shared types
  2130. if( outFunc->IsShared() )
  2131. {
  2132. asCObjectType *ot = type.GetObjectType();
  2133. if( ot && !ot->IsShared() )
  2134. {
  2135. asCString msg;
  2136. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  2137. Error(msg, decl);
  2138. }
  2139. }
  2140. // Get the name of the identifier
  2141. asCString name(&script->code[node->tokenPos], node->tokenLength);
  2142. // Verify that the name isn't used by a dynamic data type
  2143. // TODO: Must check against registered funcdefs too
  2144. if( engine->GetRegisteredObjectType(name.AddressOf(), outFunc->nameSpace) != 0 )
  2145. {
  2146. asCString str;
  2147. str.Format(TXT_ILLEGAL_VARIABLE_NAME_s, name.AddressOf());
  2148. Error(str, node);
  2149. }
  2150. int offset = AllocateVariable(type, false);
  2151. if( variables->DeclareVariable(name.AddressOf(), type, offset, IsVariableOnHeap(offset)) < 0 )
  2152. {
  2153. // TODO: It might be an out-of-memory too
  2154. asCString str;
  2155. str.Format(TXT_s_ALREADY_DECLARED, name.AddressOf());
  2156. Error(str, node);
  2157. // Don't continue after this error, as it will just
  2158. // lead to more errors that are likely false
  2159. return;
  2160. }
  2161. // Add marker that the variable has been declared
  2162. bc->VarDecl((int)outFunc->scriptData->variables.GetLength());
  2163. outFunc->AddVariable(name, type, offset);
  2164. // Keep the node for the variable decl
  2165. asCScriptNode *varNode = node;
  2166. node = node->next;
  2167. if( node == 0 || node->nodeType == snIdentifier )
  2168. {
  2169. // Initialize with default constructor
  2170. CompileInitialization(0, bc, type, varNode, offset, 0, 0);
  2171. }
  2172. else
  2173. {
  2174. // Compile the initialization expression
  2175. asQWORD constantValue = 0;
  2176. if( CompileInitialization(node, bc, type, varNode, offset, &constantValue, 0, preCompiled ? &compiledCtx : 0) )
  2177. {
  2178. // Check if the variable should be marked as pure constant
  2179. if( type.IsPrimitive() && type.IsReadOnly() )
  2180. {
  2181. sVariable *v = variables->GetVariable(name.AddressOf());
  2182. v->isPureConstant = true;
  2183. v->constantValue = constantValue;
  2184. }
  2185. }
  2186. node = node->next;
  2187. }
  2188. }
  2189. bc->OptimizeLocally(tempVariableOffsets);
  2190. }
  2191. // Returns true if the initialization expression is a constant expression
  2192. bool asCCompiler::CompileInitialization(asCScriptNode *node, asCByteCode *bc, asCDataType &type, asCScriptNode *errNode, int offset, asQWORD *constantValue, int isVarGlobOrMem, asSExprContext *preCompiled)
  2193. {
  2194. bool isConstantExpression = false;
  2195. if( node && node->nodeType == snArgList )
  2196. {
  2197. // Make sure it is an object and not a handle
  2198. if( type.GetObjectType() == 0 || type.IsObjectHandle() )
  2199. {
  2200. Error(TXT_MUST_BE_OBJECT, node);
  2201. }
  2202. else
  2203. {
  2204. // Compile the arguments
  2205. asCArray<asSExprContext *> args;
  2206. asCArray<asSNamedArgument> namedArgs;
  2207. if( CompileArgumentList(node, args, namedArgs) >= 0 )
  2208. {
  2209. // Find all constructors
  2210. asCArray<int> funcs;
  2211. asSTypeBehaviour *beh = type.GetBehaviour();
  2212. if( beh )
  2213. {
  2214. if( type.GetObjectType()->flags & asOBJ_REF )
  2215. funcs = beh->factories;
  2216. else
  2217. funcs = beh->constructors;
  2218. }
  2219. asCString str = type.Format();
  2220. MatchFunctions(funcs, args, node, str.AddressOf(), &namedArgs);
  2221. if( funcs.GetLength() == 1 )
  2222. {
  2223. // Add the default values for arguments not explicitly supplied
  2224. int r = CompileDefaultAndNamedArgs(node, args, funcs[0], type.GetObjectType(), &namedArgs);
  2225. if( r == asSUCCESS )
  2226. {
  2227. asSExprContext ctx(engine);
  2228. if( type.GetObjectType() && (type.GetObjectType()->flags & asOBJ_REF) )
  2229. {
  2230. if( isVarGlobOrMem == 0 )
  2231. MakeFunctionCall(&ctx, funcs[0], 0, args, node, true, offset);
  2232. else
  2233. {
  2234. MakeFunctionCall(&ctx, funcs[0], 0, args, node);
  2235. ctx.bc.Instr(asBC_RDSPtr);
  2236. if( isVarGlobOrMem == 1 )
  2237. {
  2238. // Store the returned handle in the global variable
  2239. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  2240. }
  2241. else
  2242. {
  2243. // Store the returned handle in the member
  2244. ctx.bc.InstrSHORT(asBC_PSF, 0);
  2245. ctx.bc.Instr(asBC_RDSPtr);
  2246. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2247. }
  2248. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  2249. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  2250. }
  2251. // Pop the reference left by the function call
  2252. ctx.bc.Instr(asBC_PopPtr);
  2253. }
  2254. else
  2255. {
  2256. bool onHeap = false;
  2257. if( isVarGlobOrMem == 0 )
  2258. {
  2259. // When the object is allocated on the heap, the address where the
  2260. // reference will be stored must be pushed on the stack before the
  2261. // arguments. This reference on the stack is safe, even if the script
  2262. // is suspended during the evaluation of the arguments.
  2263. onHeap = IsVariableOnHeap(offset);
  2264. if( onHeap )
  2265. ctx.bc.InstrSHORT(asBC_PSF, (short)offset);
  2266. }
  2267. else if( isVarGlobOrMem == 1 )
  2268. {
  2269. // Push the address of the location where the variable will be stored on the stack.
  2270. // This reference is safe, because the addresses of the global variables cannot change.
  2271. onHeap = true;
  2272. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  2273. }
  2274. else
  2275. {
  2276. // Value types may be allocated inline if they are POD types
  2277. onHeap = !type.IsObject() || type.IsReference() || (type.GetObjectType()->flags & asOBJ_REF);
  2278. if( onHeap )
  2279. {
  2280. ctx.bc.InstrSHORT(asBC_PSF, 0);
  2281. ctx.bc.Instr(asBC_RDSPtr);
  2282. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2283. }
  2284. }
  2285. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  2286. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  2287. // When the object is allocated on the stack, the address to the
  2288. // object is pushed on the stack after the arguments as the object pointer
  2289. if( !onHeap )
  2290. {
  2291. if( isVarGlobOrMem == 2 )
  2292. {
  2293. ctx.bc.InstrSHORT(asBC_PSF, 0);
  2294. ctx.bc.Instr(asBC_RDSPtr);
  2295. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2296. }
  2297. else
  2298. {
  2299. ctx.bc.InstrSHORT(asBC_PSF, (short)offset);
  2300. }
  2301. }
  2302. PerformFunctionCall(funcs[0], &ctx, onHeap, &args, type.GetObjectType());
  2303. if( isVarGlobOrMem == 0 )
  2304. {
  2305. // Mark the object in the local variable as initialized
  2306. ctx.bc.ObjInfo(offset, asOBJ_INIT);
  2307. }
  2308. }
  2309. bc->AddCode(&ctx.bc);
  2310. }
  2311. }
  2312. }
  2313. // Cleanup
  2314. for( asUINT n = 0; n < args.GetLength(); n++ )
  2315. if( args[n] )
  2316. {
  2317. asDELETE(args[n],asSExprContext);
  2318. }
  2319. for( asUINT n = 0; n < namedArgs.GetLength(); n++ )
  2320. if( namedArgs[n].ctx )
  2321. {
  2322. asDELETE(namedArgs[n].ctx,asSExprContext);
  2323. }
  2324. }
  2325. }
  2326. else if( node && node->nodeType == snInitList )
  2327. {
  2328. asCTypeInfo ti;
  2329. ti.Set(type);
  2330. ti.isVariable = (isVarGlobOrMem == 0);
  2331. ti.isTemporary = false;
  2332. ti.stackOffset = (short)offset;
  2333. ti.isLValue = true;
  2334. CompileInitList(&ti, node, bc, isVarGlobOrMem);
  2335. }
  2336. else if( node && node->nodeType == snAssignment )
  2337. {
  2338. asSExprContext ctx(engine);
  2339. // TODO: copy: Here we should look for the best matching constructor, instead of
  2340. // just the copy constructor. Only if no appropriate constructor is
  2341. // available should the assignment operator be used.
  2342. // Compile the expression
  2343. asSExprContext newExpr(engine);
  2344. asSExprContext* expr;
  2345. int r = 0;
  2346. if( preCompiled )
  2347. {
  2348. expr = preCompiled;
  2349. }
  2350. else
  2351. {
  2352. expr = &newExpr;
  2353. r = CompileAssignment(node, expr);
  2354. }
  2355. // Call the default constructor here
  2356. if( isVarGlobOrMem == 0 )
  2357. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), &ctx.bc, errNode);
  2358. else if( isVarGlobOrMem == 1 )
  2359. CallDefaultConstructor(type, offset, true, &ctx.bc, errNode, isVarGlobOrMem);
  2360. else if( isVarGlobOrMem == 2 )
  2361. CallDefaultConstructor(type, offset, type.IsReference(), &ctx.bc, errNode, isVarGlobOrMem);
  2362. if( r >= 0 )
  2363. {
  2364. if( type.IsPrimitive() )
  2365. {
  2366. if( type.IsReadOnly() && expr->type.isConstant )
  2367. {
  2368. ImplicitConversion(expr, type, node, asIC_IMPLICIT_CONV);
  2369. // Tell caller that the expression is a constant so it can mark the variable as pure constant
  2370. isConstantExpression = true;
  2371. *constantValue = expr->type.qwordValue;
  2372. }
  2373. asSExprContext lctx(engine);
  2374. if( isVarGlobOrMem == 0 )
  2375. lctx.type.SetVariable(type, offset, false);
  2376. else if( isVarGlobOrMem == 1 )
  2377. {
  2378. lctx.type.Set(type);
  2379. lctx.type.dataType.MakeReference(true);
  2380. // If it is an enum value, i.e. offset is negative, that is being compiled then
  2381. // we skip this as the bytecode won't be used anyway, only the constant value
  2382. if( offset >= 0 )
  2383. lctx.bc.InstrPTR(asBC_LDG, engine->globalProperties[offset]->GetAddressOfValue());
  2384. }
  2385. else
  2386. {
  2387. asASSERT( isVarGlobOrMem == 2 );
  2388. lctx.type.Set(type);
  2389. lctx.type.dataType.MakeReference(true);
  2390. // Load the reference of the primitive member into the register
  2391. lctx.bc.InstrSHORT(asBC_PSF, 0);
  2392. lctx.bc.Instr(asBC_RDSPtr);
  2393. lctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2394. lctx.bc.Instr(asBC_PopRPtr);
  2395. }
  2396. lctx.type.dataType.MakeReadOnly(false);
  2397. lctx.type.isLValue = true;
  2398. DoAssignment(&ctx, &lctx, expr, node, node, ttAssignment, node);
  2399. ProcessDeferredParams(&ctx);
  2400. }
  2401. else
  2402. {
  2403. // TODO: runtime optimize: Here we should look for the best matching constructor, instead of
  2404. // just the copy constructor. Only if no appropriate constructor is
  2405. // available should the assignment operator be used.
  2406. asSExprContext lexpr(engine);
  2407. lexpr.type.Set(type);
  2408. if( isVarGlobOrMem == 0 )
  2409. lexpr.type.dataType.MakeReference(IsVariableOnHeap(offset));
  2410. else if( isVarGlobOrMem == 1 )
  2411. lexpr.type.dataType.MakeReference(true);
  2412. else if( isVarGlobOrMem == 2 )
  2413. {
  2414. if( !lexpr.type.dataType.IsObject() || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_REF) )
  2415. lexpr.type.dataType.MakeReference(true);
  2416. }
  2417. // Allow initialization of constant variables
  2418. lexpr.type.dataType.MakeReadOnly(false);
  2419. if( type.IsObjectHandle() )
  2420. lexpr.type.isExplicitHandle = true;
  2421. if( isVarGlobOrMem == 0 )
  2422. {
  2423. lexpr.bc.InstrSHORT(asBC_PSF, (short)offset);
  2424. lexpr.type.stackOffset = (short)offset;
  2425. lexpr.type.isVariable = true;
  2426. }
  2427. else if( isVarGlobOrMem == 1 )
  2428. {
  2429. lexpr.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  2430. }
  2431. else
  2432. {
  2433. lexpr.bc.InstrSHORT(asBC_PSF, 0);
  2434. lexpr.bc.Instr(asBC_RDSPtr);
  2435. lexpr.bc.InstrSHORT_DW(asBC_ADDSi, (short)offset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2436. lexpr.type.stackOffset = -1;
  2437. }
  2438. lexpr.type.isLValue = true;
  2439. // If left expression resolves into a registered type
  2440. // check if the assignment operator is overloaded, and check
  2441. // the type of the right hand expression. If none is found
  2442. // the default action is a direct copy if it is the same type
  2443. // and a simple assignment.
  2444. bool assigned = false;
  2445. // Even though an ASHANDLE can be an explicit handle the overloaded operator needs to be called
  2446. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  2447. {
  2448. bool useHndlAssign = lexpr.type.dataType.IsHandleToAsHandleType();
  2449. assigned = CompileOverloadedDualOperator(node, &lexpr, expr, &ctx, useHndlAssign);
  2450. if( assigned )
  2451. {
  2452. // Pop the resulting value
  2453. if( !ctx.type.dataType.IsPrimitive() )
  2454. ctx.bc.Instr(asBC_PopPtr);
  2455. // Release the argument
  2456. ProcessDeferredParams(&ctx);
  2457. // Release temporary variable that may be allocated by the overloaded operator
  2458. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  2459. }
  2460. }
  2461. if( !assigned )
  2462. {
  2463. PrepareForAssignment(&lexpr.type.dataType, expr, node, false);
  2464. // If the expression is constant and the variable also is constant
  2465. // then mark the variable as pure constant. This will allow the compiler
  2466. // to optimize expressions with this variable.
  2467. if( type.IsReadOnly() && expr->type.isConstant )
  2468. {
  2469. isConstantExpression = true;
  2470. *constantValue = expr->type.qwordValue;
  2471. }
  2472. // Add expression code to bytecode
  2473. MergeExprBytecode(&ctx, expr);
  2474. // Add byte code for storing value of expression in variable
  2475. ctx.bc.AddCode(&lexpr.bc);
  2476. PerformAssignment(&lexpr.type, &expr->type, &ctx.bc, errNode);
  2477. // Release temporary variables used by expression
  2478. ReleaseTemporaryVariable(expr->type, &ctx.bc);
  2479. ctx.bc.Instr(asBC_PopPtr);
  2480. ProcessDeferredParams(&ctx);
  2481. }
  2482. }
  2483. }
  2484. bc->AddCode(&ctx.bc);
  2485. }
  2486. else
  2487. {
  2488. asASSERT( node == 0 );
  2489. // Call the default constructor here, as no explicit initialization is done
  2490. if( isVarGlobOrMem == 0 )
  2491. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), bc, errNode);
  2492. else if( isVarGlobOrMem == 1 )
  2493. CallDefaultConstructor(type, offset, true, bc, errNode, isVarGlobOrMem);
  2494. else if( isVarGlobOrMem == 2 )
  2495. {
  2496. if( !type.IsObject() || type.IsReference() || (type.GetObjectType()->flags & asOBJ_REF) )
  2497. CallDefaultConstructor(type, offset, true, bc, errNode, isVarGlobOrMem);
  2498. else
  2499. CallDefaultConstructor(type, offset, false, bc, errNode, isVarGlobOrMem);
  2500. }
  2501. }
  2502. return isConstantExpression;
  2503. }
  2504. void asCCompiler::CompileInitList(asCTypeInfo *var, asCScriptNode *node, asCByteCode *bc, int isVarGlobOrMem)
  2505. {
  2506. // Check if the type supports initialization lists
  2507. if( var->dataType.GetObjectType() == 0 ||
  2508. var->dataType.GetBehaviour()->listFactory == 0 ||
  2509. var->dataType.IsObjectHandle() )
  2510. {
  2511. asCString str;
  2512. str.Format(TXT_INIT_LIST_CANNOT_BE_USED_WITH_s, var->dataType.Format().AddressOf());
  2513. Error(str, node);
  2514. return;
  2515. }
  2516. // Construct the buffer with the elements
  2517. // Find the list factory
  2518. int funcId = var->dataType.GetBehaviour()->listFactory;
  2519. asASSERT( engine->scriptFunctions[funcId]->listPattern );
  2520. // TODO: runtime optimize: A future optimization should be to use the stack space directly
  2521. // for small buffers so that the dynamic allocation is skipped
  2522. // Create a new special object type for the lists. Both asCRestore and the
  2523. // context exception handler will need this to know how to parse the buffer.
  2524. asCObjectType *listPatternType = engine->GetListPatternType(funcId);
  2525. // Allocate a temporary variable to hold the pointer to the buffer
  2526. int bufferVar = AllocateVariable(asCDataType::CreateObject(listPatternType, false), true);
  2527. asUINT bufferSize = 0;
  2528. // Evaluate all elements of the list
  2529. asSExprContext valueExpr(engine);
  2530. asCScriptNode *el = node;
  2531. asSListPatternNode *patternNode = engine->scriptFunctions[listPatternType->templateSubTypes[0].GetBehaviour()->listFactory]->listPattern;
  2532. int elementsInSubList = -1;
  2533. int r = CompileInitListElement(patternNode, el, engine->GetTypeIdFromDataType(asCDataType::CreateObject(listPatternType, false)), short(bufferVar), bufferSize, valueExpr.bc, elementsInSubList);
  2534. asASSERT( r || patternNode == 0 );
  2535. UNUSED_VAR(r);
  2536. // After all values have been evaluated we know the final size of the buffer
  2537. asSExprContext allocExpr(engine);
  2538. allocExpr.bc.InstrSHORT_DW(asBC_AllocMem, short(bufferVar), bufferSize);
  2539. // Merge the bytecode into the final sequence
  2540. bc->AddCode(&allocExpr.bc);
  2541. bc->AddCode(&valueExpr.bc);
  2542. // The object itself is the last to be created and will receive the pointer to the buffer
  2543. asCArray<asSExprContext *> args;
  2544. asSExprContext arg1(engine);
  2545. arg1.type.Set(asCDataType::CreatePrimitive(ttUInt, false));
  2546. arg1.type.dataType.MakeReference(true);
  2547. arg1.bc.InstrSHORT(asBC_PshVPtr, short(bufferVar));
  2548. args.PushLast(&arg1);
  2549. asSExprContext ctx(engine);
  2550. if( var->isVariable )
  2551. {
  2552. asASSERT( isVarGlobOrMem == 0 );
  2553. if( var->dataType.GetObjectType()->GetFlags() & asOBJ_REF )
  2554. {
  2555. ctx.bc.AddCode(&arg1.bc);
  2556. // Call factory and store the handle in the given variable
  2557. PerformFunctionCall(funcId, &ctx, false, &args, 0, true, var->stackOffset);
  2558. ctx.bc.Instr(asBC_PopPtr);
  2559. }
  2560. else
  2561. {
  2562. // Call the constructor
  2563. // When the object is allocated on the heap, the address where the
  2564. // reference will be stored must be pushed on the stack before the
  2565. // arguments. This reference on the stack is safe, even if the script
  2566. // is suspended during the evaluation of the arguments.
  2567. bool onHeap = IsVariableOnHeap(var->stackOffset);
  2568. if( onHeap )
  2569. ctx.bc.InstrSHORT(asBC_PSF, var->stackOffset);
  2570. ctx.bc.AddCode(&arg1.bc);
  2571. // When the object is allocated on the stack, the address to the
  2572. // object is pushed on the stack after the arguments as the object pointer
  2573. if( !onHeap )
  2574. ctx.bc.InstrSHORT(asBC_PSF, var->stackOffset);
  2575. PerformFunctionCall(funcId, &ctx, onHeap, &args, var->dataType.GetObjectType());
  2576. // Mark the object in the local variable as initialized
  2577. ctx.bc.ObjInfo(var->stackOffset, asOBJ_INIT);
  2578. }
  2579. }
  2580. else
  2581. {
  2582. if( var->dataType.GetObjectType()->GetFlags() & asOBJ_REF )
  2583. {
  2584. ctx.bc.AddCode(&arg1.bc);
  2585. PerformFunctionCall(funcId, &ctx, false, &args);
  2586. ctx.bc.Instr(asBC_RDSPtr);
  2587. if( isVarGlobOrMem == 1 )
  2588. {
  2589. // Store the returned handle in the global variable
  2590. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  2591. }
  2592. else
  2593. {
  2594. // Store the returned handle in the member
  2595. ctx.bc.InstrSHORT(asBC_PSF, 0);
  2596. ctx.bc.Instr(asBC_RDSPtr);
  2597. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)var->stackOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2598. }
  2599. ctx.bc.InstrPTR(asBC_REFCPY, var->dataType.GetObjectType());
  2600. ctx.bc.Instr(asBC_PopPtr);
  2601. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  2602. }
  2603. else
  2604. {
  2605. bool onHeap = true;
  2606. // Put the address where the object pointer will be placed on the stack
  2607. if( isVarGlobOrMem == 1 )
  2608. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  2609. else
  2610. {
  2611. onHeap = !var->dataType.IsObject() || var->dataType.IsReference() || (var->dataType.GetObjectType()->flags & asOBJ_REF);
  2612. if( onHeap )
  2613. {
  2614. ctx.bc.InstrSHORT(asBC_PSF, 0);
  2615. ctx.bc.Instr(asBC_RDSPtr);
  2616. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)var->stackOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2617. }
  2618. }
  2619. // Add the address of the list buffer as the argument
  2620. ctx.bc.AddCode(&arg1.bc);
  2621. if( !onHeap )
  2622. {
  2623. ctx.bc.InstrSHORT(asBC_PSF, 0);
  2624. ctx.bc.Instr(asBC_RDSPtr);
  2625. ctx.bc.InstrSHORT_DW(asBC_ADDSi, (short)var->stackOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(outFunc->objectType, false)));
  2626. }
  2627. // Call the ALLOC instruction to allocate memory and invoke constructor
  2628. PerformFunctionCall(funcId, &ctx, onHeap, &args, var->dataType.GetObjectType());
  2629. }
  2630. }
  2631. bc->AddCode(&ctx.bc);
  2632. // Free the temporary buffer. The FREE instruction will make sure to destroy
  2633. // each element in the buffer so there is no need to do this manually
  2634. bc->InstrW_PTR(asBC_FREE, short(bufferVar), listPatternType);
  2635. ReleaseTemporaryVariable(bufferVar, bc);
  2636. }
  2637. int asCCompiler::CompileInitListElement(asSListPatternNode *&patternNode, asCScriptNode *&valueNode, int bufferTypeId, short bufferVar, asUINT &bufferSize, asCByteCode &byteCode, int &elementsInSubList)
  2638. {
  2639. if( patternNode->type == asLPT_START )
  2640. {
  2641. if( valueNode->nodeType != snInitList )
  2642. {
  2643. Error(TXT_EXPECTED_LIST, valueNode);
  2644. return -1;
  2645. }
  2646. // Compile all values until asLPT_END
  2647. patternNode = patternNode->next;
  2648. asCScriptNode *node = valueNode->firstChild;
  2649. while( patternNode->type != asLPT_END )
  2650. {
  2651. if( node == 0 )
  2652. {
  2653. Error(TXT_NOT_ENOUGH_VALUES_FOR_LIST, valueNode);
  2654. return -1;
  2655. }
  2656. int r = CompileInitListElement(patternNode, node, bufferTypeId, bufferVar, bufferSize, byteCode, elementsInSubList);
  2657. if( r < 0 ) return r;
  2658. asASSERT( patternNode );
  2659. }
  2660. if( node )
  2661. {
  2662. Error(TXT_TOO_MANY_VALUES_FOR_LIST, valueNode);
  2663. return -1;
  2664. }
  2665. // Move to the next node
  2666. valueNode = valueNode->next;
  2667. patternNode = patternNode->next;
  2668. }
  2669. else if( patternNode->type == asLPT_REPEAT || patternNode->type == asLPT_REPEAT_SAME )
  2670. {
  2671. // TODO: list: repeat_inner should make sure the list has the same size as the inner list, i.e. square area
  2672. // TODO: list: repeat_prev should make sure the list is the same size as the previous
  2673. asEListPatternNodeType repeatType = patternNode->type;
  2674. asCScriptNode *firstValue = valueNode;
  2675. // The following values will be repeated N times
  2676. patternNode = patternNode->next;
  2677. // Keep track of the patternNode so it can be reset
  2678. asSListPatternNode *nextNode = patternNode;
  2679. // Align the buffer size to 4 bytes in case previous value was smaller than 4 bytes
  2680. if( bufferSize & 0x3 )
  2681. bufferSize += 4 - (bufferSize & 0x3);
  2682. // The first dword will hold the number of elements in the list
  2683. asDWORD currSize = bufferSize;
  2684. bufferSize += 4;
  2685. asUINT countElements = 0;
  2686. int elementsInSubSubList = -1;
  2687. asSExprContext ctx(engine);
  2688. while( valueNode )
  2689. {
  2690. patternNode = nextNode;
  2691. int r = CompileInitListElement(patternNode, valueNode, bufferTypeId, bufferVar, bufferSize, ctx.bc, elementsInSubSubList);
  2692. if( r < 0 ) return r;
  2693. countElements++;
  2694. }
  2695. // For repeat_same each repeated sublist must have the same size to form a rectangular array
  2696. if( repeatType == asLPT_REPEAT_SAME && elementsInSubList != -1 && asUINT(elementsInSubList) != countElements )
  2697. {
  2698. if( countElements < asUINT(elementsInSubList) )
  2699. Error(TXT_NOT_ENOUGH_VALUES_FOR_LIST, firstValue);
  2700. else
  2701. Error(TXT_TOO_MANY_VALUES_FOR_LIST, firstValue);
  2702. return -1;
  2703. }
  2704. else
  2705. {
  2706. // Return to caller the amount of elments in this sublist
  2707. elementsInSubList = countElements;
  2708. }
  2709. // The first dword in the buffer will hold the number of elements
  2710. byteCode.InstrSHORT_DW_DW(asBC_SetListSize, bufferVar, currSize, countElements);
  2711. // Add the values
  2712. byteCode.AddCode(&ctx.bc);
  2713. }
  2714. else if( patternNode->type == asLPT_TYPE )
  2715. {
  2716. // Determine the size of the element
  2717. asUINT size = 0;
  2718. asCDataType dt = reinterpret_cast<asSListPatternDataTypeNode*>(patternNode)->dataType;
  2719. if( valueNode->nodeType == snAssignment || valueNode->nodeType == snInitList )
  2720. {
  2721. asSExprContext lctx(engine);
  2722. asSExprContext rctx(engine);
  2723. if( valueNode->nodeType == snAssignment )
  2724. {
  2725. // Compile the assignment expression
  2726. CompileAssignment(valueNode, &rctx);
  2727. if( dt.GetTokenType() == ttQuestion )
  2728. {
  2729. // We now know the type
  2730. dt = rctx.type.dataType;
  2731. dt.MakeReadOnly(false);
  2732. dt.MakeReference(false);
  2733. // Values on the list must be aligned to 32bit boundaries, except if the type is smaller than 32bit.
  2734. if( bufferSize & 0x3 )
  2735. bufferSize += 4 - (bufferSize & 0x3);
  2736. // Place the type id in the buffer
  2737. byteCode.InstrSHORT_DW_DW(asBC_SetListType, bufferVar, bufferSize, engine->GetTypeIdFromDataType(dt));
  2738. bufferSize += 4;
  2739. }
  2740. }
  2741. else if( valueNode->nodeType == snInitList )
  2742. {
  2743. if( dt.GetTokenType() == ttQuestion )
  2744. {
  2745. // Can't use init lists with var type as it is not possible to determine what type should be allocated
  2746. asCString str;
  2747. str.Format(TXT_INIT_LIST_CANNOT_BE_USED_WITH_s, "?");
  2748. Error(str.AddressOf(), valueNode);
  2749. rctx.type.SetDummy();
  2750. dt = rctx.type.dataType;
  2751. }
  2752. else
  2753. {
  2754. // Allocate a temporary variable that will be initialized with the list
  2755. int offset = AllocateVariable(dt, true);
  2756. rctx.type.Set(dt);
  2757. rctx.type.isVariable = true;
  2758. rctx.type.isTemporary = true;
  2759. rctx.type.stackOffset = (short)offset;
  2760. CompileInitList(&rctx.type, valueNode, &rctx.bc, 0);
  2761. // Put the object on the stack
  2762. rctx.bc.InstrSHORT(asBC_PSF, rctx.type.stackOffset);
  2763. // It is a reference that we place on the stack
  2764. rctx.type.dataType.MakeReference(true);
  2765. }
  2766. }
  2767. // Determine size of the element
  2768. if( dt.IsPrimitive() || (!dt.IsNullHandle() && (dt.GetObjectType()->flags & asOBJ_VALUE)) )
  2769. size = dt.GetSizeInMemoryBytes();
  2770. else
  2771. size = AS_PTR_SIZE*4;
  2772. // Values on the list must be aligned to 32bit boundaries, except if the type is smaller than 32bit.
  2773. if( size >= 4 && (bufferSize & 0x3) )
  2774. bufferSize += 4 - (bufferSize & 0x3);
  2775. // Compile the lvalue
  2776. lctx.bc.InstrSHORT_DW(asBC_PshListElmnt, bufferVar, bufferSize);
  2777. lctx.type.Set(dt);
  2778. lctx.type.isLValue = true;
  2779. if( dt.IsPrimitive() )
  2780. {
  2781. lctx.bc.Instr(asBC_PopRPtr);
  2782. lctx.type.dataType.MakeReference(true);
  2783. }
  2784. else if( dt.IsObjectHandle() ||
  2785. dt.GetObjectType()->flags & asOBJ_REF )
  2786. {
  2787. lctx.type.isExplicitHandle = true;
  2788. lctx.type.dataType.MakeReference(true);
  2789. }
  2790. else
  2791. {
  2792. asASSERT( dt.GetObjectType()->flags & asOBJ_VALUE );
  2793. // Make sure the object has been constructed before the assignment
  2794. // TODO: runtime optimize: Use copy constructor instead of assignment to initialize the objects
  2795. asSTypeBehaviour *beh = dt.GetBehaviour();
  2796. int func = 0;
  2797. if( beh ) func = beh->construct;
  2798. if( func == 0 && (dt.GetObjectType()->flags & asOBJ_POD) == 0 )
  2799. {
  2800. asCString str;
  2801. // TODO: funcdef: asCDataType should have a GetTypeName()
  2802. if( dt.GetFuncDef() )
  2803. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetFuncDef()->GetName());
  2804. else
  2805. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetObjectType()->GetName());
  2806. Error(str, valueNode);
  2807. }
  2808. else if( func )
  2809. {
  2810. // Call the constructor as a normal function
  2811. byteCode.InstrSHORT_DW(asBC_PshListElmnt, bufferVar, bufferSize);
  2812. asSExprContext ctx(engine);
  2813. PerformFunctionCall(func, &ctx, false, 0, dt.GetObjectType());
  2814. byteCode.AddCode(&ctx.bc);
  2815. }
  2816. }
  2817. asSExprContext ctx(engine);
  2818. DoAssignment(&ctx, &lctx, &rctx, valueNode, valueNode, ttAssignment, valueNode);
  2819. if( !lctx.type.dataType.IsPrimitive() )
  2820. ctx.bc.Instr(asBC_PopPtr);
  2821. // Release temporary variables used by expression
  2822. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  2823. ProcessDeferredParams(&ctx);
  2824. byteCode.AddCode(&ctx.bc);
  2825. }
  2826. else
  2827. {
  2828. // There is no specific value so we need to fill it with a default value
  2829. if( dt.GetTokenType() == ttQuestion )
  2830. {
  2831. // Values on the list must be aligned to 32bit boundaries, except if the type is smaller than 32bit.
  2832. if( bufferSize & 0x3 )
  2833. bufferSize += 4 - (bufferSize & 0x3);
  2834. // Place the type id for a null handle in the buffer
  2835. byteCode.InstrSHORT_DW_DW(asBC_SetListType, bufferVar, bufferSize, 0);
  2836. bufferSize += 4;
  2837. dt = asCDataType::CreateNullHandle();
  2838. // No need to initialize the handle as the buffer is already initialized with zeroes
  2839. }
  2840. else if( dt.GetObjectType() && dt.GetObjectType()->flags & asOBJ_VALUE )
  2841. {
  2842. // For value types with default constructor we need to call the constructor
  2843. asSTypeBehaviour *beh = dt.GetBehaviour();
  2844. int func = 0;
  2845. if( beh ) func = beh->construct;
  2846. if( func == 0 && (dt.GetObjectType()->flags & asOBJ_POD) == 0 )
  2847. {
  2848. asCString str;
  2849. // TODO: funcdef: asCDataType should have a GetTypeName()
  2850. if( dt.GetFuncDef() )
  2851. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetFuncDef()->GetName());
  2852. else
  2853. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetObjectType()->GetName());
  2854. Error(str, valueNode);
  2855. }
  2856. else if( func )
  2857. {
  2858. // Values on the list must be aligned to 32bit boundaries, except if the type is smaller than 32bit.
  2859. if( bufferSize & 0x3 )
  2860. bufferSize += 4 - (bufferSize & 0x3);
  2861. // Call the constructor as a normal function
  2862. byteCode.InstrSHORT_DW(asBC_PshListElmnt, bufferVar, bufferSize);
  2863. asSExprContext ctx(engine);
  2864. PerformFunctionCall(func, &ctx, false, 0, dt.GetObjectType());
  2865. byteCode.AddCode(&ctx.bc);
  2866. }
  2867. }
  2868. else if( !dt.IsObjectHandle() && dt.GetObjectType() && dt.GetObjectType()->flags & asOBJ_REF )
  2869. {
  2870. // For ref types (not handles) we need to call the default factory
  2871. asSTypeBehaviour *beh = dt.GetBehaviour();
  2872. int func = 0;
  2873. if( beh ) func = beh->factory;
  2874. if( func == 0 )
  2875. {
  2876. asCString str;
  2877. // TODO: funcdef: asCDataType should have a GetTypeName()
  2878. if( dt.GetFuncDef() )
  2879. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetFuncDef()->GetName());
  2880. else
  2881. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetObjectType()->GetName());
  2882. Error(str, valueNode);
  2883. }
  2884. else if( func )
  2885. {
  2886. asSExprContext rctx(engine);
  2887. PerformFunctionCall(func, &rctx, false, 0, dt.GetObjectType());
  2888. // Values on the list must be aligned to 32bit boundaries, except if the type is smaller than 32bit.
  2889. if( bufferSize & 0x3 )
  2890. bufferSize += 4 - (bufferSize & 0x3);
  2891. asSExprContext lctx(engine);
  2892. lctx.bc.InstrSHORT_DW(asBC_PshListElmnt, bufferVar, bufferSize);
  2893. lctx.type.Set(dt);
  2894. lctx.type.isLValue = true;
  2895. lctx.type.isExplicitHandle = true;
  2896. lctx.type.dataType.MakeReference(true);
  2897. asSExprContext ctx(engine);
  2898. DoAssignment(&ctx, &lctx, &rctx, valueNode, valueNode, ttAssignment, valueNode);
  2899. if( !lctx.type.dataType.IsPrimitive() )
  2900. ctx.bc.Instr(asBC_PopPtr);
  2901. // Release temporary variables used by expression
  2902. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  2903. ProcessDeferredParams(&ctx);
  2904. byteCode.AddCode(&ctx.bc);
  2905. }
  2906. }
  2907. }
  2908. // Determine size of the element
  2909. if( dt.IsPrimitive() || (!dt.IsNullHandle() && (dt.GetObjectType()->flags & asOBJ_VALUE)) )
  2910. size = dt.GetSizeInMemoryBytes();
  2911. else
  2912. size = AS_PTR_SIZE*4;
  2913. asASSERT( size <= 4 || (size & 0x3) == 0 );
  2914. // Move to the next element
  2915. bufferSize += size;
  2916. patternNode = patternNode->next;
  2917. valueNode = valueNode->next;
  2918. }
  2919. else
  2920. asASSERT( false );
  2921. return 0;
  2922. }
  2923. void asCCompiler::CompileStatement(asCScriptNode *statement, bool *hasReturn, asCByteCode *bc)
  2924. {
  2925. // Don't clear the hasReturn flag if this is an empty statement
  2926. // to avoid false errors of 'not all paths return'
  2927. if( statement->nodeType != snExpressionStatement || statement->firstChild )
  2928. *hasReturn = false;
  2929. if( statement->nodeType == snStatementBlock )
  2930. CompileStatementBlock(statement, true, hasReturn, bc);
  2931. else if( statement->nodeType == snIf )
  2932. CompileIfStatement(statement, hasReturn, bc);
  2933. else if( statement->nodeType == snFor )
  2934. CompileForStatement(statement, bc);
  2935. else if( statement->nodeType == snWhile )
  2936. CompileWhileStatement(statement, bc);
  2937. else if( statement->nodeType == snDoWhile )
  2938. CompileDoWhileStatement(statement, bc);
  2939. else if( statement->nodeType == snExpressionStatement )
  2940. CompileExpressionStatement(statement, bc);
  2941. else if( statement->nodeType == snBreak )
  2942. CompileBreakStatement(statement, bc);
  2943. else if( statement->nodeType == snContinue )
  2944. CompileContinueStatement(statement, bc);
  2945. else if( statement->nodeType == snSwitch )
  2946. CompileSwitchStatement(statement, hasReturn, bc);
  2947. else if( statement->nodeType == snReturn )
  2948. {
  2949. CompileReturnStatement(statement, bc);
  2950. *hasReturn = true;
  2951. }
  2952. }
  2953. void asCCompiler::CompileSwitchStatement(asCScriptNode *snode, bool *, asCByteCode *bc)
  2954. {
  2955. // TODO: inheritance: Must guarantee that all options in the switch case call a constructor, or that none call it.
  2956. // Reserve label for break statements
  2957. int breakLabel = nextLabel++;
  2958. breakLabels.PushLast(breakLabel);
  2959. // Add a variable scope that will be used by CompileBreak
  2960. // to know where to stop deallocating variables
  2961. AddVariableScope(true, false);
  2962. //---------------------------
  2963. // Compile the switch expression
  2964. //-------------------------------
  2965. // Compile the switch expression
  2966. asSExprContext expr(engine);
  2967. CompileAssignment(snode->firstChild, &expr);
  2968. // Verify that the expression is a primitive type
  2969. if( !expr.type.dataType.IsIntegerType() && !expr.type.dataType.IsUnsignedType() )
  2970. {
  2971. Error(TXT_SWITCH_MUST_BE_INTEGRAL, snode->firstChild);
  2972. return;
  2973. }
  2974. ProcessPropertyGetAccessor(&expr, snode);
  2975. // TODO: Need to support 64bit integers
  2976. // Convert the expression to a 32bit variable
  2977. asCDataType to;
  2978. if( expr.type.dataType.IsIntegerType() )
  2979. to.SetTokenType(ttInt);
  2980. else if( expr.type.dataType.IsUnsignedType() )
  2981. to.SetTokenType(ttUInt);
  2982. // Make sure the value is in a variable
  2983. if( expr.type.dataType.IsReference() )
  2984. ConvertToVariable(&expr);
  2985. ImplicitConversion(&expr, to, snode->firstChild, asIC_IMPLICIT_CONV, true);
  2986. ConvertToVariable(&expr);
  2987. int offset = expr.type.stackOffset;
  2988. ProcessDeferredParams(&expr);
  2989. //-------------------------------
  2990. // Determine case values and labels
  2991. //--------------------------------
  2992. // Remember the first label so that we can later pass the
  2993. // correct label to each CompileCase()
  2994. int firstCaseLabel = nextLabel;
  2995. int defaultLabel = 0;
  2996. asCArray<int> caseValues;
  2997. asCArray<int> caseLabels;
  2998. // Compile all case comparisons and make them jump to the right label
  2999. asCScriptNode *cnode = snode->firstChild->next;
  3000. while( cnode )
  3001. {
  3002. // Each case should have a constant expression
  3003. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  3004. {
  3005. // Compile expression
  3006. asSExprContext c(engine);
  3007. CompileExpression(cnode->firstChild, &c);
  3008. // Verify that the result is a constant
  3009. if( !c.type.isConstant )
  3010. Error(TXT_SWITCH_CASE_MUST_BE_CONSTANT, cnode->firstChild);
  3011. // Verify that the result is an integral number
  3012. if( !c.type.dataType.IsIntegerType() && !c.type.dataType.IsUnsignedType() )
  3013. Error(TXT_SWITCH_MUST_BE_INTEGRAL, cnode->firstChild);
  3014. ImplicitConversion(&c, to, cnode->firstChild, asIC_IMPLICIT_CONV, true);
  3015. // Has this case been declared already?
  3016. if( caseValues.IndexOf(c.type.intValue) >= 0 )
  3017. {
  3018. Error(TXT_DUPLICATE_SWITCH_CASE, cnode->firstChild);
  3019. }
  3020. // TODO: Optimize: We can insert the numbers sorted already
  3021. // Store constant for later use
  3022. caseValues.PushLast(c.type.intValue);
  3023. // Reserve label for this case
  3024. caseLabels.PushLast(nextLabel++);
  3025. }
  3026. else
  3027. {
  3028. // TODO: It shouldn't be necessary for the default case to be the last one.
  3029. // Is default the last case?
  3030. if( cnode->next )
  3031. {
  3032. Error(TXT_DEFAULT_MUST_BE_LAST, cnode);
  3033. break;
  3034. }
  3035. // Reserve label for this case
  3036. defaultLabel = nextLabel++;
  3037. }
  3038. cnode = cnode->next;
  3039. }
  3040. // check for empty switch
  3041. if (caseValues.GetLength() == 0)
  3042. {
  3043. Error(TXT_EMPTY_SWITCH, snode);
  3044. return;
  3045. }
  3046. if( defaultLabel == 0 )
  3047. defaultLabel = breakLabel;
  3048. //---------------------------------
  3049. // Output the optimized case comparisons
  3050. // with jumps to the case code
  3051. //------------------------------------
  3052. // Sort the case values by increasing value. Do the sort together with the labels
  3053. // A simple bubble sort is sufficient since we don't expect a huge number of values
  3054. for( asUINT fwd = 1; fwd < caseValues.GetLength(); fwd++ )
  3055. {
  3056. for( int bck = fwd - 1; bck >= 0; bck-- )
  3057. {
  3058. int bckp = bck + 1;
  3059. if( caseValues[bck] > caseValues[bckp] )
  3060. {
  3061. // Swap the values in both arrays
  3062. int swap = caseValues[bckp];
  3063. caseValues[bckp] = caseValues[bck];
  3064. caseValues[bck] = swap;
  3065. swap = caseLabels[bckp];
  3066. caseLabels[bckp] = caseLabels[bck];
  3067. caseLabels[bck] = swap;
  3068. }
  3069. else
  3070. break;
  3071. }
  3072. }
  3073. // Find ranges of consecutive numbers
  3074. asCArray<int> ranges;
  3075. ranges.PushLast(0);
  3076. asUINT n;
  3077. for( n = 1; n < caseValues.GetLength(); ++n )
  3078. {
  3079. // We can join numbers that are less than 5 numbers
  3080. // apart since the output code will still be smaller
  3081. if( caseValues[n] > caseValues[n-1] + 5 )
  3082. ranges.PushLast(n);
  3083. }
  3084. // If the value is larger than the largest case value, jump to default
  3085. int tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  3086. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[caseValues.GetLength()-1]);
  3087. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  3088. expr.bc.InstrDWORD(asBC_JP, defaultLabel);
  3089. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  3090. // TODO: runtime optimize: We could possibly optimize this even more by doing a
  3091. // binary search instead of a linear search through the ranges
  3092. // For each range
  3093. int range;
  3094. for( range = 0; range < (int)ranges.GetLength(); range++ )
  3095. {
  3096. // Find the largest value in this range
  3097. int maxRange = caseValues[ranges[range]];
  3098. int index = ranges[range];
  3099. for( ; (index < (int)caseValues.GetLength()) && (caseValues[index] <= maxRange + 5); index++ )
  3100. maxRange = caseValues[index];
  3101. // If there are only 2 numbers then it is better to compare them directly
  3102. if( index - ranges[range] > 2 )
  3103. {
  3104. // If the value is smaller than the smallest case value in the range, jump to default
  3105. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  3106. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  3107. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  3108. expr.bc.InstrDWORD(asBC_JS, defaultLabel);
  3109. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  3110. int nextRangeLabel = nextLabel++;
  3111. // If this is the last range we don't have to make this test
  3112. if( range < (int)ranges.GetLength() - 1 )
  3113. {
  3114. // If the value is larger than the largest case value in the range, jump to the next range
  3115. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  3116. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, maxRange);
  3117. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  3118. expr.bc.InstrDWORD(asBC_JP, nextRangeLabel);
  3119. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  3120. }
  3121. // Jump forward according to the value
  3122. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  3123. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  3124. expr.bc.InstrW_W_W(asBC_SUBi, tmpOffset, offset, tmpOffset);
  3125. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  3126. expr.bc.JmpP(tmpOffset, maxRange - caseValues[ranges[range]]);
  3127. // Add the list of jumps to the correct labels (any holes, jump to default)
  3128. index = ranges[range];
  3129. for( int n = caseValues[index]; n <= maxRange; n++ )
  3130. {
  3131. if( caseValues[index] == n )
  3132. expr.bc.InstrINT(asBC_JMP, caseLabels[index++]);
  3133. else
  3134. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  3135. }
  3136. expr.bc.Label((short)nextRangeLabel);
  3137. }
  3138. else
  3139. {
  3140. // Simply make a comparison with each value
  3141. int n;
  3142. for( n = ranges[range]; n < index; ++n )
  3143. {
  3144. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  3145. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[n]);
  3146. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  3147. expr.bc.InstrDWORD(asBC_JZ, caseLabels[n]);
  3148. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  3149. }
  3150. }
  3151. }
  3152. // Catch any value that falls trough
  3153. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  3154. // Release the temporary variable previously stored
  3155. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3156. // TODO: optimize: Should optimize each piece individually
  3157. expr.bc.OptimizeLocally(tempVariableOffsets);
  3158. //----------------------------------
  3159. // Output case implementations
  3160. //----------------------------------
  3161. // Compile case implementations, each one with the label before it
  3162. cnode = snode->firstChild->next;
  3163. while( cnode )
  3164. {
  3165. // Each case should have a constant expression
  3166. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  3167. {
  3168. expr.bc.Label((short)firstCaseLabel++);
  3169. CompileCase(cnode->firstChild->next, &expr.bc);
  3170. }
  3171. else
  3172. {
  3173. expr.bc.Label((short)defaultLabel);
  3174. // Is default the last case?
  3175. if( cnode->next )
  3176. {
  3177. // We've already reported this error
  3178. break;
  3179. }
  3180. CompileCase(cnode->firstChild, &expr.bc);
  3181. }
  3182. cnode = cnode->next;
  3183. }
  3184. //--------------------------------
  3185. bc->AddCode(&expr.bc);
  3186. // Add break label
  3187. bc->Label((short)breakLabel);
  3188. breakLabels.PopLast();
  3189. RemoveVariableScope();
  3190. }
  3191. void asCCompiler::CompileCase(asCScriptNode *node, asCByteCode *bc)
  3192. {
  3193. bool isFinished = false;
  3194. bool hasReturn = false;
  3195. bool hasUnreachableCode = false;
  3196. while( node )
  3197. {
  3198. if( !hasUnreachableCode && (hasReturn || isFinished) )
  3199. {
  3200. hasUnreachableCode = true;
  3201. Warning(TXT_UNREACHABLE_CODE, node);
  3202. break;
  3203. }
  3204. if( node->nodeType == snBreak || node->nodeType == snContinue )
  3205. isFinished = true;
  3206. asCByteCode statement(engine);
  3207. if( node->nodeType == snDeclaration )
  3208. {
  3209. Error(TXT_DECL_IN_SWITCH, node);
  3210. // Compile it anyway to avoid further compiler errors
  3211. CompileDeclaration(node, &statement);
  3212. }
  3213. else
  3214. CompileStatement(node, &hasReturn, &statement);
  3215. LineInstr(bc, node->tokenPos);
  3216. bc->AddCode(&statement);
  3217. if( !hasCompileErrors )
  3218. asASSERT( tempVariables.GetLength() == 0 );
  3219. node = node->next;
  3220. }
  3221. }
  3222. void asCCompiler::CompileIfStatement(asCScriptNode *inode, bool *hasReturn, asCByteCode *bc)
  3223. {
  3224. // We will use one label for the if statement
  3225. // and possibly another for the else statement
  3226. int afterLabel = nextLabel++;
  3227. // Compile the expression
  3228. asSExprContext expr(engine);
  3229. int r = CompileAssignment(inode->firstChild, &expr);
  3230. if( r == 0 )
  3231. {
  3232. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  3233. Error(TXT_EXPR_MUST_BE_BOOL, inode->firstChild);
  3234. else
  3235. {
  3236. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  3237. ProcessDeferredParams(&expr);
  3238. if( !expr.type.isConstant )
  3239. {
  3240. ProcessPropertyGetAccessor(&expr, inode);
  3241. ConvertToVariable(&expr);
  3242. // Add a test
  3243. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  3244. expr.bc.Instr(asBC_ClrHi);
  3245. expr.bc.InstrDWORD(asBC_JZ, afterLabel);
  3246. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3247. expr.bc.OptimizeLocally(tempVariableOffsets);
  3248. bc->AddCode(&expr.bc);
  3249. }
  3250. else if( expr.type.dwordValue == 0 )
  3251. {
  3252. // Jump to the else case
  3253. bc->InstrINT(asBC_JMP, afterLabel);
  3254. // TODO: Should we warn that the expression will always go to the else?
  3255. }
  3256. }
  3257. }
  3258. // Compile the if statement
  3259. bool origIsConstructorCalled = m_isConstructorCalled;
  3260. bool hasReturn1;
  3261. asCByteCode ifBC(engine);
  3262. CompileStatement(inode->firstChild->next, &hasReturn1, &ifBC);
  3263. // Add the byte code
  3264. LineInstr(bc, inode->firstChild->next->tokenPos);
  3265. bc->AddCode(&ifBC);
  3266. if( inode->firstChild->next->nodeType == snExpressionStatement && inode->firstChild->next->firstChild == 0 )
  3267. {
  3268. // Don't allow if( expr );
  3269. Error(TXT_IF_WITH_EMPTY_STATEMENT, inode->firstChild->next);
  3270. }
  3271. // If one of the statements call the constructor, the other must as well
  3272. // otherwise it is possible the constructor is never called
  3273. bool constructorCall1 = false;
  3274. bool constructorCall2 = false;
  3275. if( !origIsConstructorCalled && m_isConstructorCalled )
  3276. constructorCall1 = true;
  3277. // Do we have an else statement?
  3278. if( inode->firstChild->next != inode->lastChild )
  3279. {
  3280. // Reset the constructor called flag so the else statement can call the constructor too
  3281. m_isConstructorCalled = origIsConstructorCalled;
  3282. int afterElse = 0;
  3283. if( !hasReturn1 )
  3284. {
  3285. afterElse = nextLabel++;
  3286. // Add jump to after the else statement
  3287. bc->InstrINT(asBC_JMP, afterElse);
  3288. }
  3289. // Add label for the else statement
  3290. bc->Label((short)afterLabel);
  3291. bool hasReturn2;
  3292. asCByteCode elseBC(engine);
  3293. CompileStatement(inode->lastChild, &hasReturn2, &elseBC);
  3294. // Add byte code for the else statement
  3295. LineInstr(bc, inode->lastChild->tokenPos);
  3296. bc->AddCode(&elseBC);
  3297. if( inode->lastChild->nodeType == snExpressionStatement && inode->lastChild->firstChild == 0 )
  3298. {
  3299. // Don't allow if( expr ) {} else;
  3300. Error(TXT_ELSE_WITH_EMPTY_STATEMENT, inode->lastChild);
  3301. }
  3302. if( !hasReturn1 )
  3303. {
  3304. // Add label for the end of else statement
  3305. bc->Label((short)afterElse);
  3306. }
  3307. // The if statement only has return if both alternatives have
  3308. *hasReturn = hasReturn1 && hasReturn2;
  3309. if( !origIsConstructorCalled && m_isConstructorCalled )
  3310. constructorCall2 = true;
  3311. }
  3312. else
  3313. {
  3314. // Add label for the end of if statement
  3315. bc->Label((short)afterLabel);
  3316. *hasReturn = false;
  3317. }
  3318. // Make sure both or neither conditions call a constructor
  3319. if( (constructorCall1 && !constructorCall2) ||
  3320. (constructorCall2 && !constructorCall1) )
  3321. {
  3322. Error(TXT_BOTH_CONDITIONS_MUST_CALL_CONSTRUCTOR, inode);
  3323. }
  3324. m_isConstructorCalled = origIsConstructorCalled || constructorCall1 || constructorCall2;
  3325. }
  3326. void asCCompiler::CompileForStatement(asCScriptNode *fnode, asCByteCode *bc)
  3327. {
  3328. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  3329. AddVariableScope(true, true);
  3330. // We will use three labels for the for loop
  3331. int conditionLabel = nextLabel++;
  3332. int afterLabel = nextLabel++;
  3333. int continueLabel = nextLabel++;
  3334. int insideLabel = nextLabel++;
  3335. continueLabels.PushLast(continueLabel);
  3336. breakLabels.PushLast(afterLabel);
  3337. //---------------------------------------
  3338. // Compile the initialization statement
  3339. asCByteCode initBC(engine);
  3340. LineInstr(&initBC, fnode->firstChild->tokenPos);
  3341. if( fnode->firstChild->nodeType == snDeclaration )
  3342. CompileDeclaration(fnode->firstChild, &initBC);
  3343. else
  3344. CompileExpressionStatement(fnode->firstChild, &initBC);
  3345. //-----------------------------------
  3346. // Compile the condition statement
  3347. asSExprContext expr(engine);
  3348. asCScriptNode *second = fnode->firstChild->next;
  3349. if( second->firstChild )
  3350. {
  3351. int r = CompileAssignment(second->firstChild, &expr);
  3352. if( r >= 0 )
  3353. {
  3354. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  3355. Error(TXT_EXPR_MUST_BE_BOOL, second);
  3356. else
  3357. {
  3358. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  3359. ProcessDeferredParams(&expr);
  3360. ProcessPropertyGetAccessor(&expr, second);
  3361. // If expression is false exit the loop
  3362. ConvertToVariable(&expr);
  3363. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  3364. expr.bc.Instr(asBC_ClrHi);
  3365. expr.bc.InstrDWORD(asBC_JNZ, insideLabel);
  3366. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3367. expr.bc.OptimizeLocally(tempVariableOffsets);
  3368. // Prepend the line instruction for the condition
  3369. asCByteCode tmp(engine);
  3370. LineInstr(&tmp, second->firstChild->tokenPos);
  3371. tmp.AddCode(&expr.bc);
  3372. expr.bc.AddCode(&tmp);
  3373. }
  3374. }
  3375. }
  3376. //---------------------------
  3377. // Compile the increment statement
  3378. asCByteCode nextBC(engine);
  3379. asCScriptNode *third = second->next;
  3380. if( third->nodeType == snExpressionStatement )
  3381. {
  3382. LineInstr(&nextBC, third->tokenPos);
  3383. CompileExpressionStatement(third, &nextBC);
  3384. }
  3385. //------------------------------
  3386. // Compile loop statement
  3387. bool hasReturn;
  3388. asCByteCode forBC(engine);
  3389. CompileStatement(fnode->lastChild, &hasReturn, &forBC);
  3390. //-------------------------------
  3391. // Join the code pieces
  3392. bc->AddCode(&initBC);
  3393. bc->InstrDWORD(asBC_JMP, conditionLabel);
  3394. bc->Label((short)insideLabel);
  3395. // Add a suspend bytecode inside the loop to guarantee
  3396. // that the application can suspend the execution
  3397. bc->Instr(asBC_SUSPEND);
  3398. bc->InstrPTR(asBC_JitEntry, 0);
  3399. LineInstr(bc, fnode->lastChild->tokenPos);
  3400. bc->AddCode(&forBC);
  3401. bc->Label((short)continueLabel);
  3402. bc->AddCode(&nextBC);
  3403. bc->Label((short)conditionLabel);
  3404. if( expr.bc.GetLastInstr() == -1 )
  3405. // There is no condition, so we just always jump
  3406. bc->InstrDWORD(asBC_JMP, insideLabel);
  3407. else
  3408. bc->AddCode(&expr.bc);
  3409. bc->Label((short)afterLabel);
  3410. continueLabels.PopLast();
  3411. breakLabels.PopLast();
  3412. // Deallocate variables in this block, in reverse order
  3413. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  3414. {
  3415. sVariable *v = variables->variables[n];
  3416. // Call variable destructors here, for variables not yet destroyed
  3417. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  3418. // Don't deallocate function parameters
  3419. if( v->stackOffset > 0 )
  3420. DeallocateVariable(v->stackOffset);
  3421. }
  3422. RemoveVariableScope();
  3423. }
  3424. void asCCompiler::CompileWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  3425. {
  3426. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  3427. AddVariableScope(true, true);
  3428. // We will use two labels for the while loop
  3429. int beforeLabel = nextLabel++;
  3430. int afterLabel = nextLabel++;
  3431. continueLabels.PushLast(beforeLabel);
  3432. breakLabels.PushLast(afterLabel);
  3433. // Add label before the expression
  3434. bc->Label((short)beforeLabel);
  3435. // Compile expression
  3436. asSExprContext expr(engine);
  3437. int r = CompileAssignment(wnode->firstChild, &expr);
  3438. if( r == 0 )
  3439. {
  3440. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  3441. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  3442. else
  3443. {
  3444. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  3445. ProcessDeferredParams(&expr);
  3446. ProcessPropertyGetAccessor(&expr, wnode);
  3447. // Add byte code for the expression
  3448. ConvertToVariable(&expr);
  3449. // Jump to end of statement if expression is false
  3450. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  3451. expr.bc.Instr(asBC_ClrHi);
  3452. expr.bc.InstrDWORD(asBC_JZ, afterLabel);
  3453. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3454. expr.bc.OptimizeLocally(tempVariableOffsets);
  3455. bc->AddCode(&expr.bc);
  3456. }
  3457. }
  3458. // Add a suspend bytecode inside the loop to guarantee
  3459. // that the application can suspend the execution
  3460. bc->Instr(asBC_SUSPEND);
  3461. bc->InstrPTR(asBC_JitEntry, 0);
  3462. // Compile statement
  3463. bool hasReturn;
  3464. asCByteCode whileBC(engine);
  3465. CompileStatement(wnode->lastChild, &hasReturn, &whileBC);
  3466. // Add byte code for the statement
  3467. LineInstr(bc, wnode->lastChild->tokenPos);
  3468. bc->AddCode(&whileBC);
  3469. // Jump to the expression
  3470. bc->InstrINT(asBC_JMP, beforeLabel);
  3471. // Add label after the statement
  3472. bc->Label((short)afterLabel);
  3473. continueLabels.PopLast();
  3474. breakLabels.PopLast();
  3475. RemoveVariableScope();
  3476. }
  3477. void asCCompiler::CompileDoWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  3478. {
  3479. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  3480. AddVariableScope(true, true);
  3481. // We will use two labels for the while loop
  3482. int beforeLabel = nextLabel++;
  3483. int beforeTest = nextLabel++;
  3484. int afterLabel = nextLabel++;
  3485. continueLabels.PushLast(beforeTest);
  3486. breakLabels.PushLast(afterLabel);
  3487. // Add label before the statement
  3488. bc->Label((short)beforeLabel);
  3489. // Compile statement
  3490. bool hasReturn;
  3491. asCByteCode whileBC(engine);
  3492. CompileStatement(wnode->firstChild, &hasReturn, &whileBC);
  3493. // Add byte code for the statement
  3494. LineInstr(bc, wnode->firstChild->tokenPos);
  3495. bc->AddCode(&whileBC);
  3496. // Add label before the expression
  3497. bc->Label((short)beforeTest);
  3498. // Add a suspend bytecode inside the loop to guarantee
  3499. // that the application can suspend the execution
  3500. bc->Instr(asBC_SUSPEND);
  3501. bc->InstrPTR(asBC_JitEntry, 0);
  3502. // Add a line instruction
  3503. LineInstr(bc, wnode->lastChild->tokenPos);
  3504. // Compile expression
  3505. asSExprContext expr(engine);
  3506. CompileAssignment(wnode->lastChild, &expr);
  3507. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  3508. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  3509. else
  3510. {
  3511. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  3512. ProcessDeferredParams(&expr);
  3513. ProcessPropertyGetAccessor(&expr, wnode);
  3514. // Add byte code for the expression
  3515. ConvertToVariable(&expr);
  3516. // Jump to next iteration if expression is true
  3517. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  3518. expr.bc.Instr(asBC_ClrHi);
  3519. expr.bc.InstrDWORD(asBC_JNZ, beforeLabel);
  3520. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3521. expr.bc.OptimizeLocally(tempVariableOffsets);
  3522. bc->AddCode(&expr.bc);
  3523. }
  3524. // Add label after the statement
  3525. bc->Label((short)afterLabel);
  3526. continueLabels.PopLast();
  3527. breakLabels.PopLast();
  3528. RemoveVariableScope();
  3529. }
  3530. void asCCompiler::CompileBreakStatement(asCScriptNode *node, asCByteCode *bc)
  3531. {
  3532. if( breakLabels.GetLength() == 0 )
  3533. {
  3534. Error(TXT_INVALID_BREAK, node);
  3535. return;
  3536. }
  3537. // Add destructor calls for all variables that will go out of scope
  3538. // Put this clean up in a block to allow exception handler to understand them
  3539. bc->Block(true);
  3540. asCVariableScope *vs = variables;
  3541. while( !vs->isBreakScope )
  3542. {
  3543. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  3544. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  3545. vs = vs->parent;
  3546. }
  3547. bc->Block(false);
  3548. bc->InstrINT(asBC_JMP, breakLabels[breakLabels.GetLength()-1]);
  3549. }
  3550. void asCCompiler::CompileContinueStatement(asCScriptNode *node, asCByteCode *bc)
  3551. {
  3552. if( continueLabels.GetLength() == 0 )
  3553. {
  3554. Error(TXT_INVALID_CONTINUE, node);
  3555. return;
  3556. }
  3557. // Add destructor calls for all variables that will go out of scope
  3558. // Put this clean up in a block to allow exception handler to understand them
  3559. bc->Block(true);
  3560. asCVariableScope *vs = variables;
  3561. while( !vs->isContinueScope )
  3562. {
  3563. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  3564. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  3565. vs = vs->parent;
  3566. }
  3567. bc->Block(false);
  3568. bc->InstrINT(asBC_JMP, continueLabels[continueLabels.GetLength()-1]);
  3569. }
  3570. void asCCompiler::CompileExpressionStatement(asCScriptNode *enode, asCByteCode *bc)
  3571. {
  3572. if( enode->firstChild )
  3573. {
  3574. // Compile the expression
  3575. asSExprContext expr(engine);
  3576. CompileAssignment(enode->firstChild, &expr);
  3577. // Must not have unused ambiguous names
  3578. if( expr.IsClassMethod() || expr.IsGlobalFunc() )
  3579. Error(TXT_INVALID_EXPRESSION_AMBIGUOUS_NAME, enode);
  3580. // If we get here and there is still an unprocessed property
  3581. // accessor, then process it as a get access. Don't call if there is
  3582. // already a compile error, or we might report an error that is not valid
  3583. if( !hasCompileErrors )
  3584. ProcessPropertyGetAccessor(&expr, enode);
  3585. // Pop the value from the stack
  3586. if( !expr.type.dataType.IsPrimitive() )
  3587. expr.bc.Instr(asBC_PopPtr);
  3588. // Release temporary variables used by expression
  3589. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3590. ProcessDeferredParams(&expr);
  3591. expr.bc.OptimizeLocally(tempVariableOffsets);
  3592. bc->AddCode(&expr.bc);
  3593. }
  3594. }
  3595. void asCCompiler::PrepareTemporaryObject(asCScriptNode *node, asSExprContext *ctx, bool forceOnHeap)
  3596. {
  3597. // If the object already is stored in temporary variable then nothing needs to be done
  3598. // Note, a type can be temporary without being a variable, in which case it is holding off
  3599. // on releasing a previously used object.
  3600. if( ctx->type.isTemporary && ctx->type.isVariable &&
  3601. !(forceOnHeap && !IsVariableOnHeap(ctx->type.stackOffset)) )
  3602. {
  3603. // If the temporary object is currently not a reference
  3604. // the expression needs to be reevaluated to a reference
  3605. if( !ctx->type.dataType.IsReference() )
  3606. {
  3607. ctx->bc.Instr(asBC_PopPtr);
  3608. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3609. ctx->type.dataType.MakeReference(true);
  3610. }
  3611. return;
  3612. }
  3613. // Allocate temporary variable
  3614. asCDataType dt = ctx->type.dataType;
  3615. dt.MakeReference(false);
  3616. dt.MakeReadOnly(false);
  3617. int offset = AllocateVariable(dt, true, forceOnHeap);
  3618. // Objects stored on the stack are not considered references
  3619. dt.MakeReference(IsVariableOnHeap(offset));
  3620. asCTypeInfo lvalue;
  3621. lvalue.Set(dt);
  3622. lvalue.isExplicitHandle = ctx->type.isExplicitHandle;
  3623. bool isExplicitHandle = ctx->type.isExplicitHandle;
  3624. CompileInitAsCopy(dt, offset, &ctx->bc, ctx, node, false);
  3625. // Push the reference to the temporary variable on the stack
  3626. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  3627. ctx->type.Set(dt);
  3628. ctx->type.isTemporary = true;
  3629. ctx->type.stackOffset = (short)offset;
  3630. ctx->type.isVariable = true;
  3631. ctx->type.isExplicitHandle = isExplicitHandle;
  3632. ctx->type.dataType.MakeReference(IsVariableOnHeap(offset));
  3633. }
  3634. void asCCompiler::CompileReturnStatement(asCScriptNode *rnode, asCByteCode *bc)
  3635. {
  3636. // Get return type and location
  3637. sVariable *v = variables->GetVariable("return");
  3638. // Basic validations
  3639. if( v->type.GetSizeOnStackDWords() > 0 && !rnode->firstChild )
  3640. {
  3641. Error(TXT_MUST_RETURN_VALUE, rnode);
  3642. return;
  3643. }
  3644. else if( v->type.GetSizeOnStackDWords() == 0 && rnode->firstChild )
  3645. {
  3646. Error(TXT_CANT_RETURN_VALUE, rnode);
  3647. return;
  3648. }
  3649. // Compile the expression
  3650. if( rnode->firstChild )
  3651. {
  3652. // Compile the expression
  3653. asSExprContext expr(engine);
  3654. int r = CompileAssignment(rnode->firstChild, &expr);
  3655. if( r < 0 ) return;
  3656. if( v->type.IsReference() )
  3657. {
  3658. // The expression that gives the reference must not use any of the
  3659. // variables that must be destroyed upon exit, because then it means
  3660. // reference will stay alive while the clean-up is done, which could
  3661. // potentially mean that the reference is invalidated by the clean-up.
  3662. //
  3663. // When the function is returning a reference, the clean-up of the
  3664. // variables must be done before the evaluation of the expression.
  3665. //
  3666. // A reference to a global variable, or a class member for class methods
  3667. // should be allowed to be returned.
  3668. if( !(expr.type.dataType.IsReference() ||
  3669. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle())) )
  3670. {
  3671. // Clean up the potential deferred parameters
  3672. ProcessDeferredParams(&expr);
  3673. Error(TXT_NOT_VALID_REFERENCE, rnode);
  3674. return;
  3675. }
  3676. // No references to local variables, temporary variables, or parameters
  3677. // are allowed to be returned, since they go out of scope when the function
  3678. // returns. Even reference parameters are disallowed, since it is not possible
  3679. // to know the scope of them. The exception is the 'this' pointer, which
  3680. // is treated by the compiler as a local variable, but isn't really so.
  3681. if( (expr.type.isVariable && !(expr.type.stackOffset == 0 && outFunc->objectType)) || expr.type.isTemporary )
  3682. {
  3683. // Clean up the potential deferred parameters
  3684. ProcessDeferredParams(&expr);
  3685. Error(TXT_CANNOT_RETURN_REF_TO_LOCAL, rnode);
  3686. return;
  3687. }
  3688. // The type must match exactly as we cannot convert
  3689. // the reference without loosing the original value
  3690. if( !(v->type.IsEqualExceptConst(expr.type.dataType) ||
  3691. (expr.type.dataType.IsObject() &&
  3692. !expr.type.dataType.IsObjectHandle() &&
  3693. v->type.IsEqualExceptRefAndConst(expr.type.dataType))) ||
  3694. (!v->type.IsReadOnly() && expr.type.dataType.IsReadOnly()) )
  3695. {
  3696. // Clean up the potential deferred parameters
  3697. ProcessDeferredParams(&expr);
  3698. asCString str;
  3699. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  3700. Error(str, rnode);
  3701. return;
  3702. }
  3703. // The expression must not have any deferred expressions, because the evaluation
  3704. // of these cannot be done without keeping the reference which is not safe
  3705. if( expr.deferredParams.GetLength() )
  3706. {
  3707. // Clean up the potential deferred parameters
  3708. ProcessDeferredParams(&expr);
  3709. Error(TXT_REF_CANT_BE_RETURNED_DEFERRED_PARAM, rnode);
  3710. return;
  3711. }
  3712. // Make sure the expression isn't using any local variables that
  3713. // will need to be cleaned up before the function completes
  3714. asCArray<int> usedVars;
  3715. expr.bc.GetVarsUsed(usedVars);
  3716. for( asUINT n = 0; n < usedVars.GetLength(); n++ )
  3717. {
  3718. int var = GetVariableSlot(usedVars[n]);
  3719. if( var != -1 )
  3720. {
  3721. asCDataType dt = variableAllocations[var];
  3722. if( dt.IsObject() )
  3723. {
  3724. ProcessDeferredParams(&expr);
  3725. Error(TXT_REF_CANT_BE_RETURNED_LOCAL_VARS, rnode);
  3726. return;
  3727. }
  3728. }
  3729. }
  3730. // All objects in the function must be cleaned up before the expression
  3731. // is evaluated, otherwise there is a possibility that the cleanup will
  3732. // invalidate the reference.
  3733. // Destroy the local variables before loading
  3734. // the reference into the register. This will
  3735. // be done before the expression is evaluated.
  3736. DestroyVariables(bc);
  3737. // For primitives the reference is already in the register,
  3738. // but for non-primitives the reference is on the stack so we
  3739. // need to load it into the register
  3740. if( !expr.type.dataType.IsPrimitive() )
  3741. {
  3742. if( !expr.type.dataType.IsObjectHandle() &&
  3743. expr.type.dataType.IsReference() )
  3744. expr.bc.Instr(asBC_RDSPtr);
  3745. expr.bc.Instr(asBC_PopRPtr);
  3746. }
  3747. // There are no temporaries to release so we're done
  3748. }
  3749. else // if( !v->type.IsReference() )
  3750. {
  3751. ProcessPropertyGetAccessor(&expr, rnode);
  3752. // Prepare the value for assignment
  3753. IsVariableInitialized(&expr.type, rnode->firstChild);
  3754. if( v->type.IsPrimitive() )
  3755. {
  3756. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  3757. // Implicitly convert the value to the return type
  3758. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  3759. // Verify that the conversion was successful
  3760. if( expr.type.dataType != v->type )
  3761. {
  3762. asCString str;
  3763. str.Format(TXT_NO_CONVERSION_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  3764. Error(str, rnode);
  3765. return;
  3766. }
  3767. else
  3768. {
  3769. ConvertToVariable(&expr);
  3770. // Clean up the local variables and process deferred parameters
  3771. DestroyVariables(&expr.bc);
  3772. ProcessDeferredParams(&expr);
  3773. ReleaseTemporaryVariable(expr.type, &expr.bc);
  3774. // Load the variable in the register
  3775. if( v->type.GetSizeOnStackDWords() == 1 )
  3776. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  3777. else
  3778. expr.bc.InstrSHORT(asBC_CpyVtoR8, expr.type.stackOffset);
  3779. }
  3780. }
  3781. else if( v->type.IsObject() )
  3782. {
  3783. // Value types are returned on the stack, in a location
  3784. // that has been reserved by the calling function.
  3785. if( outFunc->DoesReturnOnStack() )
  3786. {
  3787. // TODO: runtime optimize: If the return type has a constructor that takes the type of the expression,
  3788. // it should be called directly instead of first converting the expression and
  3789. // then copy the value.
  3790. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  3791. {
  3792. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  3793. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  3794. {
  3795. asCString str;
  3796. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  3797. Error(str, rnode->firstChild);
  3798. return;
  3799. }
  3800. }
  3801. int offset = outFunc->objectType ? -AS_PTR_SIZE : 0;
  3802. CompileInitAsCopy(v->type, offset, &expr.bc, &expr, rnode->firstChild, true);
  3803. // Clean up the local variables and process deferred parameters
  3804. DestroyVariables(&expr.bc);
  3805. ProcessDeferredParams(&expr);
  3806. }
  3807. else
  3808. {
  3809. asASSERT( v->type.GetObjectType()->flags & asOBJ_REF );
  3810. // Prepare the expression to be loaded into the object
  3811. // register. This will place the reference in local variable
  3812. PrepareArgument(&v->type, &expr, rnode->firstChild, false, 0);
  3813. // Pop the reference to the temporary variable
  3814. expr.bc.Instr(asBC_PopPtr);
  3815. // Clean up the local variables and process deferred parameters
  3816. DestroyVariables(&expr.bc);
  3817. ProcessDeferredParams(&expr);
  3818. // Load the object pointer into the object register
  3819. // LOADOBJ also clears the address in the variable
  3820. expr.bc.InstrSHORT(asBC_LOADOBJ, expr.type.stackOffset);
  3821. // LOADOBJ cleared the address in the variable so the object will not be freed
  3822. // here, but the temporary variable must still be freed so the slot can be reused
  3823. // By releasing without the bytecode we do just that.
  3824. ReleaseTemporaryVariable(expr.type, 0);
  3825. }
  3826. }
  3827. }
  3828. expr.bc.OptimizeLocally(tempVariableOffsets);
  3829. bc->AddCode(&expr.bc);
  3830. }
  3831. else
  3832. {
  3833. // For functions that don't return anything
  3834. // we just detroy the local variables
  3835. DestroyVariables(bc);
  3836. }
  3837. // Jump to the end of the function
  3838. bc->InstrINT(asBC_JMP, 0);
  3839. }
  3840. void asCCompiler::DestroyVariables(asCByteCode *bc)
  3841. {
  3842. // Call destructor on all variables except for the function parameters
  3843. // Put the clean-up in a block to allow exception handler to understand this
  3844. bc->Block(true);
  3845. asCVariableScope *vs = variables;
  3846. while( vs )
  3847. {
  3848. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  3849. if( vs->variables[n]->stackOffset > 0 )
  3850. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  3851. vs = vs->parent;
  3852. }
  3853. bc->Block(false);
  3854. }
  3855. void asCCompiler::AddVariableScope(bool isBreakScope, bool isContinueScope)
  3856. {
  3857. variables = asNEW(asCVariableScope)(variables);
  3858. if( variables == 0 )
  3859. {
  3860. // Out of memory
  3861. return;
  3862. }
  3863. variables->isBreakScope = isBreakScope;
  3864. variables->isContinueScope = isContinueScope;
  3865. }
  3866. void asCCompiler::RemoveVariableScope()
  3867. {
  3868. if( variables )
  3869. {
  3870. asCVariableScope *var = variables;
  3871. variables = variables->parent;
  3872. asDELETE(var,asCVariableScope);
  3873. }
  3874. }
  3875. void asCCompiler::Error(const asCString &msg, asCScriptNode *node)
  3876. {
  3877. asCString str;
  3878. int r = 0, c = 0;
  3879. asASSERT( node );
  3880. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3881. builder->WriteError(script->name, msg, r, c);
  3882. hasCompileErrors = true;
  3883. }
  3884. void asCCompiler::Warning(const asCString &msg, asCScriptNode *node)
  3885. {
  3886. asCString str;
  3887. int r = 0, c = 0;
  3888. asASSERT( node );
  3889. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3890. builder->WriteWarning(script->name, msg, r, c);
  3891. }
  3892. void asCCompiler::Information(const asCString &msg, asCScriptNode *node)
  3893. {
  3894. asCString str;
  3895. int r = 0, c = 0;
  3896. asASSERT( node );
  3897. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3898. builder->WriteInfo(script->name, msg, r, c, false);
  3899. }
  3900. void asCCompiler::PrintMatchingFuncs(asCArray<int> &funcs, asCScriptNode *node, asCObjectType *inType)
  3901. {
  3902. int r = 0, c = 0;
  3903. asASSERT( node );
  3904. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3905. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  3906. {
  3907. asCScriptFunction *func = builder->GetFunctionDescription(funcs[n]);
  3908. if( inType && func->funcType == asFUNC_VIRTUAL )
  3909. func = inType->virtualFunctionTable[func->vfTableIdx];
  3910. builder->WriteInfo(script->name, func->GetDeclaration(true, false, true), r, c, false);
  3911. }
  3912. }
  3913. int asCCompiler::AllocateVariableNotIn(const asCDataType &type, bool isTemporary, bool forceOnHeap, asSExprContext *ctx)
  3914. {
  3915. int l = int(reservedVariables.GetLength());
  3916. ctx->bc.GetVarsUsed(reservedVariables);
  3917. int var = AllocateVariable(type, isTemporary, forceOnHeap);
  3918. reservedVariables.SetLength(l);
  3919. return var;
  3920. }
  3921. int asCCompiler::AllocateVariable(const asCDataType &type, bool isTemporary, bool forceOnHeap)
  3922. {
  3923. asCDataType t(type);
  3924. t.MakeReference(false);
  3925. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 1 )
  3926. t.SetTokenType(ttInt);
  3927. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 2 )
  3928. t.SetTokenType(ttDouble);
  3929. // Only null handles have the token type unrecognized token
  3930. asASSERT( t.IsObjectHandle() || t.GetTokenType() != ttUnrecognizedToken );
  3931. bool isOnHeap = true;
  3932. if( t.IsPrimitive() ||
  3933. (t.GetObjectType() && (t.GetObjectType()->GetFlags() & asOBJ_VALUE) && !forceOnHeap) )
  3934. {
  3935. // Primitives and value types (unless overridden) are allocated on the stack
  3936. isOnHeap = false;
  3937. }
  3938. // Find a free location with the same type
  3939. for( asUINT n = 0; n < freeVariables.GetLength(); n++ )
  3940. {
  3941. int slot = freeVariables[n];
  3942. if( variableAllocations[slot].IsEqualExceptConst(t) &&
  3943. variableIsTemporary[slot] == isTemporary &&
  3944. variableIsOnHeap[slot] == isOnHeap )
  3945. {
  3946. // We can't return by slot, must count variable sizes
  3947. int offset = GetVariableOffset(slot);
  3948. // Verify that it is not in the list of reserved variables
  3949. bool isUsed = false;
  3950. if( reservedVariables.GetLength() )
  3951. isUsed = reservedVariables.Exists(offset);
  3952. if( !isUsed )
  3953. {
  3954. if( n != freeVariables.GetLength() - 1 )
  3955. freeVariables[n] = freeVariables.PopLast();
  3956. else
  3957. freeVariables.PopLast();
  3958. if( isTemporary )
  3959. tempVariables.PushLast(offset);
  3960. return offset;
  3961. }
  3962. }
  3963. }
  3964. variableAllocations.PushLast(t);
  3965. variableIsTemporary.PushLast(isTemporary);
  3966. variableIsOnHeap.PushLast(isOnHeap);
  3967. int offset = GetVariableOffset((int)variableAllocations.GetLength()-1);
  3968. if( isTemporary )
  3969. {
  3970. // Add offset to the currently allocated temporary variables
  3971. tempVariables.PushLast(offset);
  3972. // Add offset to all known offsets to temporary variables, whether allocated or not
  3973. tempVariableOffsets.PushLast(offset);
  3974. }
  3975. return offset;
  3976. }
  3977. int asCCompiler::GetVariableOffset(int varIndex)
  3978. {
  3979. // Return offset to the last dword on the stack
  3980. // Start at 1 as offset 0 is reserved for the this pointer (or first argument for global functions)
  3981. int varOffset = 1;
  3982. // Skip lower variables
  3983. for( int n = 0; n < varIndex; n++ )
  3984. {
  3985. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  3986. varOffset += variableAllocations[n].GetSizeInMemoryDWords();
  3987. else
  3988. varOffset += variableAllocations[n].GetSizeOnStackDWords();
  3989. }
  3990. if( varIndex < (int)variableAllocations.GetLength() )
  3991. {
  3992. // For variables larger than 1 dword the returned offset should be to the last dword
  3993. int size;
  3994. if( !variableIsOnHeap[varIndex] && variableAllocations[varIndex].IsObject() )
  3995. size = variableAllocations[varIndex].GetSizeInMemoryDWords();
  3996. else
  3997. size = variableAllocations[varIndex].GetSizeOnStackDWords();
  3998. if( size > 1 )
  3999. varOffset += size-1;
  4000. }
  4001. return varOffset;
  4002. }
  4003. int asCCompiler::GetVariableSlot(int offset)
  4004. {
  4005. int varOffset = 1;
  4006. for( asUINT n = 0; n < variableAllocations.GetLength(); n++ )
  4007. {
  4008. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  4009. varOffset += -1 + variableAllocations[n].GetSizeInMemoryDWords();
  4010. else
  4011. varOffset += -1 + variableAllocations[n].GetSizeOnStackDWords();
  4012. if( varOffset == offset )
  4013. return n;
  4014. varOffset++;
  4015. }
  4016. return -1;
  4017. }
  4018. bool asCCompiler::IsVariableOnHeap(int offset)
  4019. {
  4020. int varSlot = GetVariableSlot(offset);
  4021. if( varSlot < 0 )
  4022. {
  4023. // This happens for function arguments that are considered as on the heap
  4024. return true;
  4025. }
  4026. return variableIsOnHeap[varSlot];
  4027. }
  4028. void asCCompiler::DeallocateVariable(int offset)
  4029. {
  4030. // Remove temporary variable
  4031. int n;
  4032. for( n = 0; n < (int)tempVariables.GetLength(); n++ )
  4033. {
  4034. if( offset == tempVariables[n] )
  4035. {
  4036. if( n == (int)tempVariables.GetLength()-1 )
  4037. tempVariables.PopLast();
  4038. else
  4039. tempVariables[n] = tempVariables.PopLast();
  4040. break;
  4041. }
  4042. }
  4043. n = GetVariableSlot(offset);
  4044. if( n != -1 )
  4045. {
  4046. freeVariables.PushLast(n);
  4047. return;
  4048. }
  4049. // We might get here if the variable was implicitly declared
  4050. // because it was use before a formal declaration, in this case
  4051. // the offset is 0x7FFF
  4052. asASSERT(offset == 0x7FFF);
  4053. }
  4054. void asCCompiler::ReleaseTemporaryVariable(asCTypeInfo &t, asCByteCode *bc)
  4055. {
  4056. if( t.isTemporary )
  4057. {
  4058. ReleaseTemporaryVariable(t.stackOffset, bc);
  4059. t.isTemporary = false;
  4060. }
  4061. }
  4062. void asCCompiler::ReleaseTemporaryVariable(int offset, asCByteCode *bc)
  4063. {
  4064. asASSERT( tempVariables.Exists(offset) );
  4065. if( bc )
  4066. {
  4067. // We need to call the destructor on the true variable type
  4068. int n = GetVariableSlot(offset);
  4069. asASSERT( n >= 0 );
  4070. if( n >= 0 )
  4071. {
  4072. asCDataType dt = variableAllocations[n];
  4073. bool isOnHeap = variableIsOnHeap[n];
  4074. // Call destructor
  4075. CallDestructor(dt, offset, isOnHeap, bc);
  4076. }
  4077. }
  4078. DeallocateVariable(offset);
  4079. }
  4080. void asCCompiler::Dereference(asSExprContext *ctx, bool generateCode)
  4081. {
  4082. if( ctx->type.dataType.IsReference() )
  4083. {
  4084. if( ctx->type.dataType.IsObject() )
  4085. {
  4086. ctx->type.dataType.MakeReference(false);
  4087. if( generateCode )
  4088. ctx->bc.Instr(asBC_RDSPtr);
  4089. }
  4090. else
  4091. {
  4092. // This should never happen as primitives are treated differently
  4093. asASSERT(false);
  4094. }
  4095. }
  4096. }
  4097. bool asCCompiler::IsVariableInitialized(asCTypeInfo *type, asCScriptNode *node)
  4098. {
  4099. // No need to check if there is no variable scope
  4100. if( variables == 0 ) return true;
  4101. // Temporary variables are assumed to be initialized
  4102. if( type->isTemporary ) return true;
  4103. // Verify that it is a variable
  4104. if( !type->isVariable ) return true;
  4105. // Find the variable
  4106. sVariable *v = variables->GetVariableByOffset(type->stackOffset);
  4107. // The variable isn't found if it is a constant, in which case it is guaranteed to be initialized
  4108. if( v == 0 ) return true;
  4109. if( v->isInitialized ) return true;
  4110. // Complex types don't need this test
  4111. if( v->type.IsObject() ) return true;
  4112. // Mark as initialized so that the user will not be bothered again
  4113. v->isInitialized = true;
  4114. // Write warning
  4115. asCString str;
  4116. str.Format(TXT_s_NOT_INITIALIZED, (const char *)v->name.AddressOf());
  4117. Warning(str, node);
  4118. return false;
  4119. }
  4120. void asCCompiler::PrepareOperand(asSExprContext *ctx, asCScriptNode *node)
  4121. {
  4122. // Check if the variable is initialized (if it indeed is a variable)
  4123. IsVariableInitialized(&ctx->type, node);
  4124. asCDataType to = ctx->type.dataType;
  4125. to.MakeReference(false);
  4126. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  4127. ProcessDeferredParams(ctx);
  4128. }
  4129. void asCCompiler::PrepareForAssignment(asCDataType *lvalue, asSExprContext *rctx, asCScriptNode *node, bool toTemporary, asSExprContext *lvalueExpr)
  4130. {
  4131. // Reserve the temporary variables used in the lvalue expression so they won't end up being used by the rvalue too
  4132. int l = int(reservedVariables.GetLength());
  4133. if( lvalueExpr ) lvalueExpr->bc.GetVarsUsed(reservedVariables);
  4134. ProcessPropertyGetAccessor(rctx, node);
  4135. // Make sure the rvalue is initialized if it is a variable
  4136. IsVariableInitialized(&rctx->type, node);
  4137. if( lvalue->IsPrimitive() )
  4138. {
  4139. if( rctx->type.dataType.IsPrimitive() )
  4140. {
  4141. if( rctx->type.dataType.IsReference() )
  4142. {
  4143. // Cannot do implicit conversion of references so we first convert the reference to a variable
  4144. ConvertToVariableNotIn(rctx, lvalueExpr);
  4145. }
  4146. }
  4147. // Implicitly convert the value to the right type
  4148. ImplicitConversion(rctx, *lvalue, node, asIC_IMPLICIT_CONV);
  4149. // Check data type
  4150. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  4151. {
  4152. asCString str;
  4153. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  4154. Error(str, node);
  4155. rctx->type.SetDummy();
  4156. }
  4157. // Make sure the rvalue is a variable
  4158. if( !rctx->type.isVariable )
  4159. ConvertToVariableNotIn(rctx, lvalueExpr);
  4160. }
  4161. else
  4162. {
  4163. asCDataType to = *lvalue;
  4164. to.MakeReference(false);
  4165. // TODO: ImplicitConversion should know to do this by itself
  4166. // First convert to a handle which will do a reference cast
  4167. if( !lvalue->IsObjectHandle() &&
  4168. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  4169. to.MakeHandle(true);
  4170. // Don't allow the implicit conversion to create an object
  4171. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, !toTemporary);
  4172. if( !lvalue->IsObjectHandle() &&
  4173. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  4174. {
  4175. // Then convert to a reference, which will validate the handle
  4176. to.MakeHandle(false);
  4177. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, !toTemporary);
  4178. }
  4179. // Check data type
  4180. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  4181. {
  4182. asCString str;
  4183. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  4184. Error(str, node);
  4185. }
  4186. else
  4187. {
  4188. // If the assignment will be made with the copy behaviour then the rvalue must not be a reference
  4189. if( lvalue->IsObject() )
  4190. asASSERT(!rctx->type.dataType.IsReference());
  4191. }
  4192. }
  4193. // Unreserve variables
  4194. reservedVariables.SetLength(l);
  4195. }
  4196. bool asCCompiler::IsLValue(asCTypeInfo &type)
  4197. {
  4198. if( !type.isLValue ) return false;
  4199. if( type.dataType.IsReadOnly() ) return false;
  4200. if( !type.dataType.IsObject() && !type.isVariable && !type.dataType.IsReference() ) return false;
  4201. return true;
  4202. }
  4203. int asCCompiler::PerformAssignment(asCTypeInfo *lvalue, asCTypeInfo *rvalue, asCByteCode *bc, asCScriptNode *node)
  4204. {
  4205. if( lvalue->dataType.IsReadOnly() )
  4206. {
  4207. Error(TXT_REF_IS_READ_ONLY, node);
  4208. return -1;
  4209. }
  4210. if( lvalue->dataType.IsPrimitive() )
  4211. {
  4212. if( lvalue->isVariable )
  4213. {
  4214. // Copy the value between the variables directly
  4215. if( lvalue->dataType.GetSizeInMemoryDWords() == 1 )
  4216. bc->InstrW_W(asBC_CpyVtoV4, lvalue->stackOffset, rvalue->stackOffset);
  4217. else
  4218. bc->InstrW_W(asBC_CpyVtoV8, lvalue->stackOffset, rvalue->stackOffset);
  4219. // Mark variable as initialized
  4220. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  4221. if( v ) v->isInitialized = true;
  4222. }
  4223. else if( lvalue->dataType.IsReference() )
  4224. {
  4225. // Copy the value of the variable to the reference in the register
  4226. int s = lvalue->dataType.GetSizeInMemoryBytes();
  4227. if( s == 1 )
  4228. bc->InstrSHORT(asBC_WRTV1, rvalue->stackOffset);
  4229. else if( s == 2 )
  4230. bc->InstrSHORT(asBC_WRTV2, rvalue->stackOffset);
  4231. else if( s == 4 )
  4232. bc->InstrSHORT(asBC_WRTV4, rvalue->stackOffset);
  4233. else if( s == 8 )
  4234. bc->InstrSHORT(asBC_WRTV8, rvalue->stackOffset);
  4235. }
  4236. else
  4237. {
  4238. Error(TXT_NOT_VALID_LVALUE, node);
  4239. return -1;
  4240. }
  4241. }
  4242. else if( !lvalue->isExplicitHandle )
  4243. {
  4244. asSExprContext ctx(engine);
  4245. ctx.type = *lvalue;
  4246. Dereference(&ctx, true);
  4247. *lvalue = ctx.type;
  4248. bc->AddCode(&ctx.bc);
  4249. asSTypeBehaviour *beh = lvalue->dataType.GetBehaviour();
  4250. if( beh->copy && beh->copy != engine->scriptTypeBehaviours.beh.copy )
  4251. {
  4252. asSExprContext res(engine);
  4253. PerformFunctionCall(beh->copy, &res, false, 0, lvalue->dataType.GetObjectType());
  4254. bc->AddCode(&res.bc);
  4255. *lvalue = res.type;
  4256. }
  4257. else if( beh->copy == engine->scriptTypeBehaviours.beh.copy )
  4258. {
  4259. // Call the default copy operator for script classes
  4260. // This is done differently because the default copy operator
  4261. // is registered as returning int&, but in reality it returns
  4262. // a reference to the object.
  4263. // TODO: Avoid this special case by implementing a copystub for
  4264. // script classes that uses the default copy operator
  4265. bc->Call(asBC_CALLSYS, beh->copy, 2*AS_PTR_SIZE);
  4266. bc->Instr(asBC_PshRPtr);
  4267. }
  4268. else
  4269. {
  4270. // Default copy operator
  4271. if( lvalue->dataType.GetSizeInMemoryDWords() == 0 ||
  4272. !(lvalue->dataType.GetObjectType()->flags & asOBJ_POD) )
  4273. {
  4274. asCString msg;
  4275. msg.Format(TXT_NO_DEFAULT_COPY_OP_FOR_s, lvalue->dataType.GetObjectType()->name.AddressOf());
  4276. Error(msg, node);
  4277. return -1;
  4278. }
  4279. // Copy larger data types from a reference
  4280. // TODO: runtime optimize: COPY should pop both arguments and store the reference in the register.
  4281. bc->InstrSHORT_DW(asBC_COPY, (short)lvalue->dataType.GetSizeInMemoryDWords(), engine->GetTypeIdFromDataType(lvalue->dataType));
  4282. }
  4283. }
  4284. else
  4285. {
  4286. // TODO: The object handle can be stored in a variable as well
  4287. if( !lvalue->dataType.IsReference() )
  4288. {
  4289. Error(TXT_NOT_VALID_REFERENCE, node);
  4290. return -1;
  4291. }
  4292. bc->InstrPTR(asBC_REFCPY, lvalue->dataType.GetObjectType());
  4293. // Mark variable as initialized
  4294. if( variables )
  4295. {
  4296. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  4297. if( v ) v->isInitialized = true;
  4298. }
  4299. }
  4300. return 0;
  4301. }
  4302. bool asCCompiler::CompileRefCast(asSExprContext *ctx, const asCDataType &to, bool isExplicit, asCScriptNode *node, bool generateCode)
  4303. {
  4304. bool conversionDone = false;
  4305. asCArray<int> ops;
  4306. asUINT n;
  4307. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT )
  4308. {
  4309. // We need it to be a reference
  4310. if( !ctx->type.dataType.IsReference() )
  4311. {
  4312. asCDataType to = ctx->type.dataType;
  4313. to.MakeReference(true);
  4314. ImplicitConversion(ctx, to, 0, isExplicit ? asIC_EXPLICIT_REF_CAST : asIC_IMPLICIT_CONV, generateCode);
  4315. }
  4316. if( isExplicit )
  4317. {
  4318. // Allow dynamic cast between object handles (only for script objects).
  4319. // At run time this may result in a null handle,
  4320. // which when used will throw an exception
  4321. conversionDone = true;
  4322. if( generateCode )
  4323. {
  4324. ctx->bc.InstrDWORD(asBC_Cast, engine->GetTypeIdFromDataType(to));
  4325. // Allocate a temporary variable for the returned object
  4326. int returnOffset = AllocateVariable(to, true);
  4327. // Move the pointer from the object register to the temporary variable
  4328. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  4329. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  4330. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4331. ctx->type.SetVariable(to, returnOffset, true);
  4332. ctx->type.dataType.MakeReference(true);
  4333. }
  4334. else
  4335. {
  4336. ctx->type.dataType = to;
  4337. ctx->type.dataType.MakeReference(true);
  4338. }
  4339. }
  4340. else
  4341. {
  4342. if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  4343. {
  4344. conversionDone = true;
  4345. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4346. }
  4347. }
  4348. }
  4349. else
  4350. {
  4351. // Find a suitable registered behaviour
  4352. asSTypeBehaviour *beh = &ctx->type.dataType.GetObjectType()->beh;
  4353. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  4354. {
  4355. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  4356. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  4357. {
  4358. int funcId = beh->operators[n+1];
  4359. // Is the operator for the output type?
  4360. asCScriptFunction *func = engine->scriptFunctions[funcId];
  4361. if( func->returnType.GetObjectType() != to.GetObjectType() )
  4362. continue;
  4363. ops.PushLast(funcId);
  4364. }
  4365. }
  4366. // It shouldn't be possible to have more than one
  4367. asASSERT( ops.GetLength() <= 1 );
  4368. // Should only have one behaviour for each output type
  4369. if( ops.GetLength() == 1 )
  4370. {
  4371. if( generateCode )
  4372. {
  4373. // TODO: runtime optimize: Instead of producing bytecode for checking if the handle is
  4374. // null, we can create a special CALLSYS instruction that checks
  4375. // if the object pointer is null and if so sets the object register
  4376. // to null directly without executing the function.
  4377. //
  4378. // Alternatively I could force the ref cast behaviours be global
  4379. // functions with 1 parameter, even though they should still be
  4380. // registered with RegisterObjectBehaviour()
  4381. // Add code to avoid calling the cast behaviour if the handle is already null,
  4382. // because that will raise a null pointer exception due to the cast behaviour
  4383. // being a class method, and the this pointer cannot be null.
  4384. if( !ctx->type.isVariable )
  4385. {
  4386. Dereference(ctx, true);
  4387. ConvertToVariable(ctx);
  4388. }
  4389. // The reference on the stack will not be used
  4390. ctx->bc.Instr(asBC_PopPtr);
  4391. // TODO: runtime optimize: should have immediate comparison for null pointer
  4392. int offset = AllocateVariable(asCDataType::CreateNullHandle(), true);
  4393. // TODO: runtime optimize: ClrVPtr is not necessary, because the VM should initialize the variable to null anyway (it is currently not done for null pointers though)
  4394. ctx->bc.InstrSHORT(asBC_ClrVPtr, (asWORD)offset);
  4395. ctx->bc.InstrW_W(asBC_CmpPtr, ctx->type.stackOffset, offset);
  4396. DeallocateVariable(offset);
  4397. int afterLabel = nextLabel++;
  4398. ctx->bc.InstrDWORD(asBC_JZ, afterLabel);
  4399. // Call the cast operator
  4400. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  4401. ctx->bc.Instr(asBC_RDSPtr);
  4402. ctx->type.dataType.MakeReference(false);
  4403. asCArray<asSExprContext *> args;
  4404. MakeFunctionCall(ctx, ops[0], ctx->type.dataType.GetObjectType(), args, node);
  4405. ctx->bc.Instr(asBC_PopPtr);
  4406. int endLabel = nextLabel++;
  4407. ctx->bc.InstrINT(asBC_JMP, endLabel);
  4408. ctx->bc.Label((short)afterLabel);
  4409. // Make a NULL pointer
  4410. ctx->bc.InstrSHORT(asBC_ClrVPtr, ctx->type.stackOffset);
  4411. ctx->bc.Label((short)endLabel);
  4412. // Push the reference to the handle on the stack
  4413. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  4414. }
  4415. else
  4416. {
  4417. asCScriptFunction *func = engine->scriptFunctions[ops[0]];
  4418. ctx->type.Set(func->returnType);
  4419. }
  4420. }
  4421. else if( ops.GetLength() == 0 )
  4422. {
  4423. // Check for the generic ref cast behaviour
  4424. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  4425. {
  4426. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  4427. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  4428. {
  4429. int funcId = beh->operators[n+1];
  4430. // Does the operator take the ?&out parameter?
  4431. asCScriptFunction *func = engine->scriptFunctions[funcId];
  4432. if( func->parameterTypes.GetLength() != 1 ||
  4433. func->parameterTypes[0].GetTokenType() != ttQuestion ||
  4434. func->inOutFlags[0] != asTM_OUTREF )
  4435. continue;
  4436. ops.PushLast(funcId);
  4437. }
  4438. }
  4439. // It shouldn't be possible to have more than one
  4440. asASSERT( ops.GetLength() <= 1 );
  4441. if( ops.GetLength() == 1 )
  4442. {
  4443. if( generateCode )
  4444. {
  4445. asASSERT(to.IsObjectHandle());
  4446. // Allocate a temporary variable of the requested handle type
  4447. int stackOffset = AllocateVariableNotIn(to, true, false, ctx);
  4448. // Pass the reference of that variable to the function as output parameter
  4449. asCDataType toRef(to);
  4450. toRef.MakeReference(true);
  4451. asCArray<asSExprContext *> args;
  4452. asSExprContext arg(engine);
  4453. arg.bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  4454. // Don't mark the variable as temporary, so it won't be freed too early
  4455. arg.type.SetVariable(toRef, stackOffset, false);
  4456. arg.type.isLValue = true;
  4457. arg.type.isExplicitHandle = true;
  4458. args.PushLast(&arg);
  4459. // Call the behaviour method
  4460. MakeFunctionCall(ctx, ops[0], ctx->type.dataType.GetObjectType(), args, node);
  4461. // Use the reference to the variable as the result of the expression
  4462. // Now we can mark the variable as temporary
  4463. ctx->type.SetVariable(toRef, stackOffset, true);
  4464. ctx->bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  4465. }
  4466. else
  4467. {
  4468. // All casts are legal
  4469. ctx->type.Set(to);
  4470. }
  4471. }
  4472. }
  4473. }
  4474. return conversionDone;
  4475. }
  4476. asUINT asCCompiler::ImplicitConvPrimitiveToPrimitive(asSExprContext *ctx, const asCDataType &toOrig, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  4477. {
  4478. asCDataType to = toOrig;
  4479. to.MakeReference(false);
  4480. asASSERT( !ctx->type.dataType.IsReference() );
  4481. // Maybe no conversion is needed
  4482. if( to.IsEqualExceptConst(ctx->type.dataType) )
  4483. {
  4484. // A primitive is const or not
  4485. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4486. return asCC_NO_CONV;
  4487. }
  4488. // Is the conversion an ambiguous enum value?
  4489. if( ctx->enumValue != "" )
  4490. {
  4491. if( to.IsEnumType() )
  4492. {
  4493. // Attempt to resolve an ambiguous enum value
  4494. asCDataType out;
  4495. asDWORD value;
  4496. if( builder->GetEnumValueFromObjectType(to.GetObjectType(), ctx->enumValue.AddressOf(), out, value) )
  4497. {
  4498. ctx->type.SetConstantDW(out, value);
  4499. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4500. // It wasn't really a conversion. The compiler just resolved the ambiguity (or not)
  4501. return asCC_NO_CONV;
  4502. }
  4503. }
  4504. // The enum value is ambiguous
  4505. if( node && generateCode )
  4506. Error(TXT_FOUND_MULTIPLE_ENUM_VALUES, node);
  4507. // Set a dummy to allow the compiler to try to continue the conversion
  4508. ctx->type.SetDummy();
  4509. }
  4510. // Determine the cost of this conversion
  4511. asUINT cost = asCC_NO_CONV;
  4512. if( (to.IsIntegerType() || to.IsUnsignedType()) && (ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType()) )
  4513. cost = asCC_INT_FLOAT_CONV;
  4514. else if( (to.IsFloatType() || to.IsDoubleType()) && (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType()) )
  4515. cost = asCC_INT_FLOAT_CONV;
  4516. else if( to.IsUnsignedType() && ctx->type.dataType.IsIntegerType() )
  4517. cost = asCC_SIGNED_CONV;
  4518. else if( to.IsIntegerType() && ctx->type.dataType.IsUnsignedType() )
  4519. cost = asCC_SIGNED_CONV;
  4520. else if( to.GetSizeInMemoryBytes() || ctx->type.dataType.GetSizeInMemoryBytes() )
  4521. cost = asCC_PRIMITIVE_SIZE_CONV;
  4522. // Start by implicitly converting constant values
  4523. if( ctx->type.isConstant )
  4524. {
  4525. ImplicitConversionConstant(ctx, to, node, convType);
  4526. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4527. return cost;
  4528. }
  4529. // Allow implicit conversion between numbers
  4530. if( generateCode )
  4531. {
  4532. // When generating the code the decision has already been made, so we don't bother determining the cost
  4533. // Convert smaller types to 32bit first
  4534. int s = ctx->type.dataType.GetSizeInMemoryBytes();
  4535. if( s < 4 )
  4536. {
  4537. ConvertToTempVariable(ctx);
  4538. if( ctx->type.dataType.IsIntegerType() )
  4539. {
  4540. if( s == 1 )
  4541. ctx->bc.InstrSHORT(asBC_sbTOi, ctx->type.stackOffset);
  4542. else if( s == 2 )
  4543. ctx->bc.InstrSHORT(asBC_swTOi, ctx->type.stackOffset);
  4544. ctx->type.dataType.SetTokenType(ttInt);
  4545. }
  4546. else if( ctx->type.dataType.IsUnsignedType() )
  4547. {
  4548. if( s == 1 )
  4549. ctx->bc.InstrSHORT(asBC_ubTOi, ctx->type.stackOffset);
  4550. else if( s == 2 )
  4551. ctx->bc.InstrSHORT(asBC_uwTOi, ctx->type.stackOffset);
  4552. ctx->type.dataType.SetTokenType(ttUInt);
  4553. }
  4554. }
  4555. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1 && !to.IsEnumType()) ||
  4556. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  4557. {
  4558. if( ctx->type.dataType.IsIntegerType() ||
  4559. ctx->type.dataType.IsUnsignedType() )
  4560. {
  4561. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4562. {
  4563. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4564. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4565. }
  4566. else
  4567. {
  4568. ConvertToTempVariable(ctx);
  4569. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4570. int offset = AllocateVariable(to, true);
  4571. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  4572. ctx->type.SetVariable(to, offset, true);
  4573. }
  4574. }
  4575. else if( ctx->type.dataType.IsFloatType() )
  4576. {
  4577. ConvertToTempVariable(ctx);
  4578. ctx->bc.InstrSHORT(asBC_fTOi, ctx->type.stackOffset);
  4579. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4580. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4581. if( convType != asIC_EXPLICIT_VAL_CAST )
  4582. Warning(TXT_FLOAT_CONV_TO_INT_CAUSE_TRUNC, node);
  4583. }
  4584. else if( ctx->type.dataType.IsDoubleType() )
  4585. {
  4586. ConvertToTempVariable(ctx);
  4587. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4588. int offset = AllocateVariable(to, true);
  4589. ctx->bc.InstrW_W(asBC_dTOi, offset, ctx->type.stackOffset);
  4590. ctx->type.SetVariable(to, offset, true);
  4591. if( convType != asIC_EXPLICIT_VAL_CAST )
  4592. Warning(TXT_FLOAT_CONV_TO_INT_CAUSE_TRUNC, node);
  4593. }
  4594. // Convert to smaller integer if necessary
  4595. int s = to.GetSizeInMemoryBytes();
  4596. if( s < 4 )
  4597. {
  4598. ConvertToTempVariable(ctx);
  4599. if( s == 1 )
  4600. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  4601. else if( s == 2 )
  4602. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  4603. }
  4604. }
  4605. else if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  4606. {
  4607. if( ctx->type.dataType.IsIntegerType() ||
  4608. ctx->type.dataType.IsUnsignedType() )
  4609. {
  4610. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4611. {
  4612. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4613. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4614. }
  4615. else
  4616. {
  4617. ConvertToTempVariable(ctx);
  4618. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4619. int offset = AllocateVariable(to, true);
  4620. if( ctx->type.dataType.IsUnsignedType() )
  4621. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  4622. else
  4623. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  4624. ctx->type.SetVariable(to, offset, true);
  4625. }
  4626. }
  4627. else if( ctx->type.dataType.IsFloatType() )
  4628. {
  4629. ConvertToTempVariable(ctx);
  4630. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4631. int offset = AllocateVariable(to, true);
  4632. ctx->bc.InstrW_W(asBC_fTOi64, offset, ctx->type.stackOffset);
  4633. ctx->type.SetVariable(to, offset, true);
  4634. if( convType != asIC_EXPLICIT_VAL_CAST )
  4635. Warning(TXT_FLOAT_CONV_TO_INT_CAUSE_TRUNC, node);
  4636. }
  4637. else if( ctx->type.dataType.IsDoubleType() )
  4638. {
  4639. ConvertToTempVariable(ctx);
  4640. ctx->bc.InstrSHORT(asBC_dTOi64, ctx->type.stackOffset);
  4641. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4642. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4643. if( convType != asIC_EXPLICIT_VAL_CAST )
  4644. Warning(TXT_FLOAT_CONV_TO_INT_CAUSE_TRUNC, node);
  4645. }
  4646. }
  4647. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  4648. {
  4649. if( ctx->type.dataType.IsIntegerType() ||
  4650. ctx->type.dataType.IsUnsignedType() )
  4651. {
  4652. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4653. {
  4654. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4655. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4656. }
  4657. else
  4658. {
  4659. ConvertToTempVariable(ctx);
  4660. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4661. int offset = AllocateVariable(to, true);
  4662. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  4663. ctx->type.SetVariable(to, offset, true);
  4664. }
  4665. }
  4666. else if( ctx->type.dataType.IsFloatType() )
  4667. {
  4668. ConvertToTempVariable(ctx);
  4669. ctx->bc.InstrSHORT(asBC_fTOu, ctx->type.stackOffset);
  4670. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4671. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4672. if( convType != asIC_EXPLICIT_VAL_CAST )
  4673. Warning(TXT_FLOAT_CONV_TO_INT_CAUSE_TRUNC, node);
  4674. }
  4675. else if( ctx->type.dataType.IsDoubleType() )
  4676. {
  4677. ConvertToTempVariable(ctx);
  4678. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4679. int offset = AllocateVariable(to, true);
  4680. ctx->bc.InstrW_W(asBC_dTOu, offset, ctx->type.stackOffset);
  4681. ctx->type.SetVariable(to, offset, true);
  4682. if( convType != asIC_EXPLICIT_VAL_CAST )
  4683. Warning(TXT_FLOAT_CONV_TO_INT_CAUSE_TRUNC, node);
  4684. }
  4685. // Convert to smaller integer if necessary
  4686. int s = to.GetSizeInMemoryBytes();
  4687. if( s < 4 )
  4688. {
  4689. ConvertToTempVariable(ctx);
  4690. if( s == 1 )
  4691. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  4692. else if( s == 2 )
  4693. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  4694. }
  4695. }
  4696. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  4697. {
  4698. if( ctx->type.dataType.IsIntegerType() ||
  4699. ctx->type.dataType.IsUnsignedType() )
  4700. {
  4701. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4702. {
  4703. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4704. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4705. }
  4706. else
  4707. {
  4708. ConvertToTempVariable(ctx);
  4709. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4710. int offset = AllocateVariable(to, true);
  4711. if( ctx->type.dataType.IsUnsignedType() )
  4712. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  4713. else
  4714. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  4715. ctx->type.SetVariable(to, offset, true);
  4716. }
  4717. }
  4718. else if( ctx->type.dataType.IsFloatType() )
  4719. {
  4720. ConvertToTempVariable(ctx);
  4721. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4722. int offset = AllocateVariable(to, true);
  4723. ctx->bc.InstrW_W(asBC_fTOu64, offset, ctx->type.stackOffset);
  4724. ctx->type.SetVariable(to, offset, true);
  4725. if( convType != asIC_EXPLICIT_VAL_CAST )
  4726. Warning(TXT_FLOAT_CONV_TO_INT_CAUSE_TRUNC, node);
  4727. }
  4728. else if( ctx->type.dataType.IsDoubleType() )
  4729. {
  4730. ConvertToTempVariable(ctx);
  4731. ctx->bc.InstrSHORT(asBC_dTOu64, ctx->type.stackOffset);
  4732. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4733. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4734. if( convType != asIC_EXPLICIT_VAL_CAST )
  4735. Warning(TXT_FLOAT_CONV_TO_INT_CAUSE_TRUNC, node);
  4736. }
  4737. }
  4738. else if( to.IsFloatType() )
  4739. {
  4740. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4741. {
  4742. ConvertToTempVariable(ctx);
  4743. ctx->bc.InstrSHORT(asBC_iTOf, ctx->type.stackOffset);
  4744. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4745. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4746. }
  4747. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4748. {
  4749. ConvertToTempVariable(ctx);
  4750. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4751. int offset = AllocateVariable(to, true);
  4752. ctx->bc.InstrW_W(asBC_i64TOf, offset, ctx->type.stackOffset);
  4753. ctx->type.SetVariable(to, offset, true);
  4754. }
  4755. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4756. {
  4757. ConvertToTempVariable(ctx);
  4758. ctx->bc.InstrSHORT(asBC_uTOf, ctx->type.stackOffset);
  4759. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4760. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4761. }
  4762. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4763. {
  4764. ConvertToTempVariable(ctx);
  4765. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4766. int offset = AllocateVariable(to, true);
  4767. ctx->bc.InstrW_W(asBC_u64TOf, offset, ctx->type.stackOffset);
  4768. ctx->type.SetVariable(to, offset, true);
  4769. }
  4770. else if( ctx->type.dataType.IsDoubleType() )
  4771. {
  4772. ConvertToTempVariable(ctx);
  4773. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4774. int offset = AllocateVariable(to, true);
  4775. ctx->bc.InstrW_W(asBC_dTOf, offset, ctx->type.stackOffset);
  4776. ctx->type.SetVariable(to, offset, true);
  4777. }
  4778. }
  4779. else if( to.IsDoubleType() )
  4780. {
  4781. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4782. {
  4783. ConvertToTempVariable(ctx);
  4784. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4785. int offset = AllocateVariable(to, true);
  4786. ctx->bc.InstrW_W(asBC_iTOd, offset, ctx->type.stackOffset);
  4787. ctx->type.SetVariable(to, offset, true);
  4788. }
  4789. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4790. {
  4791. ConvertToTempVariable(ctx);
  4792. ctx->bc.InstrSHORT(asBC_i64TOd, ctx->type.stackOffset);
  4793. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4794. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4795. }
  4796. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  4797. {
  4798. ConvertToTempVariable(ctx);
  4799. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4800. int offset = AllocateVariable(to, true);
  4801. ctx->bc.InstrW_W(asBC_uTOd, offset, ctx->type.stackOffset);
  4802. ctx->type.SetVariable(to, offset, true);
  4803. }
  4804. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  4805. {
  4806. ConvertToTempVariable(ctx);
  4807. ctx->bc.InstrSHORT(asBC_u64TOd, ctx->type.stackOffset);
  4808. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4809. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4810. }
  4811. else if( ctx->type.dataType.IsFloatType() )
  4812. {
  4813. ConvertToTempVariable(ctx);
  4814. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  4815. int offset = AllocateVariable(to, true);
  4816. ctx->bc.InstrW_W(asBC_fTOd, offset, ctx->type.stackOffset);
  4817. ctx->type.SetVariable(to, offset, true);
  4818. }
  4819. }
  4820. }
  4821. else
  4822. {
  4823. if( ((to.IsIntegerType() && !to.IsEnumType()) || to.IsUnsignedType() ||
  4824. to.IsFloatType() || to.IsDoubleType() ||
  4825. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST)) &&
  4826. (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() ||
  4827. ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType()) )
  4828. {
  4829. ctx->type.dataType.SetTokenType(to.GetTokenType());
  4830. ctx->type.dataType.SetObjectType(to.GetObjectType());
  4831. }
  4832. }
  4833. // Primitive types on the stack, can be const or non-const
  4834. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4835. return cost;
  4836. }
  4837. asUINT asCCompiler::ImplicitConversion(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, bool allowObjectConstruct)
  4838. {
  4839. asASSERT( ctx->type.dataType.GetTokenType() != ttUnrecognizedToken ||
  4840. ctx->type.dataType.IsNullHandle() );
  4841. // No conversion from void to any other type
  4842. if( ctx->type.dataType.GetTokenType() == ttVoid )
  4843. return asCC_NO_CONV;
  4844. // Do we want a var type?
  4845. if( to.GetTokenType() == ttQuestion )
  4846. {
  4847. // Any type can be converted to a var type, but only when not generating code
  4848. asASSERT( !generateCode );
  4849. ctx->type.dataType = to;
  4850. return asCC_VARIABLE_CONV;
  4851. }
  4852. // Do we want a primitive?
  4853. else if( to.IsPrimitive() )
  4854. {
  4855. if( !ctx->type.dataType.IsPrimitive() )
  4856. return ImplicitConvObjectToPrimitive(ctx, to, node, convType, generateCode);
  4857. else
  4858. return ImplicitConvPrimitiveToPrimitive(ctx, to, node, convType, generateCode);
  4859. }
  4860. else // The target is a complex type
  4861. {
  4862. if( ctx->type.dataType.IsPrimitive() )
  4863. return ImplicitConvPrimitiveToObject(ctx, to, node, convType, generateCode, allowObjectConstruct);
  4864. else if( ctx->type.IsNullConstant() || ctx->type.dataType.GetObjectType() )
  4865. return ImplicitConvObjectToObject(ctx, to, node, convType, generateCode, allowObjectConstruct);
  4866. }
  4867. return asCC_NO_CONV;
  4868. }
  4869. asUINT asCCompiler::ImplicitConvObjectToPrimitive(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  4870. {
  4871. if( ctx->type.isExplicitHandle )
  4872. {
  4873. // An explicit handle cannot be converted to a primitive
  4874. if( convType != asIC_IMPLICIT_CONV && node )
  4875. {
  4876. asCString str;
  4877. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  4878. Error(str, node);
  4879. }
  4880. return asCC_NO_CONV;
  4881. }
  4882. // TODO: Must use the const cast behaviour if the object is read-only
  4883. // Find matching value cast behaviours
  4884. // Here we're only interested in those that convert the type to a primitive type
  4885. asCArray<int> funcs;
  4886. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  4887. if( beh == 0 )
  4888. {
  4889. if( convType != asIC_IMPLICIT_CONV && node )
  4890. {
  4891. asCString str;
  4892. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  4893. Error(str, node);
  4894. }
  4895. return asCC_NO_CONV;
  4896. }
  4897. if( convType == asIC_EXPLICIT_VAL_CAST )
  4898. {
  4899. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  4900. {
  4901. // accept both implicit and explicit cast
  4902. // TODO: 2.29.0: look for opConv or opImplConv methods
  4903. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  4904. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  4905. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  4906. funcs.PushLast(beh->operators[n+1]);
  4907. }
  4908. }
  4909. else
  4910. {
  4911. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  4912. {
  4913. // accept only implicit cast
  4914. // TODO: 2.29.0: look for opImplConv methods
  4915. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  4916. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  4917. funcs.PushLast(beh->operators[n+1]);
  4918. }
  4919. }
  4920. // This matrix describes the priorities of the types to search for, for each target type
  4921. // The first column is the target type, the priorities goes from left to right
  4922. eTokenType matchMtx[10][10] =
  4923. {
  4924. {ttDouble, ttFloat, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  4925. {ttFloat, ttDouble, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  4926. {ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  4927. {ttUInt64, ttInt64, ttUInt, ttInt, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  4928. {ttInt, ttUInt, ttInt64, ttUInt64, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  4929. {ttUInt, ttInt, ttUInt64, ttInt64, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  4930. {ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttInt8, ttUInt8, ttDouble, ttFloat},
  4931. {ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttUInt8, ttInt8, ttDouble, ttFloat},
  4932. {ttInt8, ttUInt8, ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttDouble, ttFloat},
  4933. {ttUInt8, ttInt8, ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttDouble, ttFloat},
  4934. };
  4935. // Which row to use?
  4936. eTokenType *row = 0;
  4937. for( unsigned int type = 0; type < 10; type++ )
  4938. {
  4939. if( to.GetTokenType() == matchMtx[type][0] )
  4940. {
  4941. row = &matchMtx[type][0];
  4942. break;
  4943. }
  4944. }
  4945. // Find the best matching cast operator
  4946. int funcId = 0;
  4947. if( row )
  4948. {
  4949. asCDataType target(to);
  4950. // Priority goes from left to right in the matrix
  4951. for( unsigned int attempt = 0; attempt < 10 && funcId == 0; attempt++ )
  4952. {
  4953. target.SetTokenType(row[attempt]);
  4954. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  4955. {
  4956. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[n]);
  4957. if( descr->returnType.IsEqualExceptRefAndConst(target) )
  4958. {
  4959. funcId = funcs[n];
  4960. break;
  4961. }
  4962. }
  4963. }
  4964. }
  4965. // Did we find a suitable function?
  4966. if( funcId != 0 )
  4967. {
  4968. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  4969. if( generateCode )
  4970. {
  4971. Dereference(ctx, true);
  4972. PerformFunctionCall(funcId, ctx);
  4973. }
  4974. else
  4975. ctx->type.Set(descr->returnType);
  4976. // Allow one more implicit conversion to another primitive type
  4977. return asCC_OBJ_TO_PRIMITIVE_CONV + ImplicitConversion(ctx, to, node, convType, generateCode, false);
  4978. }
  4979. // TODO: clean-up: This part is similar to what is in ImplicitConvObjectValue
  4980. // If no direct conversion is found we should look for the generic form 'void opConv(?&out)'
  4981. funcs.SetLength(0);
  4982. for( asUINT n = 0; n < beh->operators.GetLength(); n+= 2 )
  4983. {
  4984. if( ((convType == asIC_EXPLICIT_VAL_CAST) && asBEHAVE_VALUE_CAST == beh->operators[n]) ||
  4985. asBEHAVE_IMPLICIT_VALUE_CAST == beh->operators[n] )
  4986. {
  4987. int funcId = beh->operators[n+1];
  4988. // Does the operator take the ?&out parameter?
  4989. asCScriptFunction *func = engine->scriptFunctions[funcId];
  4990. if( func->parameterTypes.GetLength() != 1 ||
  4991. func->parameterTypes[0].GetTokenType() != ttQuestion ||
  4992. func->inOutFlags[0] != asTM_OUTREF )
  4993. continue;
  4994. funcs.PushLast(funcId);
  4995. }
  4996. }
  4997. // TODO: If there are multiple valid value casts, then we must choose the most appropriate one
  4998. asASSERT( funcs.GetLength() <= 1 );
  4999. if( funcs.GetLength() == 1 )
  5000. {
  5001. if( generateCode )
  5002. {
  5003. // Allocate a temporary variable of the requested type
  5004. int stackOffset = AllocateVariableNotIn(to, true, false, ctx);
  5005. CallDefaultConstructor(to, stackOffset, IsVariableOnHeap(stackOffset), &ctx->bc, node);
  5006. // Pass the reference of that variable to the function as output parameter
  5007. asCDataType toRef(to);
  5008. toRef.MakeReference(true);
  5009. toRef.MakeReadOnly(false);
  5010. asCArray<asSExprContext *> args;
  5011. asSExprContext arg(engine);
  5012. // Don't mark the variable as temporary, so it won't be freed too early
  5013. arg.type.SetVariable(toRef, stackOffset, false);
  5014. arg.type.isLValue = true;
  5015. arg.exprNode = node;
  5016. args.PushLast(&arg);
  5017. // Call the behaviour method
  5018. MakeFunctionCall(ctx, funcs[0], ctx->type.dataType.GetObjectType(), args, node);
  5019. // Use the reference to the variable as the result of the expression
  5020. // Now we can mark the variable as temporary
  5021. toRef.MakeReference(false);
  5022. ctx->type.SetVariable(toRef, stackOffset, true);
  5023. }
  5024. else
  5025. ctx->type.Set(to);
  5026. return asCC_OBJ_TO_PRIMITIVE_CONV;
  5027. }
  5028. if( convType != asIC_IMPLICIT_CONV && node )
  5029. {
  5030. asCString str;
  5031. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  5032. Error(str, node);
  5033. }
  5034. return asCC_NO_CONV;
  5035. }
  5036. asUINT asCCompiler::ImplicitConvObjectRef(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  5037. {
  5038. // Convert null to any object type handle, but not to a non-handle type
  5039. if( ctx->type.IsNullConstant() && ctx->methodName == "" )
  5040. {
  5041. if( to.IsObjectHandle() )
  5042. {
  5043. ctx->type.dataType = to;
  5044. return asCC_REF_CONV;
  5045. }
  5046. return asCC_NO_CONV;
  5047. }
  5048. asASSERT(ctx->type.dataType.GetObjectType() || ctx->methodName != "");
  5049. // First attempt to convert the base type without instanciating another instance
  5050. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() && ctx->methodName == "" )
  5051. {
  5052. // If the to type is an interface and the from type implements it, then we can convert it immediately
  5053. if( ctx->type.dataType.GetObjectType()->Implements(to.GetObjectType()) )
  5054. {
  5055. ctx->type.dataType.SetObjectType(to.GetObjectType());
  5056. return asCC_REF_CONV;
  5057. }
  5058. // If the to type is a class and the from type derives from it, then we can convert it immediately
  5059. else if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  5060. {
  5061. ctx->type.dataType.SetObjectType(to.GetObjectType());
  5062. return asCC_REF_CONV;
  5063. }
  5064. // If the types are not equal yet, then we may still be able to find a reference cast
  5065. else if( ctx->type.dataType.GetObjectType() != to.GetObjectType() )
  5066. {
  5067. // A ref cast must not remove the constness
  5068. bool isConst = ctx->type.dataType.IsObjectConst();
  5069. // We may still be able to find an implicit ref cast behaviour
  5070. CompileRefCast(ctx, to, convType == asIC_EXPLICIT_REF_CAST, node, generateCode);
  5071. ctx->type.dataType.MakeHandleToConst(isConst);
  5072. // Was the conversion done?
  5073. if( ctx->type.dataType.GetObjectType() == to.GetObjectType() )
  5074. return asCC_REF_CONV;
  5075. }
  5076. }
  5077. // Convert matching function types
  5078. if( to.GetFuncDef() )
  5079. {
  5080. // If the input expression is already a funcdef, check if it can be converted
  5081. if( ctx->type.dataType.GetFuncDef() &&
  5082. to.GetFuncDef() != ctx->type.dataType.GetFuncDef() )
  5083. {
  5084. asCScriptFunction *toFunc = to.GetFuncDef();
  5085. asCScriptFunction *fromFunc = ctx->type.dataType.GetFuncDef();
  5086. if( toFunc->IsSignatureExceptNameEqual(fromFunc) )
  5087. {
  5088. ctx->type.dataType.SetFuncDef(toFunc);
  5089. return asCC_REF_CONV;
  5090. }
  5091. }
  5092. // If the input expression is a deferred function ref, check if there is a matching func
  5093. if( ctx->methodName != "" )
  5094. {
  5095. // Determine the namespace
  5096. asSNameSpace *ns = 0;
  5097. asCString name = "";
  5098. int pos = ctx->methodName.FindLast("::");
  5099. if( pos >= 0 )
  5100. {
  5101. asCString nsName = ctx->methodName.SubString(0, pos+2);
  5102. // Trim off the last ::
  5103. if( nsName.GetLength() > 2 )
  5104. nsName.SetLength(nsName.GetLength()-2);
  5105. ns = DetermineNameSpace(nsName);
  5106. name = ctx->methodName.SubString(pos+2);
  5107. }
  5108. else
  5109. {
  5110. DetermineNameSpace("");
  5111. name = ctx->methodName;
  5112. }
  5113. asCArray<int> funcs;
  5114. if( ns )
  5115. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  5116. // Check if any of the functions have perfect match
  5117. for( asUINT n = 0; n < funcs.GetLength(); n++ )
  5118. {
  5119. asCScriptFunction *func = builder->GetFunctionDescription(funcs[n]);
  5120. if( to.GetFuncDef()->IsSignatureExceptNameEqual(func) )
  5121. {
  5122. if( generateCode )
  5123. {
  5124. ctx->bc.InstrPTR(asBC_FuncPtr, func);
  5125. // Make sure the identified function is shared if we're compiling a shared function
  5126. if( !func->IsShared() && outFunc->IsShared() )
  5127. {
  5128. asCString msg;
  5129. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, func->GetDeclaration());
  5130. Error(msg, node);
  5131. }
  5132. }
  5133. ctx->type.dataType = asCDataType::CreateFuncDef(to.GetFuncDef());
  5134. return asCC_REF_CONV;
  5135. }
  5136. }
  5137. }
  5138. }
  5139. return asCC_NO_CONV;
  5140. }
  5141. asUINT asCCompiler::ImplicitConvObjectValue(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  5142. {
  5143. asUINT cost = asCC_NO_CONV;
  5144. // If the base type is still different, and we are allowed to instance
  5145. // another object then we can try an implicit value cast
  5146. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  5147. {
  5148. // TODO: Implement support for implicit constructor/factory
  5149. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  5150. if( beh == 0 )
  5151. return cost;
  5152. asCArray<int> funcs;
  5153. if( convType == asIC_EXPLICIT_VAL_CAST )
  5154. {
  5155. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  5156. {
  5157. // accept both implicit and explicit cast
  5158. // TODO: 2.29.0: Look for opConv and opImplConv methods instead
  5159. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  5160. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  5161. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  5162. funcs.PushLast(beh->operators[n+1]);
  5163. }
  5164. }
  5165. else
  5166. {
  5167. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  5168. {
  5169. // accept only implicit cast
  5170. // TODO: 2.29.0: Look for opImplConv methods instead
  5171. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  5172. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  5173. funcs.PushLast(beh->operators[n+1]);
  5174. }
  5175. }
  5176. // TODO: If there are multiple valid value casts, then we must choose the most appropriate one
  5177. asASSERT( funcs.GetLength() <= 1 );
  5178. if( funcs.GetLength() == 1 )
  5179. {
  5180. asCScriptFunction *f = builder->GetFunctionDescription(funcs[0]);
  5181. if( generateCode )
  5182. {
  5183. Dereference(ctx, true);
  5184. bool useVariable = false;
  5185. int stackOffset = 0;
  5186. if( f->DoesReturnOnStack() )
  5187. {
  5188. useVariable = true;
  5189. stackOffset = AllocateVariable(f->returnType, true);
  5190. // Push the pointer to the pre-allocated space for the return value
  5191. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  5192. // The object pointer is already on the stack, but should be the top
  5193. // one, so we need to swap the pointers in order to get the correct
  5194. ctx->bc.Instr(asBC_SwapPtr);
  5195. }
  5196. PerformFunctionCall(funcs[0], ctx, false, 0, 0, useVariable, stackOffset);
  5197. }
  5198. else
  5199. ctx->type.Set(f->returnType);
  5200. cost = asCC_TO_OBJECT_CONV;
  5201. }
  5202. else
  5203. {
  5204. // TODO: cleanup: This part is similar to the second half of ImplicitConvObjectToPrimitive
  5205. // Look for a value cast with variable type
  5206. for( asUINT n = 0; n < beh->operators.GetLength(); n+= 2 )
  5207. {
  5208. if( ((convType == asIC_EXPLICIT_VAL_CAST) && asBEHAVE_VALUE_CAST == beh->operators[n]) ||
  5209. asBEHAVE_IMPLICIT_VALUE_CAST == beh->operators[n] )
  5210. {
  5211. int funcId = beh->operators[n+1];
  5212. // Does the operator take the ?&out parameter?
  5213. asCScriptFunction *func = engine->scriptFunctions[funcId];
  5214. if( func->parameterTypes.GetLength() != 1 ||
  5215. func->parameterTypes[0].GetTokenType() != ttQuestion ||
  5216. func->inOutFlags[0] != asTM_OUTREF )
  5217. continue;
  5218. funcs.PushLast(funcId);
  5219. }
  5220. }
  5221. // TODO: If there are multiple valid value casts, then we must choose the most appropriate one
  5222. asASSERT( funcs.GetLength() <= 1 );
  5223. if( funcs.GetLength() == 1 )
  5224. {
  5225. cost = asCC_TO_OBJECT_CONV;
  5226. if( generateCode )
  5227. {
  5228. // Allocate a temporary variable of the requested type
  5229. int stackOffset = AllocateVariableNotIn(to, true, false, ctx);
  5230. CallDefaultConstructor(to, stackOffset, IsVariableOnHeap(stackOffset), &ctx->bc, node);
  5231. // Pass the reference of that variable to the function as output parameter
  5232. asCDataType toRef(to);
  5233. toRef.MakeReference(false);
  5234. asCArray<asSExprContext *> args;
  5235. asSExprContext arg(engine);
  5236. arg.bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  5237. // Don't mark the variable as temporary, so it won't be freed too early
  5238. arg.type.SetVariable(toRef, stackOffset, false);
  5239. arg.type.isLValue = true;
  5240. arg.exprNode = node;
  5241. args.PushLast(&arg);
  5242. // Call the behaviour method
  5243. MakeFunctionCall(ctx, funcs[0], ctx->type.dataType.GetObjectType(), args, node);
  5244. // Use the reference to the variable as the result of the expression
  5245. // Now we can mark the variable as temporary
  5246. ctx->type.SetVariable(toRef, stackOffset, true);
  5247. ctx->bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  5248. }
  5249. else
  5250. {
  5251. // All casts are legal
  5252. ctx->type.Set(to);
  5253. }
  5254. }
  5255. }
  5256. }
  5257. return cost;
  5258. }
  5259. asUINT asCCompiler::ImplicitConvObjectToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, bool allowObjectConstruct)
  5260. {
  5261. // First try a ref cast
  5262. asUINT cost = ImplicitConvObjectRef(ctx, to, node, convType, generateCode);
  5263. // If the desired type is an asOBJ_ASHANDLE then we'll assume it is allowed to implicitly
  5264. // construct the object through any of the available constructors
  5265. if( to.GetObjectType() && (to.GetObjectType()->flags & asOBJ_ASHANDLE) && to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  5266. {
  5267. asCArray<int> funcs;
  5268. funcs = to.GetObjectType()->beh.constructors;
  5269. asCArray<asSExprContext *> args;
  5270. args.PushLast(ctx);
  5271. cost = asCC_TO_OBJECT_CONV + MatchFunctions(funcs, args, node, 0, 0, 0, false, true, false);
  5272. // Did we find a matching constructor?
  5273. if( funcs.GetLength() == 1 )
  5274. {
  5275. if( generateCode )
  5276. {
  5277. // If the ASHANDLE receives a variable type parameter, then we need to
  5278. // make sure the expression is treated as a handle and not as a value
  5279. asCScriptFunction *func = engine->scriptFunctions[funcs[0]];
  5280. if( func->parameterTypes[0].GetTokenType() == ttQuestion )
  5281. {
  5282. if( !ctx->type.isExplicitHandle )
  5283. {
  5284. asCDataType toHandle = ctx->type.dataType;
  5285. toHandle.MakeHandle(true);
  5286. toHandle.MakeReference(true);
  5287. toHandle.MakeHandleToConst(ctx->type.dataType.IsReadOnly());
  5288. ImplicitConversion(ctx, toHandle, node, asIC_IMPLICIT_CONV, true, false);
  5289. asASSERT( ctx->type.dataType.IsObjectHandle() );
  5290. }
  5291. ctx->type.isExplicitHandle = true;
  5292. }
  5293. // TODO: This should really reuse the code from CompileConstructCall
  5294. // Allocate the new object
  5295. asCTypeInfo tempObj;
  5296. tempObj.dataType = to;
  5297. tempObj.dataType.MakeReference(false);
  5298. tempObj.stackOffset = (short)AllocateVariable(tempObj.dataType, true);
  5299. tempObj.dataType.MakeReference(true);
  5300. tempObj.isTemporary = true;
  5301. tempObj.isVariable = true;
  5302. bool onHeap = IsVariableOnHeap(tempObj.stackOffset);
  5303. // Push the address of the object on the stack
  5304. asSExprContext e(engine);
  5305. if( onHeap )
  5306. e.bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  5307. PrepareFunctionCall(funcs[0], &e.bc, args);
  5308. MoveArgsToStack(funcs[0], &e.bc, args, false);
  5309. // If the object is allocated on the stack, then call the constructor as a normal function
  5310. if( onHeap )
  5311. {
  5312. int offset = 0;
  5313. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  5314. offset = descr->parameterTypes[0].GetSizeOnStackDWords();
  5315. e.bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  5316. }
  5317. else
  5318. e.bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  5319. PerformFunctionCall(funcs[0], &e, onHeap, &args, tempObj.dataType.GetObjectType());
  5320. // Add tag that the object has been initialized
  5321. e.bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  5322. // The constructor doesn't return anything,
  5323. // so we have to manually inform the type of
  5324. // the return value
  5325. e.type = tempObj;
  5326. if( !onHeap )
  5327. e.type.dataType.MakeReference(false);
  5328. // Push the address of the object on the stack again
  5329. e.bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  5330. MergeExprBytecodeAndType(ctx, &e);
  5331. }
  5332. else
  5333. {
  5334. ctx->type.Set(asCDataType::CreateObject(to.GetObjectType(), false));
  5335. }
  5336. }
  5337. }
  5338. // If the base type is still different, and we are allowed to instance
  5339. // another object then we can try an implicit value cast
  5340. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  5341. {
  5342. // Attempt implicit value cast
  5343. cost = ImplicitConvObjectValue(ctx, to, node, convType, generateCode);
  5344. }
  5345. // If we still haven't converted the base type to the correct type, then there is
  5346. // no need to continue as it is not possible to do the conversion
  5347. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  5348. return asCC_NO_CONV;
  5349. if( to.IsObjectHandle() )
  5350. {
  5351. // There is no extra cost in converting to a handle
  5352. // reference to handle -> handle
  5353. // reference -> handle
  5354. // object -> handle
  5355. // handle -> reference to handle
  5356. // reference -> reference to handle
  5357. // object -> reference to handle
  5358. // TODO: If the type is handle, then we can't use IsReadOnly to determine the constness of the basetype
  5359. // If the rvalue is a handle to a const object, then
  5360. // the lvalue must also be a handle to a const object
  5361. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() )
  5362. {
  5363. if( convType != asIC_IMPLICIT_CONV )
  5364. {
  5365. asASSERT(node);
  5366. asCString str;
  5367. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  5368. Error(str, node);
  5369. }
  5370. }
  5371. if( !ctx->type.dataType.IsObjectHandle() )
  5372. {
  5373. // An object type can be directly converted to a handle of the
  5374. // same type by doing a ref copy to a new variable
  5375. if( ctx->type.dataType.SupportHandles() )
  5376. {
  5377. asCDataType dt = ctx->type.dataType;
  5378. dt.MakeHandle(true);
  5379. dt.MakeReference(false);
  5380. if( generateCode )
  5381. {
  5382. // If the expression is already a local variable, then it is not
  5383. // necessary to do a ref copy, as the ref objects on the stack are
  5384. // really handles, only the handles cannot be modified.
  5385. if( ctx->type.isVariable )
  5386. {
  5387. bool isHandleToConst = ctx->type.dataType.IsReadOnly();
  5388. ctx->type.dataType.MakeReadOnly(false);
  5389. ctx->type.dataType.MakeHandle(true);
  5390. ctx->type.dataType.MakeReadOnly(true);
  5391. ctx->type.dataType.MakeHandleToConst(isHandleToConst);
  5392. if( to.IsReference() && !ctx->type.dataType.IsReference() )
  5393. {
  5394. ctx->bc.Instr(asBC_PopPtr);
  5395. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  5396. ctx->type.dataType.MakeReference(true);
  5397. }
  5398. else if( ctx->type.dataType.IsReference() )
  5399. {
  5400. ctx->bc.Instr(asBC_RDSPtr);
  5401. ctx->type.dataType.MakeReference(false);
  5402. }
  5403. }
  5404. else
  5405. {
  5406. int offset = AllocateVariable(dt, true);
  5407. if( ctx->type.dataType.IsReference() )
  5408. ctx->bc.Instr(asBC_RDSPtr);
  5409. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5410. ctx->bc.InstrPTR(asBC_REFCPY, dt.GetObjectType());
  5411. ctx->bc.Instr(asBC_PopPtr);
  5412. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5413. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  5414. if( to.IsReference() )
  5415. dt.MakeReference(true);
  5416. else
  5417. ctx->bc.Instr(asBC_RDSPtr);
  5418. ctx->type.SetVariable(dt, offset, true);
  5419. }
  5420. }
  5421. else
  5422. ctx->type.dataType = dt;
  5423. // When this conversion is done the expression is no longer an lvalue
  5424. ctx->type.isLValue = false;
  5425. }
  5426. }
  5427. if( ctx->type.dataType.IsObjectHandle() )
  5428. {
  5429. // A handle to non-const can be converted to a
  5430. // handle to const, but not the other way
  5431. if( to.IsHandleToConst() )
  5432. ctx->type.dataType.MakeHandleToConst(true);
  5433. // A const handle can be converted to a non-const
  5434. // handle and vice versa as the handle is just a value
  5435. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  5436. }
  5437. if( to.IsReference() && !ctx->type.dataType.IsReference() )
  5438. {
  5439. if( generateCode )
  5440. {
  5441. asASSERT( ctx->type.dataType.IsObjectHandle() );
  5442. // If the input type is a handle, then a simple ref copy is enough
  5443. bool isExplicitHandle = ctx->type.isExplicitHandle;
  5444. ctx->type.isExplicitHandle = ctx->type.dataType.IsObjectHandle();
  5445. // If the input type is read-only we'll need to temporarily
  5446. // remove this constness, otherwise the assignment will fail
  5447. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  5448. ctx->type.dataType.MakeReadOnly(false);
  5449. // If the object already is a temporary variable, then the copy
  5450. // doesn't have to be made as it is already a unique object
  5451. PrepareTemporaryObject(node, ctx);
  5452. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  5453. ctx->type.isExplicitHandle = isExplicitHandle;
  5454. }
  5455. // A non-reference can be converted to a reference,
  5456. // by putting the value in a temporary variable
  5457. ctx->type.dataType.MakeReference(true);
  5458. // Since it is a new temporary variable it doesn't have to be const
  5459. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  5460. }
  5461. else if( !to.IsReference() && ctx->type.dataType.IsReference() )
  5462. {
  5463. Dereference(ctx, generateCode);
  5464. }
  5465. }
  5466. else // if( !to.IsObjectHandle() )
  5467. {
  5468. if( !to.IsReference() )
  5469. {
  5470. // reference to handle -> object
  5471. // handle -> object
  5472. // reference -> object
  5473. // An implicit handle can be converted to an object by adding a check for null pointer
  5474. if( ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  5475. {
  5476. if( generateCode )
  5477. {
  5478. if( ctx->type.dataType.IsReference() )
  5479. {
  5480. // The pointer on the stack refers to the handle
  5481. ctx->bc.Instr(asBC_ChkRefS);
  5482. }
  5483. else
  5484. {
  5485. // The pointer on the stack refers to the object
  5486. ctx->bc.Instr(asBC_CHKREF);
  5487. }
  5488. }
  5489. ctx->type.dataType.MakeHandle(false);
  5490. }
  5491. // A const object can be converted to a non-const object through a copy
  5492. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() &&
  5493. allowObjectConstruct )
  5494. {
  5495. // Does the object type allow a copy to be made?
  5496. if( ctx->type.dataType.CanBeCopied() )
  5497. {
  5498. if( generateCode )
  5499. {
  5500. // Make a temporary object with the copy
  5501. PrepareTemporaryObject(node, ctx);
  5502. }
  5503. // In case the object was already in a temporary variable, then the function
  5504. // didn't really do anything so we need to remove the constness here
  5505. ctx->type.dataType.MakeReadOnly(false);
  5506. // Add the cost for the copy
  5507. cost += asCC_TO_OBJECT_CONV;
  5508. }
  5509. }
  5510. if( ctx->type.dataType.IsReference() )
  5511. {
  5512. // This may look strange, but a value type allocated on the stack is already
  5513. // correct, so nothing should be done other than remove the mark as reference.
  5514. // For types allocated on the heap, it is necessary to dereference the pointer
  5515. // that is currently on the stack
  5516. if( IsVariableOnHeap(ctx->type.stackOffset) )
  5517. Dereference(ctx, generateCode);
  5518. else
  5519. ctx->type.dataType.MakeReference(false);
  5520. }
  5521. // A non-const object can be converted to a const object directly
  5522. if( !ctx->type.dataType.IsReadOnly() && to.IsReadOnly() )
  5523. {
  5524. ctx->type.dataType.MakeReadOnly(true);
  5525. }
  5526. }
  5527. else // if( to.IsReference() )
  5528. {
  5529. // reference to handle -> reference
  5530. // handle -> reference
  5531. // object -> reference
  5532. if( ctx->type.dataType.IsReference() )
  5533. {
  5534. if( ctx->type.isExplicitHandle && ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  5535. {
  5536. // ASHANDLE objects are really value types, so explicit handle can be removed
  5537. ctx->type.isExplicitHandle = false;
  5538. ctx->type.dataType.MakeHandle(false);
  5539. }
  5540. // A reference to a handle can be converted to a reference to an object
  5541. // by first reading the address, then verifying that it is not null
  5542. if( !to.IsObjectHandle() && ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  5543. {
  5544. ctx->type.dataType.MakeHandle(false);
  5545. if( generateCode )
  5546. ctx->bc.Instr(asBC_ChkRefS);
  5547. }
  5548. // A reference to a non-const can be converted to a reference to a const
  5549. if( to.IsReadOnly() )
  5550. ctx->type.dataType.MakeReadOnly(true);
  5551. else if( ctx->type.dataType.IsReadOnly() )
  5552. {
  5553. // A reference to a const can be converted to a reference to a
  5554. // non-const by copying the object to a temporary variable
  5555. ctx->type.dataType.MakeReadOnly(false);
  5556. if( generateCode )
  5557. {
  5558. // If the object already is a temporary variable, then the copy
  5559. // doesn't have to be made as it is already a unique object
  5560. PrepareTemporaryObject(node, ctx);
  5561. }
  5562. // Add the cost for the copy
  5563. cost += asCC_TO_OBJECT_CONV;
  5564. }
  5565. }
  5566. else // if( !ctx->type.dataType.IsReference() )
  5567. {
  5568. // A non-reference handle can be converted to a non-handle reference by checking against null handle
  5569. if( ctx->type.dataType.IsObjectHandle() )
  5570. {
  5571. bool readOnly = false;
  5572. if( ctx->type.dataType.IsHandleToConst() )
  5573. readOnly = true;
  5574. if( generateCode )
  5575. {
  5576. if( ctx->type.isVariable )
  5577. ctx->bc.InstrSHORT(asBC_ChkNullV, ctx->type.stackOffset);
  5578. else
  5579. ctx->bc.Instr(asBC_CHKREF);
  5580. }
  5581. ctx->type.dataType.MakeHandle(false);
  5582. ctx->type.dataType.MakeReference(true);
  5583. // Make sure a handle to const isn't converted to non-const reference
  5584. if( readOnly )
  5585. ctx->type.dataType.MakeReadOnly(true);
  5586. }
  5587. else
  5588. {
  5589. // A value type allocated on the stack is differentiated
  5590. // by it not being a reference. But it can be handled as
  5591. // reference by pushing the pointer on the stack
  5592. if( (ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) &&
  5593. (ctx->type.isVariable || ctx->type.isTemporary) &&
  5594. !IsVariableOnHeap(ctx->type.stackOffset) )
  5595. {
  5596. // Actually the pointer is already pushed on the stack in
  5597. // CompileVariableAccess, so we don't need to do anything else
  5598. }
  5599. else if( generateCode )
  5600. {
  5601. // A non-reference can be converted to a reference,
  5602. // by putting the value in a temporary variable
  5603. // If the input type is read-only we'll need to temporarily
  5604. // remove this constness, otherwise the assignment will fail
  5605. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  5606. ctx->type.dataType.MakeReadOnly(false);
  5607. // If the object already is a temporary variable, then the copy
  5608. // doesn't have to be made as it is already a unique object
  5609. PrepareTemporaryObject(node, ctx);
  5610. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  5611. // Add the cost for the copy
  5612. cost += asCC_TO_OBJECT_CONV;
  5613. }
  5614. // This may look strange as the conversion was to make the expression a reference
  5615. // but a value type allocated on the stack is a reference even without the type
  5616. // being marked as such.
  5617. ctx->type.dataType.MakeReference(IsVariableOnHeap(ctx->type.stackOffset));
  5618. }
  5619. // TODO: If the variable is an object allocated on the stack the following is not true as the copy may not have been made
  5620. // Since it is a new temporary variable it doesn't have to be const
  5621. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  5622. }
  5623. }
  5624. }
  5625. return cost;
  5626. }
  5627. asUINT asCCompiler::ImplicitConvPrimitiveToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode * /*node*/, EImplicitConv /*isExplicit*/, bool generateCode, bool /*allowObjectConstruct*/)
  5628. {
  5629. // Reference types currently don't allow implicit conversion from primitive to object
  5630. // TODO: Allow implicit conversion to scoped reference types as they are supposed to appear like ordinary value types
  5631. asCObjectType *objType = to.GetObjectType();
  5632. asASSERT( objType );
  5633. if( !objType || (objType->flags & asOBJ_REF) )
  5634. return asCC_NO_CONV;
  5635. // For value types the object must have a constructor that takes a single primitive argument either by value or as input reference
  5636. asCArray<int> funcs;
  5637. for( asUINT n = 0; n < objType->beh.constructors.GetLength(); n++ )
  5638. {
  5639. asCScriptFunction *func = engine->scriptFunctions[objType->beh.constructors[n]];
  5640. if( func->parameterTypes.GetLength() == 1 &&
  5641. func->parameterTypes[0].IsPrimitive() &&
  5642. !(func->inOutFlags[0] & asTM_OUTREF) )
  5643. {
  5644. funcs.PushLast(func->id);
  5645. }
  5646. }
  5647. if( funcs.GetLength() == 0 )
  5648. return asCC_NO_CONV;
  5649. // Check if it is possible to choose a best match
  5650. asSExprContext arg(engine);
  5651. arg.type = ctx->type;
  5652. arg.exprNode = ctx->exprNode; // Use the same node for compiler messages
  5653. asCArray<asSExprContext*> args;
  5654. args.PushLast(&arg);
  5655. asUINT cost = asCC_TO_OBJECT_CONV + MatchFunctions(funcs, args, 0, 0, 0, objType, false, true, false);
  5656. if( funcs.GetLength() != 1 )
  5657. return asCC_NO_CONV;
  5658. if( !generateCode )
  5659. {
  5660. ctx->type.Set(to);
  5661. return cost;
  5662. }
  5663. // TODO: clean up: This part is similar to CompileConstructCall(). It should be put in a common function
  5664. // Clear the type of ctx, as the type is moved to the arg
  5665. ctx->type.SetDummy();
  5666. // Value types and script types are allocated through the constructor
  5667. asCTypeInfo tempObj;
  5668. tempObj.dataType = to;
  5669. tempObj.stackOffset = (short)AllocateVariable(to, true);
  5670. tempObj.dataType.MakeReference(true);
  5671. tempObj.isTemporary = true;
  5672. tempObj.isVariable = true;
  5673. bool onHeap = IsVariableOnHeap(tempObj.stackOffset);
  5674. // Push the address of the object on the stack
  5675. if( onHeap )
  5676. ctx->bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  5677. PrepareFunctionCall(funcs[0], &ctx->bc, args);
  5678. MoveArgsToStack(funcs[0], &ctx->bc, args, false);
  5679. if( !(objType->flags & asOBJ_REF) )
  5680. {
  5681. // If the object is allocated on the stack, then call the constructor as a normal function
  5682. if( onHeap )
  5683. {
  5684. int offset = 0;
  5685. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  5686. for( asUINT n = 0; n < args.GetLength(); n++ )
  5687. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  5688. ctx->bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  5689. }
  5690. else
  5691. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  5692. PerformFunctionCall(funcs[0], ctx, onHeap, &args, tempObj.dataType.GetObjectType());
  5693. // Add tag that the object has been initialized
  5694. ctx->bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  5695. // The constructor doesn't return anything,
  5696. // so we have to manually inform the type of
  5697. // the return value
  5698. ctx->type = tempObj;
  5699. if( !onHeap )
  5700. ctx->type.dataType.MakeReference(false);
  5701. // Push the address of the object on the stack again
  5702. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  5703. }
  5704. else
  5705. {
  5706. asASSERT( objType->flags & asOBJ_SCOPED );
  5707. // Call the factory to create the reference type
  5708. PerformFunctionCall(funcs[0], ctx, false, &args);
  5709. }
  5710. return cost;
  5711. }
  5712. void asCCompiler::ImplicitConversionConstant(asSExprContext *from, const asCDataType &to, asCScriptNode *node, EImplicitConv convType)
  5713. {
  5714. asASSERT(from->type.isConstant);
  5715. // TODO: node should be the node of the value that is
  5716. // converted (not the operator that provokes the implicit
  5717. // conversion)
  5718. // If the base type is correct there is no more to do
  5719. if( to.IsEqualExceptRefAndConst(from->type.dataType) ) return;
  5720. // References cannot be constants
  5721. if( from->type.dataType.IsReference() ) return;
  5722. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1 && !to.IsEnumType()) ||
  5723. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  5724. {
  5725. if( from->type.dataType.IsFloatType() ||
  5726. from->type.dataType.IsDoubleType() ||
  5727. from->type.dataType.IsUnsignedType() ||
  5728. from->type.dataType.IsIntegerType() )
  5729. {
  5730. // Transform the value
  5731. // Float constants can be implicitly converted to int
  5732. if( from->type.dataType.IsFloatType() )
  5733. {
  5734. float fc = from->type.floatValue;
  5735. int ic = int(fc);
  5736. if( float(ic) != fc )
  5737. {
  5738. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5739. }
  5740. from->type.intValue = ic;
  5741. }
  5742. // Double constants can be implicitly converted to int
  5743. else if( from->type.dataType.IsDoubleType() )
  5744. {
  5745. double fc = from->type.doubleValue;
  5746. int ic = int(fc);
  5747. if( double(ic) != fc )
  5748. {
  5749. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5750. }
  5751. from->type.intValue = ic;
  5752. }
  5753. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  5754. {
  5755. // Verify that it is possible to convert to signed without getting negative
  5756. if( from->type.intValue < 0 )
  5757. {
  5758. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  5759. }
  5760. // Convert to 32bit
  5761. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5762. from->type.intValue = from->type.byteValue;
  5763. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5764. from->type.intValue = from->type.wordValue;
  5765. }
  5766. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  5767. {
  5768. // Convert to 32bit
  5769. from->type.intValue = int(from->type.qwordValue);
  5770. }
  5771. else if( from->type.dataType.IsIntegerType() &&
  5772. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  5773. {
  5774. // Convert to 32bit
  5775. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5776. from->type.intValue = (signed char)from->type.byteValue;
  5777. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5778. from->type.intValue = (short)from->type.wordValue;
  5779. }
  5780. // Set the resulting type
  5781. if( to.IsEnumType() )
  5782. from->type.dataType = to;
  5783. else
  5784. from->type.dataType = asCDataType::CreatePrimitive(ttInt, true);
  5785. }
  5786. // Check if a downsize is necessary
  5787. if( to.IsIntegerType() &&
  5788. from->type.dataType.IsIntegerType() &&
  5789. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  5790. {
  5791. // Verify if it is possible
  5792. if( to.GetSizeInMemoryBytes() == 1 )
  5793. {
  5794. if( char(from->type.intValue) != from->type.intValue )
  5795. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  5796. from->type.byteValue = char(from->type.intValue);
  5797. }
  5798. else if( to.GetSizeInMemoryBytes() == 2 )
  5799. {
  5800. if( short(from->type.intValue) != from->type.intValue )
  5801. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  5802. from->type.wordValue = short(from->type.intValue);
  5803. }
  5804. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5805. }
  5806. }
  5807. else if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  5808. {
  5809. // Float constants can be implicitly converted to int
  5810. if( from->type.dataType.IsFloatType() )
  5811. {
  5812. float fc = from->type.floatValue;
  5813. asINT64 ic = asINT64(fc);
  5814. if( float(ic) != fc )
  5815. {
  5816. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5817. }
  5818. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  5819. from->type.qwordValue = ic;
  5820. }
  5821. // Double constants can be implicitly converted to int
  5822. else if( from->type.dataType.IsDoubleType() )
  5823. {
  5824. double fc = from->type.doubleValue;
  5825. asINT64 ic = asINT64(fc);
  5826. if( double(ic) != fc )
  5827. {
  5828. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5829. }
  5830. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  5831. from->type.qwordValue = ic;
  5832. }
  5833. else if( from->type.dataType.IsUnsignedType() )
  5834. {
  5835. // Convert to 64bit
  5836. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5837. from->type.qwordValue = from->type.byteValue;
  5838. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5839. from->type.qwordValue = from->type.wordValue;
  5840. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  5841. from->type.qwordValue = from->type.dwordValue;
  5842. else if( from->type.dataType.GetSizeInMemoryBytes() == 8 )
  5843. {
  5844. if( asINT64(from->type.qwordValue) < 0 )
  5845. {
  5846. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  5847. }
  5848. }
  5849. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  5850. }
  5851. else if( from->type.dataType.IsIntegerType() )
  5852. {
  5853. // Convert to 64bit
  5854. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5855. from->type.qwordValue = (signed char)from->type.byteValue;
  5856. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5857. from->type.qwordValue = (short)from->type.wordValue;
  5858. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  5859. from->type.qwordValue = from->type.intValue;
  5860. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  5861. }
  5862. }
  5863. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  5864. {
  5865. if( from->type.dataType.IsFloatType() )
  5866. {
  5867. float fc = from->type.floatValue;
  5868. // Some compilers set the value to 0 when converting a negative float to unsigned int.
  5869. // To maintain a consistent behaviour across compilers we convert to int first.
  5870. asUINT uic = asUINT(int(fc));
  5871. if( float(uic) != fc )
  5872. {
  5873. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5874. }
  5875. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  5876. from->type.intValue = uic;
  5877. // Try once more, in case of a smaller type
  5878. ImplicitConversionConstant(from, to, node, convType);
  5879. }
  5880. else if( from->type.dataType.IsDoubleType() )
  5881. {
  5882. double fc = from->type.doubleValue;
  5883. // Some compilers set the value to 0 when converting a negative double to unsigned int.
  5884. // To maintain a consistent behaviour across compilers we convert to int first.
  5885. asUINT uic = asUINT(int(fc));
  5886. if( double(uic) != fc )
  5887. {
  5888. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5889. }
  5890. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  5891. from->type.intValue = uic;
  5892. // Try once more, in case of a smaller type
  5893. ImplicitConversionConstant(from, to, node, convType);
  5894. }
  5895. else if( from->type.dataType.IsIntegerType() )
  5896. {
  5897. // Verify that it is possible to convert to unsigned without loosing negative
  5898. if( (from->type.dataType.GetSizeInMemoryBytes() > 4 && asINT64(from->type.qwordValue) < 0) ||
  5899. (from->type.dataType.GetSizeInMemoryBytes() <= 4 && from->type.intValue < 0) )
  5900. {
  5901. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  5902. }
  5903. // Check if any data is lost
  5904. if( from->type.dataType.GetSizeInMemoryBytes() > 4 && (from->type.qwordValue >> 32) != 0 && (from->type.qwordValue >> 32) != 0xFFFFFFFF )
  5905. {
  5906. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  5907. }
  5908. // Convert to 32bit
  5909. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5910. from->type.intValue = (signed char)from->type.byteValue;
  5911. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5912. from->type.intValue = (short)from->type.wordValue;
  5913. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  5914. // Try once more, in case of a smaller type
  5915. ImplicitConversionConstant(from, to, node, convType);
  5916. }
  5917. else if( from->type.dataType.IsUnsignedType() &&
  5918. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  5919. {
  5920. // Convert to 32bit
  5921. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5922. from->type.dwordValue = from->type.byteValue;
  5923. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5924. from->type.dwordValue = from->type.wordValue;
  5925. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  5926. // Try once more, in case of a smaller type
  5927. ImplicitConversionConstant(from, to, node, convType);
  5928. }
  5929. else if( from->type.dataType.IsUnsignedType() &&
  5930. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  5931. {
  5932. // Verify if it is possible
  5933. if( to.GetSizeInMemoryBytes() == 1 )
  5934. {
  5935. if( asBYTE(from->type.dwordValue) != from->type.dwordValue )
  5936. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  5937. from->type.byteValue = asBYTE(from->type.dwordValue);
  5938. }
  5939. else if( to.GetSizeInMemoryBytes() == 2 )
  5940. {
  5941. if( asWORD(from->type.dwordValue) != from->type.dwordValue )
  5942. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  5943. from->type.wordValue = asWORD(from->type.dwordValue);
  5944. }
  5945. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  5946. }
  5947. }
  5948. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  5949. {
  5950. if( from->type.dataType.IsFloatType() )
  5951. {
  5952. float fc = from->type.floatValue;
  5953. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  5954. asQWORD uic = asQWORD(asINT64(fc));
  5955. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  5956. // MSVC6 doesn't support this conversion
  5957. if( float(uic) != fc )
  5958. {
  5959. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5960. }
  5961. #endif
  5962. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  5963. from->type.qwordValue = uic;
  5964. }
  5965. else if( from->type.dataType.IsDoubleType() )
  5966. {
  5967. double fc = from->type.doubleValue;
  5968. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  5969. asQWORD uic = asQWORD(asINT64(fc));
  5970. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  5971. // MSVC6 doesn't support this conversion
  5972. if( double(uic) != fc )
  5973. {
  5974. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  5975. }
  5976. #endif
  5977. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  5978. from->type.qwordValue = uic;
  5979. }
  5980. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  5981. {
  5982. // Convert to 64bit
  5983. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  5984. from->type.qwordValue = (asINT64)(signed char)from->type.byteValue;
  5985. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  5986. from->type.qwordValue = (asINT64)(short)from->type.wordValue;
  5987. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  5988. from->type.qwordValue = (asINT64)from->type.intValue;
  5989. // Verify that it is possible to convert to unsigned without loosing negative
  5990. if( asINT64(from->type.qwordValue) < 0 )
  5991. {
  5992. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  5993. }
  5994. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  5995. }
  5996. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  5997. {
  5998. // Verify that it is possible to convert to unsigned without loosing negative
  5999. if( asINT64(from->type.qwordValue) < 0 )
  6000. {
  6001. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  6002. }
  6003. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  6004. }
  6005. else if( from->type.dataType.IsUnsignedType() )
  6006. {
  6007. // Convert to 64bit
  6008. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  6009. from->type.qwordValue = from->type.byteValue;
  6010. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  6011. from->type.qwordValue = from->type.wordValue;
  6012. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  6013. from->type.qwordValue = from->type.dwordValue;
  6014. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  6015. }
  6016. }
  6017. else if( to.IsFloatType() )
  6018. {
  6019. if( from->type.dataType.IsDoubleType() )
  6020. {
  6021. double ic = from->type.doubleValue;
  6022. float fc = float(ic);
  6023. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6024. from->type.floatValue = fc;
  6025. }
  6026. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  6027. {
  6028. // Must properly convert value in case the from value is smaller
  6029. int ic;
  6030. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  6031. ic = (signed char)from->type.byteValue;
  6032. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  6033. ic = (short)from->type.wordValue;
  6034. else
  6035. ic = from->type.intValue;
  6036. float fc = float(ic);
  6037. if( int(fc) != ic )
  6038. {
  6039. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  6040. }
  6041. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6042. from->type.floatValue = fc;
  6043. }
  6044. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  6045. {
  6046. float fc = float(asINT64(from->type.qwordValue));
  6047. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  6048. {
  6049. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  6050. }
  6051. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6052. from->type.floatValue = fc;
  6053. }
  6054. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  6055. {
  6056. // Must properly convert value in case the from value is smaller
  6057. unsigned int uic;
  6058. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  6059. uic = from->type.byteValue;
  6060. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  6061. uic = from->type.wordValue;
  6062. else
  6063. uic = from->type.dwordValue;
  6064. float fc = float(uic);
  6065. if( (unsigned int)(fc) != uic )
  6066. {
  6067. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  6068. }
  6069. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6070. from->type.floatValue = fc;
  6071. }
  6072. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  6073. {
  6074. float fc = float((asINT64)from->type.qwordValue);
  6075. if( asQWORD(fc) != from->type.qwordValue )
  6076. {
  6077. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  6078. }
  6079. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6080. from->type.floatValue = fc;
  6081. }
  6082. }
  6083. else if( to.IsDoubleType() )
  6084. {
  6085. if( from->type.dataType.IsFloatType() )
  6086. {
  6087. float ic = from->type.floatValue;
  6088. double fc = double(ic);
  6089. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6090. from->type.doubleValue = fc;
  6091. }
  6092. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  6093. {
  6094. // Must properly convert value in case the from value is smaller
  6095. int ic;
  6096. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  6097. ic = (signed char)from->type.byteValue;
  6098. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  6099. ic = (short)from->type.wordValue;
  6100. else
  6101. ic = from->type.intValue;
  6102. double fc = double(ic);
  6103. if( int(fc) != ic )
  6104. {
  6105. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  6106. }
  6107. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6108. from->type.doubleValue = fc;
  6109. }
  6110. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  6111. {
  6112. double fc = double(asINT64(from->type.qwordValue));
  6113. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  6114. {
  6115. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  6116. }
  6117. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6118. from->type.doubleValue = fc;
  6119. }
  6120. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  6121. {
  6122. // Must properly convert value in case the from value is smaller
  6123. unsigned int uic;
  6124. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  6125. uic = from->type.byteValue;
  6126. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  6127. uic = from->type.wordValue;
  6128. else
  6129. uic = from->type.dwordValue;
  6130. double fc = double(uic);
  6131. if( (unsigned int)(fc) != uic )
  6132. {
  6133. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  6134. }
  6135. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6136. from->type.doubleValue = fc;
  6137. }
  6138. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  6139. {
  6140. double fc = double((asINT64)from->type.qwordValue);
  6141. if( asQWORD(fc) != from->type.qwordValue )
  6142. {
  6143. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  6144. }
  6145. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  6146. from->type.doubleValue = fc;
  6147. }
  6148. }
  6149. }
  6150. int asCCompiler::DoAssignment(asSExprContext *ctx, asSExprContext *lctx, asSExprContext *rctx, asCScriptNode *lexpr, asCScriptNode *rexpr, int op, asCScriptNode *opNode)
  6151. {
  6152. // Don't allow any operators on expressions that take address of class method
  6153. // If methodName is set but the type is not an object, then it is a global function
  6154. if( lctx->methodName != "" || rctx->IsClassMethod() )
  6155. {
  6156. Error(TXT_INVALID_OP_ON_METHOD, opNode);
  6157. return -1;
  6158. }
  6159. // Implicit handle types should always be treated as handles in assignments
  6160. if (lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  6161. {
  6162. lctx->type.dataType.MakeHandle(true);
  6163. lctx->type.isExplicitHandle = true;
  6164. }
  6165. // Urho3D: if there is a handle type, and it does not have an overloaded assignment operator, convert to an explicit handle
  6166. // for scripting convenience. (For the Urho3D handle types, value assignment is not supported)
  6167. if (lctx->type.dataType.IsObjectHandle() && !lctx->type.dataType.IsTemplate() && !lctx->type.isExplicitHandle &&
  6168. !lctx->type.dataType.GetBehaviour()->copy)
  6169. lctx->type.isExplicitHandle = true;
  6170. // If the left hand expression is a property accessor, then that should be used
  6171. // to do the assignment instead of the ordinary operator. The exception is when
  6172. // the property accessor is for a handle property, and the operation is a value
  6173. // assignment.
  6174. if( (lctx->property_get || lctx->property_set) &&
  6175. !(lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle) )
  6176. {
  6177. if( op != ttAssignment )
  6178. {
  6179. // TODO: getset: We may actually be able to support this, if we can
  6180. // guarantee that the object reference will stay valid
  6181. // between the calls to the get and set accessors.
  6182. // Process the property to free the memory
  6183. ProcessPropertySetAccessor(lctx, rctx, opNode);
  6184. // Compound assignments are not allowed for properties
  6185. Error(TXT_COMPOUND_ASGN_WITH_PROP, opNode);
  6186. return -1;
  6187. }
  6188. // It is not allowed to do a handle assignment on a property
  6189. // accessor that doesn't take a handle in the set accessor.
  6190. if( lctx->property_set && lctx->type.isExplicitHandle )
  6191. {
  6192. // set_opIndex has 2 arguments, where as normal setters have only 1
  6193. asCArray<asCDataType>& parameterTypes =
  6194. builder->GetFunctionDescription(lctx->property_set)->parameterTypes;
  6195. if( !parameterTypes[parameterTypes.GetLength() - 1].IsObjectHandle() )
  6196. {
  6197. // Process the property to free the memory
  6198. ProcessPropertySetAccessor(lctx, rctx, opNode);
  6199. Error(TXT_HANDLE_ASSIGN_ON_NON_HANDLE_PROP, opNode);
  6200. return -1;
  6201. }
  6202. }
  6203. MergeExprBytecodeAndType(ctx, lctx);
  6204. return ProcessPropertySetAccessor(ctx, rctx, opNode);
  6205. }
  6206. else if( lctx->property_get && lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  6207. {
  6208. // Get the handle to the object that will be used for the value assignment
  6209. ProcessPropertyGetAccessor(lctx, opNode);
  6210. }
  6211. if( lctx->type.dataType.IsPrimitive() )
  6212. {
  6213. if( !lctx->type.isLValue )
  6214. {
  6215. Error(TXT_NOT_LVALUE, lexpr);
  6216. return -1;
  6217. }
  6218. if( op != ttAssignment )
  6219. {
  6220. // Compute the operator before the assignment
  6221. asCTypeInfo lvalue = lctx->type;
  6222. if( lctx->type.isTemporary && !lctx->type.isVariable )
  6223. {
  6224. // The temporary variable must not be freed until the
  6225. // assignment has been performed. lvalue still holds
  6226. // the information about the temporary variable
  6227. lctx->type.isTemporary = false;
  6228. }
  6229. asSExprContext o(engine);
  6230. CompileOperator(opNode, lctx, rctx, &o);
  6231. MergeExprBytecode(rctx, &o);
  6232. rctx->type = o.type;
  6233. // Convert the rvalue to the right type and validate it
  6234. PrepareForAssignment(&lvalue.dataType, rctx, rexpr, false);
  6235. MergeExprBytecode(ctx, rctx);
  6236. lctx->type = lvalue;
  6237. // The lvalue continues the same, either it was a variable, or a reference in the register
  6238. }
  6239. else
  6240. {
  6241. // Convert the rvalue to the right type and validate it
  6242. PrepareForAssignment(&lctx->type.dataType, rctx, rexpr, false, lctx);
  6243. MergeExprBytecode(ctx, rctx);
  6244. MergeExprBytecode(ctx, lctx);
  6245. }
  6246. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  6247. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  6248. ctx->type = lctx->type;
  6249. }
  6250. else if( lctx->type.isExplicitHandle )
  6251. {
  6252. if( !lctx->type.isLValue )
  6253. {
  6254. Error(TXT_NOT_LVALUE, lexpr);
  6255. return -1;
  6256. }
  6257. // Object handles don't have any compound assignment operators
  6258. if( op != ttAssignment )
  6259. {
  6260. asCString str;
  6261. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  6262. Error(str, lexpr);
  6263. return -1;
  6264. }
  6265. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  6266. {
  6267. // The object is a value type but that should be treated as a handle
  6268. // Make sure the right hand value is a handle
  6269. if( !rctx->type.isExplicitHandle &&
  6270. !(rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  6271. {
  6272. // Function names can be considered handles already
  6273. if( rctx->methodName == "" )
  6274. {
  6275. asCDataType dt = rctx->type.dataType;
  6276. dt.MakeHandle(true);
  6277. dt.MakeReference(false);
  6278. PrepareArgument(&dt, rctx, rexpr, true, asTM_INREF);
  6279. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  6280. {
  6281. asCString str;
  6282. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  6283. Error(str, rexpr);
  6284. return -1;
  6285. }
  6286. }
  6287. }
  6288. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx, true) )
  6289. {
  6290. // An overloaded assignment operator was found (or a compilation error occured)
  6291. return 0;
  6292. }
  6293. // The object must implement the opAssign method
  6294. asCString msg;
  6295. msg.Format(TXT_NO_APPROPRIATE_OPHNDLASSIGN_s, lctx->type.dataType.Format().AddressOf());
  6296. Error(msg.AddressOf(), opNode);
  6297. return -1;
  6298. }
  6299. else
  6300. {
  6301. asCDataType dt = lctx->type.dataType;
  6302. dt.MakeReference(false);
  6303. PrepareArgument(&dt, rctx, rexpr, true, asTM_INREF , true);
  6304. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  6305. {
  6306. asCString str;
  6307. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  6308. Error(str, rexpr);
  6309. return -1;
  6310. }
  6311. MergeExprBytecode(ctx, rctx);
  6312. MergeExprBytecode(ctx, lctx);
  6313. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  6314. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  6315. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  6316. ctx->type = lctx->type;
  6317. // After the handle assignment the original handle is left on the stack
  6318. ctx->type.dataType.MakeReference(false);
  6319. }
  6320. }
  6321. else // if( lctx->type.dataType.IsObject() )
  6322. {
  6323. // The lvalue reference may be marked as a temporary, if for example
  6324. // it was originated as a handle returned from a function. In such
  6325. // cases it must be possible to assign values to it anyway.
  6326. if( lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  6327. {
  6328. // Convert the handle to a object reference
  6329. asCDataType to;
  6330. to = lctx->type.dataType;
  6331. to.MakeHandle(false);
  6332. ImplicitConversion(lctx, to, lexpr, asIC_IMPLICIT_CONV);
  6333. lctx->type.isLValue = true; // Handle may not have been an lvalue, but the dereferenced object is
  6334. }
  6335. // Check for overloaded assignment operator
  6336. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  6337. {
  6338. // An overloaded assignment operator was found (or a compilation error occured)
  6339. return 0;
  6340. }
  6341. // No registered operator was found. In case the operation is a direct
  6342. // assignment and the rvalue is the same type as the lvalue, then we can
  6343. // still use the byte-for-byte copy to do the assignment
  6344. if( op != ttAssignment )
  6345. {
  6346. asCString str;
  6347. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  6348. Error(str, lexpr);
  6349. return -1;
  6350. }
  6351. // If the left hand expression is simple, i.e. without any
  6352. // function calls or allocations of memory, then we can avoid
  6353. // doing a copy of the right hand expression (done by PrepareArgument).
  6354. // Instead the reference to the value can be placed directly on the
  6355. // stack.
  6356. //
  6357. // This optimization should only be done for value types, where
  6358. // the application developer is responsible for making the
  6359. // implementation safe against unwanted destruction of the input
  6360. // reference before the time.
  6361. bool simpleExpr = (lctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) && lctx->bc.IsSimpleExpression();
  6362. // Implicitly convert the rvalue to the type of the lvalue
  6363. bool needConversion = false;
  6364. if( !lctx->type.dataType.IsEqualExceptRefAndConst(rctx->type.dataType) )
  6365. needConversion = true;
  6366. if( !simpleExpr || needConversion )
  6367. {
  6368. asCDataType dt = lctx->type.dataType;
  6369. dt.MakeReference(true);
  6370. dt.MakeReadOnly(true);
  6371. int r = PrepareArgument(&dt, rctx, rexpr, true, 1, !needConversion);
  6372. if( r < 0 )
  6373. return -1;
  6374. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  6375. {
  6376. asCString str;
  6377. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  6378. Error(str, rexpr);
  6379. return -1;
  6380. }
  6381. }
  6382. else
  6383. {
  6384. // Process any property accessor first, before placing the final reference on the stack
  6385. ProcessPropertyGetAccessor(rctx, rexpr);
  6386. if( rctx->type.dataType.IsReference() && (!(rctx->type.isVariable || rctx->type.isTemporary) || IsVariableOnHeap(rctx->type.stackOffset)) )
  6387. rctx->bc.Instr(asBC_RDSPtr);
  6388. }
  6389. MergeExprBytecode(ctx, rctx);
  6390. MergeExprBytecode(ctx, lctx);
  6391. if( !simpleExpr || needConversion )
  6392. {
  6393. if( (rctx->type.isVariable || rctx->type.isTemporary) )
  6394. {
  6395. if( !IsVariableOnHeap(rctx->type.stackOffset) )
  6396. // TODO: runtime optimize: Actually the reference can be pushed on the stack directly
  6397. // as the value allocated on the stack is guaranteed to be safe.
  6398. // The bytecode optimizer should be able to determine this and optimize away the VAR + GETREF
  6399. ctx->bc.InstrWORD(asBC_GETREF, AS_PTR_SIZE);
  6400. else
  6401. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  6402. }
  6403. }
  6404. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  6405. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  6406. ctx->type = lctx->type;
  6407. }
  6408. return 0;
  6409. }
  6410. int asCCompiler::CompileAssignment(asCScriptNode *expr, asSExprContext *ctx)
  6411. {
  6412. asCScriptNode *lexpr = expr->firstChild;
  6413. if( lexpr->next )
  6414. {
  6415. // Compile the two expression terms
  6416. asSExprContext lctx(engine), rctx(engine);
  6417. int rr = CompileAssignment(lexpr->next->next, &rctx);
  6418. int lr = CompileCondition(lexpr, &lctx);
  6419. if( lr >= 0 && rr >= 0 )
  6420. return DoAssignment(ctx, &lctx, &rctx, lexpr, lexpr->next->next, lexpr->next->tokenType, lexpr->next);
  6421. // Since the operands failed, the assignment was not computed
  6422. ctx->type.SetDummy();
  6423. return -1;
  6424. }
  6425. return CompileCondition(lexpr, ctx);
  6426. }
  6427. int asCCompiler::CompileCondition(asCScriptNode *expr, asSExprContext *ctx)
  6428. {
  6429. asCTypeInfo ctype;
  6430. // Compile the conditional expression
  6431. asCScriptNode *cexpr = expr->firstChild;
  6432. if( cexpr->next )
  6433. {
  6434. //-------------------------------
  6435. // Compile the condition
  6436. asSExprContext e(engine);
  6437. int r = CompileExpression(cexpr, &e);
  6438. if( r < 0 )
  6439. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  6440. if( r >= 0 && !e.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  6441. {
  6442. Error(TXT_EXPR_MUST_BE_BOOL, cexpr);
  6443. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  6444. }
  6445. ctype = e.type;
  6446. ProcessPropertyGetAccessor(&e, cexpr);
  6447. if( e.type.dataType.IsReference() ) ConvertToVariable(&e);
  6448. ProcessDeferredParams(&e);
  6449. //-------------------------------
  6450. // Compile the left expression
  6451. asSExprContext le(engine);
  6452. int lr = CompileAssignment(cexpr->next, &le);
  6453. //-------------------------------
  6454. // Compile the right expression
  6455. asSExprContext re(engine);
  6456. int rr = CompileAssignment(cexpr->next->next, &re);
  6457. if( lr >= 0 && rr >= 0 )
  6458. {
  6459. // Don't allow any operators on expressions that take address of class method
  6460. if( le.IsClassMethod() || re.IsClassMethod() )
  6461. {
  6462. Error(TXT_INVALID_OP_ON_METHOD, expr);
  6463. return -1;
  6464. }
  6465. ProcessPropertyGetAccessor(&le, cexpr->next);
  6466. ProcessPropertyGetAccessor(&re, cexpr->next->next);
  6467. bool isExplicitHandle = le.type.isExplicitHandle || re.type.isExplicitHandle;
  6468. // Allow a 0 or null in the first case to be implicitly converted to the second type
  6469. if( le.type.isConstant && le.type.intValue == 0 && le.type.dataType.IsIntegerType() )
  6470. {
  6471. asCDataType to = re.type.dataType;
  6472. to.MakeReference(false);
  6473. to.MakeReadOnly(true);
  6474. ImplicitConversionConstant(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  6475. }
  6476. else if( le.type.IsNullConstant() )
  6477. {
  6478. asCDataType to = re.type.dataType;
  6479. to.MakeHandle(true);
  6480. ImplicitConversion(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  6481. }
  6482. // Allow either case to be converted to const @ if the other is const @
  6483. if( (le.type.dataType.IsHandleToConst() && !le.type.IsNullConstant()) || (re.type.dataType.IsHandleToConst() && !re.type.dataType.IsNullHandle()) )
  6484. {
  6485. le.type.dataType.MakeHandleToConst(true);
  6486. re.type.dataType.MakeHandleToConst(true);
  6487. }
  6488. //---------------------------------
  6489. // Output the byte code
  6490. int afterLabel = nextLabel++;
  6491. int elseLabel = nextLabel++;
  6492. // If left expression is void, then we don't need to store the result
  6493. if( le.type.dataType.IsEqualExceptConst(asCDataType::CreatePrimitive(ttVoid, false)) )
  6494. {
  6495. // Put the code for the condition expression on the output
  6496. MergeExprBytecode(ctx, &e);
  6497. // Added the branch decision
  6498. ctx->type = e.type;
  6499. ConvertToVariable(ctx);
  6500. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  6501. ctx->bc.Instr(asBC_ClrHi);
  6502. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  6503. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  6504. // Add the left expression
  6505. MergeExprBytecode(ctx, &le);
  6506. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  6507. // Add the right expression
  6508. ctx->bc.Label((short)elseLabel);
  6509. MergeExprBytecode(ctx, &re);
  6510. ctx->bc.Label((short)afterLabel);
  6511. // Make sure both expressions have the same type
  6512. if( le.type.dataType != re.type.dataType )
  6513. Error(TXT_BOTH_MUST_BE_SAME, expr);
  6514. // Set the type of the result
  6515. ctx->type = le.type;
  6516. }
  6517. else
  6518. {
  6519. // Allocate temporary variable and copy the result to that one
  6520. asCTypeInfo temp;
  6521. temp = le.type;
  6522. temp.dataType.MakeReference(false);
  6523. temp.dataType.MakeReadOnly(false);
  6524. // Make sure the variable isn't used in any of the expressions,
  6525. // as it would be overwritten which may cause crashes or less visible bugs
  6526. int l = int(reservedVariables.GetLength());
  6527. e.bc.GetVarsUsed(reservedVariables);
  6528. le.bc.GetVarsUsed(reservedVariables);
  6529. re.bc.GetVarsUsed(reservedVariables);
  6530. int offset = AllocateVariable(temp.dataType, true, false);
  6531. reservedVariables.SetLength(l);
  6532. temp.SetVariable(temp.dataType, offset, true);
  6533. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  6534. CallDefaultConstructor(temp.dataType, offset, IsVariableOnHeap(offset), &ctx->bc, expr);
  6535. // Put the code for the condition expression on the output
  6536. MergeExprBytecode(ctx, &e);
  6537. // Add the branch decision
  6538. ctx->type = e.type;
  6539. ConvertToVariable(ctx);
  6540. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  6541. ctx->bc.Instr(asBC_ClrHi);
  6542. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  6543. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  6544. // Assign the result of the left expression to the temporary variable
  6545. asCTypeInfo rtemp;
  6546. rtemp = temp;
  6547. if( rtemp.dataType.IsObjectHandle() )
  6548. rtemp.isExplicitHandle = true;
  6549. PrepareForAssignment(&rtemp.dataType, &le, cexpr->next, true);
  6550. MergeExprBytecode(ctx, &le);
  6551. if( !rtemp.dataType.IsPrimitive() )
  6552. {
  6553. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  6554. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  6555. }
  6556. asCTypeInfo result;
  6557. result = rtemp;
  6558. PerformAssignment(&result, &le.type, &ctx->bc, cexpr->next);
  6559. if( !result.dataType.IsPrimitive() )
  6560. ctx->bc.Instr(asBC_PopPtr); // Pop the original value (always a pointer)
  6561. // Release the old temporary variable
  6562. ReleaseTemporaryVariable(le.type, &ctx->bc);
  6563. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  6564. // Start of the right expression
  6565. ctx->bc.Label((short)elseLabel);
  6566. // Copy the result to the same temporary variable
  6567. PrepareForAssignment(&rtemp.dataType, &re, cexpr->next, true);
  6568. MergeExprBytecode(ctx, &re);
  6569. if( !rtemp.dataType.IsPrimitive() )
  6570. {
  6571. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  6572. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  6573. }
  6574. result = rtemp;
  6575. PerformAssignment(&result, &re.type, &ctx->bc, cexpr->next);
  6576. if( !result.dataType.IsPrimitive() )
  6577. ctx->bc.Instr(asBC_PopPtr); // Pop the original value (always a pointer)
  6578. // Release the old temporary variable
  6579. ReleaseTemporaryVariable(re.type, &ctx->bc);
  6580. ctx->bc.Label((short)afterLabel);
  6581. // Make sure both expressions have the same type
  6582. if( !le.type.dataType.IsEqualExceptConst(re.type.dataType) )
  6583. Error(TXT_BOTH_MUST_BE_SAME, expr);
  6584. // Set the temporary variable as output
  6585. ctx->type = rtemp;
  6586. ctx->type.isExplicitHandle = isExplicitHandle;
  6587. if( !ctx->type.dataType.IsPrimitive() )
  6588. {
  6589. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  6590. ctx->type.dataType.MakeReference(IsVariableOnHeap(offset));
  6591. }
  6592. // Make sure the output isn't marked as being a literal constant
  6593. ctx->type.isConstant = false;
  6594. }
  6595. }
  6596. else
  6597. {
  6598. ctx->type.SetDummy();
  6599. return -1;
  6600. }
  6601. }
  6602. else
  6603. return CompileExpression(cexpr, ctx);
  6604. return 0;
  6605. }
  6606. int asCCompiler::CompileExpression(asCScriptNode *expr, asSExprContext *ctx)
  6607. {
  6608. asASSERT(expr->nodeType == snExpression);
  6609. // Check if this is an initialization of a temp object with an initialization list
  6610. if( expr->firstChild && expr->firstChild->nodeType == snDataType )
  6611. {
  6612. // TODO: It should be possible to infer the type of the object from where the
  6613. // expression will be used. The compilation of the initialization list
  6614. // should be deferred until it is known for what it will be used. It will
  6615. // then for example be possible to write expressions like:
  6616. //
  6617. // @dict = {{'key', 'value'}};
  6618. // funcTakingArrayOfInt({1,2,3,4});
  6619. // Determine the type of the temporary object
  6620. asCDataType dt = builder->CreateDataTypeFromNode(expr->firstChild, script, outFunc->nameSpace);
  6621. // Do not allow constructing non-shared types in shared functions
  6622. if( outFunc->IsShared() &&
  6623. dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  6624. {
  6625. asCString msg;
  6626. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  6627. Error(msg, expr);
  6628. }
  6629. // Allocate and initialize the temporary object
  6630. int offset = AllocateVariable(dt, true);
  6631. CompileInitialization(expr->lastChild, &ctx->bc, dt, expr, offset, 0, 0);
  6632. // Push the reference to the object on the stack
  6633. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  6634. ctx->type.SetVariable(dt, offset, true);
  6635. ctx->type.isLValue = false;
  6636. // If the variable is allocated on the heap we have a reference,
  6637. // otherwise the actual object pointer is pushed on the stack.
  6638. if( IsVariableOnHeap(offset) )
  6639. ctx->type.dataType.MakeReference(true);
  6640. return 0;
  6641. }
  6642. // Convert to polish post fix, i.e: a+b => ab+
  6643. // The algorithm that I've implemented here is similar to
  6644. // Djikstra's Shunting Yard algorithm, though I didn't know it at the time.
  6645. // ref: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
  6646. // Count the nodes in order to preallocate the buffers
  6647. int count = 0;
  6648. asCScriptNode *node = expr->firstChild;
  6649. while( node )
  6650. {
  6651. count++;
  6652. node = node->next;
  6653. }
  6654. asCArray<asCScriptNode *> stack(count);
  6655. asCArray<asCScriptNode *> stack2(count);
  6656. node = expr->firstChild;
  6657. while( node )
  6658. {
  6659. int precedence = GetPrecedence(node);
  6660. while( stack.GetLength() > 0 &&
  6661. precedence <= GetPrecedence(stack[stack.GetLength()-1]) )
  6662. stack2.PushLast(stack.PopLast());
  6663. stack.PushLast(node);
  6664. node = node->next;
  6665. }
  6666. while( stack.GetLength() > 0 )
  6667. stack2.PushLast(stack.PopLast());
  6668. // Compile the postfix formatted expression
  6669. return CompilePostFixExpression(&stack2, ctx);
  6670. }
  6671. int asCCompiler::CompilePostFixExpression(asCArray<asCScriptNode *> *postfix, asSExprContext *ctx)
  6672. {
  6673. // Shouldn't send any byte code
  6674. asASSERT(ctx->bc.GetLastInstr() == -1);
  6675. // Set the context to a dummy type to avoid further
  6676. // errors in case the expression fails to compile
  6677. ctx->type.SetDummy();
  6678. // Evaluate the operands and operators
  6679. asCArray<asSExprContext*> free;
  6680. asCArray<asSExprContext*> expr;
  6681. int ret = 0;
  6682. for( asUINT n = 0; ret == 0 && n < postfix->GetLength(); n++ )
  6683. {
  6684. asCScriptNode *node = (*postfix)[n];
  6685. if( node->nodeType == snExprTerm )
  6686. {
  6687. asSExprContext *e = free.GetLength() ? free.PopLast() : asNEW(asSExprContext)(engine);
  6688. expr.PushLast(e);
  6689. e->exprNode = node;
  6690. ret = CompileExpressionTerm(node, e);
  6691. }
  6692. else
  6693. {
  6694. asSExprContext *r = expr.PopLast();
  6695. asSExprContext *l = expr.PopLast();
  6696. // Now compile the operator
  6697. asSExprContext *e = free.GetLength() ? free.PopLast() : asNEW(asSExprContext)(engine);
  6698. ret = CompileOperator(node, l, r, e);
  6699. expr.PushLast(e);
  6700. // Free the operands
  6701. l->Clear();
  6702. free.PushLast(l);
  6703. r->Clear();
  6704. free.PushLast(r);
  6705. }
  6706. }
  6707. if( ret == 0 )
  6708. {
  6709. asASSERT(expr.GetLength() == 1);
  6710. // The final result should be moved to the output context
  6711. MergeExprBytecodeAndType(ctx, expr[0]);
  6712. }
  6713. // Clean up
  6714. for( asUINT e = 0; e < expr.GetLength(); e++ )
  6715. asDELETE(expr[e], asSExprContext);
  6716. for( asUINT f = 0; f < free.GetLength(); f++ )
  6717. asDELETE(free[f], asSExprContext);
  6718. return ret;
  6719. }
  6720. int asCCompiler::CompileExpressionTerm(asCScriptNode *node, asSExprContext *ctx)
  6721. {
  6722. // Shouldn't send any byte code
  6723. asASSERT(ctx->bc.GetLastInstr() == -1);
  6724. // Set the type as a dummy by default, in case of any compiler errors
  6725. ctx->type.SetDummy();
  6726. // Compile the value node
  6727. asCScriptNode *vnode = node->firstChild;
  6728. while( vnode->nodeType != snExprValue )
  6729. vnode = vnode->next;
  6730. asSExprContext v(engine);
  6731. int r = CompileExpressionValue(vnode, &v); if( r < 0 ) return r;
  6732. // Compile post fix operators
  6733. asCScriptNode *pnode = vnode->next;
  6734. while( pnode )
  6735. {
  6736. r = CompileExpressionPostOp(pnode, &v); if( r < 0 ) return r;
  6737. pnode = pnode->next;
  6738. }
  6739. // Compile pre fix operators
  6740. pnode = vnode->prev;
  6741. while( pnode )
  6742. {
  6743. r = CompileExpressionPreOp(pnode, &v); if( r < 0 ) return r;
  6744. pnode = pnode->prev;
  6745. }
  6746. // Return the byte code and final type description
  6747. MergeExprBytecodeAndType(ctx, &v);
  6748. return 0;
  6749. }
  6750. int asCCompiler::CompileVariableAccess(const asCString &name, const asCString &scope, asSExprContext *ctx, asCScriptNode *errNode, bool isOptional, bool noFunction, bool noGlobal, asCObjectType *objType)
  6751. {
  6752. bool found = false;
  6753. // It is a local variable or parameter?
  6754. // This is not accessible by default arg expressions
  6755. sVariable *v = 0;
  6756. if( !isCompilingDefaultArg && scope == "" && !objType && variables )
  6757. v = variables->GetVariable(name.AddressOf());
  6758. if( v )
  6759. {
  6760. found = true;
  6761. if( v->isPureConstant )
  6762. ctx->type.SetConstantQW(v->type, v->constantValue);
  6763. else if( v->type.IsPrimitive() )
  6764. {
  6765. if( v->type.IsReference() )
  6766. {
  6767. // Copy the reference into the register
  6768. ctx->bc.InstrSHORT(asBC_PshVPtr, (short)v->stackOffset);
  6769. ctx->bc.Instr(asBC_PopRPtr);
  6770. ctx->type.Set(v->type);
  6771. }
  6772. else
  6773. ctx->type.SetVariable(v->type, v->stackOffset, false);
  6774. ctx->type.isLValue = true;
  6775. }
  6776. else
  6777. {
  6778. ctx->bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  6779. ctx->type.SetVariable(v->type, v->stackOffset, false);
  6780. // If the variable is allocated on the heap we have a reference,
  6781. // otherwise the actual object pointer is pushed on the stack.
  6782. if( v->onHeap || v->type.IsObjectHandle() ) ctx->type.dataType.MakeReference(true);
  6783. // Implicitly dereference handle parameters sent by reference
  6784. if( v->type.IsReference() && (!v->type.IsObject() || v->type.IsObjectHandle()) )
  6785. ctx->bc.Instr(asBC_RDSPtr);
  6786. ctx->type.isLValue = true;
  6787. }
  6788. }
  6789. // Is it a class member?
  6790. // This is not accessible by default arg expressions
  6791. if( !isCompilingDefaultArg && !found && ((objType) || (outFunc && outFunc->objectType && scope == "")) )
  6792. {
  6793. if( name == THIS_TOKEN && !objType )
  6794. {
  6795. asCDataType dt = asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly);
  6796. // The object pointer is located at stack position 0
  6797. ctx->bc.InstrSHORT(asBC_PSF, 0);
  6798. ctx->type.SetVariable(dt, 0, false);
  6799. ctx->type.dataType.MakeReference(true);
  6800. ctx->type.isLValue = true;
  6801. found = true;
  6802. }
  6803. if( !found )
  6804. {
  6805. // See if there are any matching property accessors
  6806. asSExprContext access(engine);
  6807. if( objType )
  6808. access.type.Set(asCDataType::CreateObject(objType, false));
  6809. else
  6810. access.type.Set(asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly));
  6811. access.type.dataType.MakeReference(true);
  6812. int r = 0;
  6813. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  6814. {
  6815. // This is an index access, check if there is a property accessor that takes an index arg
  6816. asSExprContext dummyArg(engine);
  6817. r = FindPropertyAccessor(name, &access, &dummyArg, errNode, 0, true);
  6818. }
  6819. if( r == 0 )
  6820. {
  6821. // Normal property access
  6822. r = FindPropertyAccessor(name, &access, errNode, 0, true);
  6823. }
  6824. if( r < 0 ) return -1;
  6825. if( access.property_get || access.property_set )
  6826. {
  6827. if( !objType )
  6828. {
  6829. // Prepare the bytecode for the member access
  6830. // This is only done when accessing through the implicit this pointer
  6831. ctx->bc.InstrSHORT(asBC_PSF, 0);
  6832. }
  6833. MergeExprBytecodeAndType(ctx, &access);
  6834. found = true;
  6835. }
  6836. }
  6837. if( !found )
  6838. {
  6839. asCDataType dt;
  6840. if( objType )
  6841. dt = asCDataType::CreateObject(objType, false);
  6842. else
  6843. dt = asCDataType::CreateObject(outFunc->objectType, false);
  6844. asCObjectProperty *prop = builder->GetObjectProperty(dt, name.AddressOf());
  6845. if( prop )
  6846. {
  6847. if( !objType )
  6848. {
  6849. // The object pointer is located at stack position 0
  6850. // This is only done when accessing through the implicit this pointer
  6851. ctx->bc.InstrSHORT(asBC_PSF, 0);
  6852. ctx->type.SetVariable(dt, 0, false);
  6853. ctx->type.dataType.MakeReference(true);
  6854. Dereference(ctx, true);
  6855. }
  6856. // TODO: This is the same as what is in CompileExpressionPostOp
  6857. // Put the offset on the stack
  6858. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(dt));
  6859. if( prop->type.IsReference() )
  6860. ctx->bc.Instr(asBC_RDSPtr);
  6861. // Reference to primitive must be stored in the temp register
  6862. if( prop->type.IsPrimitive() )
  6863. {
  6864. // TODO: runtime optimize: The ADD offset command should store the reference in the register directly
  6865. ctx->bc.Instr(asBC_PopRPtr);
  6866. }
  6867. // Set the new type (keeping info about temp variable)
  6868. ctx->type.dataType = prop->type;
  6869. ctx->type.dataType.MakeReference(true);
  6870. ctx->type.isVariable = false;
  6871. ctx->type.isLValue = true;
  6872. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  6873. {
  6874. // Objects that are members are not references
  6875. ctx->type.dataType.MakeReference(false);
  6876. }
  6877. // If the object reference is const, the property will also be const
  6878. ctx->type.dataType.MakeReadOnly(outFunc->isReadOnly);
  6879. found = true;
  6880. }
  6881. else if( outFunc->objectType )
  6882. {
  6883. // If it is not a property, it may still be the name of a method which can be used to create delegates
  6884. asCObjectType *ot = outFunc->objectType;
  6885. asCScriptFunction *func = 0;
  6886. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  6887. {
  6888. if( engine->scriptFunctions[ot->methods[n]]->name == name )
  6889. {
  6890. func = engine->scriptFunctions[ot->methods[n]];
  6891. break;
  6892. }
  6893. }
  6894. if( func )
  6895. {
  6896. // An object method was found. Keep the name of the method in the expression, but
  6897. // don't actually modify the bytecode at this point since it is not yet known what
  6898. // the method will be used for, or even what overloaded method should be used.
  6899. ctx->methodName = name;
  6900. // Place the object pointer on the stack, as if the expression was this.func
  6901. if( !objType )
  6902. {
  6903. // The object pointer is located at stack position 0
  6904. // This is only done when accessing through the implicit this pointer
  6905. ctx->bc.InstrSHORT(asBC_PSF, 0);
  6906. ctx->type.SetVariable(asCDataType::CreateObject(outFunc->objectType, false), 0, false);
  6907. ctx->type.dataType.MakeReference(true);
  6908. Dereference(ctx, true);
  6909. }
  6910. found = true;
  6911. }
  6912. }
  6913. }
  6914. }
  6915. // Recursively search parent namespaces for global entities
  6916. asCString currScope = scope;
  6917. if( scope == "" )
  6918. currScope = outFunc->nameSpace->name;
  6919. while( !found && !noGlobal && !objType )
  6920. {
  6921. asSNameSpace *ns = DetermineNameSpace(currScope);
  6922. // Is it a global property?
  6923. if( !found && ns )
  6924. {
  6925. // See if there are any matching global property accessors
  6926. asSExprContext access(engine);
  6927. int r = 0;
  6928. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  6929. {
  6930. // This is an index access, check if there is a property accessor that takes an index arg
  6931. asSExprContext dummyArg(engine);
  6932. r = FindPropertyAccessor(name, &access, &dummyArg, errNode, ns);
  6933. }
  6934. if( r == 0 )
  6935. {
  6936. // Normal property access
  6937. r = FindPropertyAccessor(name, &access, errNode, ns);
  6938. }
  6939. if( r < 0 ) return -1;
  6940. if( access.property_get || access.property_set )
  6941. {
  6942. // Prepare the bytecode for the function call
  6943. MergeExprBytecodeAndType(ctx, &access);
  6944. found = true;
  6945. }
  6946. // See if there is any matching global property
  6947. if( !found )
  6948. {
  6949. bool isCompiled = true;
  6950. bool isPureConstant = false;
  6951. bool isAppProp = false;
  6952. asQWORD constantValue = 0;
  6953. asCGlobalProperty *prop = builder->GetGlobalProperty(name.AddressOf(), ns, &isCompiled, &isPureConstant, &constantValue, &isAppProp);
  6954. if( prop )
  6955. {
  6956. found = true;
  6957. // Verify that the global property has been compiled already
  6958. if( isCompiled )
  6959. {
  6960. if( ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  6961. {
  6962. ctx->type.dataType.MakeHandle(true);
  6963. ctx->type.isExplicitHandle = true;
  6964. }
  6965. // If the global property is a pure constant
  6966. // we can allow the compiler to optimize it. Pure
  6967. // constants are global constant variables that were
  6968. // initialized by literal constants.
  6969. if( isPureConstant )
  6970. ctx->type.SetConstantQW(prop->type, constantValue);
  6971. else
  6972. {
  6973. // A shared type must not access global vars, unless they
  6974. // too are shared, e.g. application registered vars
  6975. if( outFunc->IsShared() )
  6976. {
  6977. if( !isAppProp )
  6978. {
  6979. asCString str;
  6980. str.Format(TXT_SHARED_CANNOT_ACCESS_NON_SHARED_VAR_s, prop->name.AddressOf());
  6981. Error(str, errNode);
  6982. // Allow the compilation to continue to catch other problems
  6983. }
  6984. }
  6985. ctx->type.Set(prop->type);
  6986. ctx->type.isLValue = true;
  6987. if( ctx->type.dataType.IsPrimitive() )
  6988. {
  6989. // Load the address of the variable into the register
  6990. ctx->bc.InstrPTR(asBC_LDG, prop->GetAddressOfValue());
  6991. ctx->type.dataType.MakeReference(true);
  6992. }
  6993. else
  6994. {
  6995. // Push the address of the variable on the stack
  6996. ctx->bc.InstrPTR(asBC_PGA, prop->GetAddressOfValue());
  6997. // If the object is a value type or a non-handle variable to a reference type,
  6998. // then we must validate the existance as it could potentially be accessed
  6999. // before it is initialized.
  7000. if( (ctx->type.dataType.GetObjectType()->flags & asOBJ_VALUE) ||
  7001. !ctx->type.dataType.IsObjectHandle() )
  7002. {
  7003. // TODO: runtime optimize: This is not necessary for application registered properties
  7004. ctx->bc.Instr(asBC_ChkRefS);
  7005. }
  7006. // If the address pushed on the stack is to a value type or an object
  7007. // handle, then mark the expression as a reference. Addresses to a reference
  7008. // type aren't marked as references to get correct behaviour
  7009. if( (ctx->type.dataType.GetObjectType()->flags & asOBJ_VALUE) ||
  7010. ctx->type.dataType.IsObjectHandle() )
  7011. {
  7012. ctx->type.dataType.MakeReference(true);
  7013. }
  7014. else
  7015. {
  7016. asASSERT( (ctx->type.dataType.GetObjectType()->flags & asOBJ_REF) && !ctx->type.dataType.IsObjectHandle() );
  7017. // It's necessary to dereference the pointer so the pointer on the stack will point to the actual object
  7018. ctx->bc.Instr(asBC_RDSPtr);
  7019. }
  7020. }
  7021. }
  7022. }
  7023. else
  7024. {
  7025. asCString str;
  7026. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, prop->name.AddressOf());
  7027. Error(str, errNode);
  7028. return -1;
  7029. }
  7030. }
  7031. }
  7032. }
  7033. // Is it the name of a global function?
  7034. if( !noFunction && !found && ns )
  7035. {
  7036. asCArray<int> funcs;
  7037. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  7038. if( funcs.GetLength() > 0 )
  7039. {
  7040. found = true;
  7041. // Defer the evaluation of which function until it is actually used
  7042. // Store the namespace and name of the function for later
  7043. ctx->type.SetUndefinedFuncHandle(engine);
  7044. ctx->methodName = ns ? ns->name + "::" + name : name;
  7045. }
  7046. }
  7047. // Is it an enum value?
  7048. if( !found )
  7049. {
  7050. // The enum type may be declared in a namespace too
  7051. asCObjectType *scopeType = 0;
  7052. if( currScope != "" && currScope != "::" )
  7053. {
  7054. // Use the last scope name as the enum type
  7055. asCString enumType = currScope;
  7056. asCString nsScope;
  7057. int p = currScope.FindLast("::");
  7058. if( p != -1 )
  7059. {
  7060. enumType = currScope.SubString(p+2);
  7061. nsScope = currScope.SubString(0, p);
  7062. }
  7063. asSNameSpace *ns = engine->FindNameSpace(nsScope.AddressOf());
  7064. if( ns )
  7065. scopeType = builder->GetObjectType(enumType.AddressOf(), ns);
  7066. }
  7067. asDWORD value = 0;
  7068. asCDataType dt;
  7069. if( scopeType && builder->GetEnumValueFromObjectType(scopeType, name.AddressOf(), dt, value) )
  7070. {
  7071. // scoped enum value found
  7072. found = true;
  7073. }
  7074. else if( !engine->ep.requireEnumScope )
  7075. {
  7076. // Look for the enum value without explicitly informing the enum type
  7077. asSNameSpace *ns = DetermineNameSpace(currScope);
  7078. int e = 0;
  7079. if( ns )
  7080. e = builder->GetEnumValue(name.AddressOf(), dt, value, ns);
  7081. if( e )
  7082. {
  7083. found = true;
  7084. if( e == 2 )
  7085. {
  7086. // Ambiguous enum value: Save the name for resolution later.
  7087. // The ambiguity could be resolved now, but I hesitate
  7088. // to store too much information in the context.
  7089. ctx->enumValue = name.AddressOf();
  7090. // We cannot set a dummy value because it will pass through
  7091. // cleanly as an integer.
  7092. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttIdentifier, true), 0);
  7093. return 0;
  7094. }
  7095. }
  7096. }
  7097. if( found )
  7098. {
  7099. // Even if the enum type is not shared, and we're compiling a shared object,
  7100. // the use of the values are still allowed, since they are treated as constants.
  7101. // an enum value was resolved
  7102. ctx->type.SetConstantDW(dt, value);
  7103. }
  7104. else
  7105. {
  7106. // If nothing was found because the scope doesn't match a namespace or an enum
  7107. // then this should be reported as an error and the search interrupted
  7108. if( !ns && !scopeType )
  7109. {
  7110. ctx->type.SetDummy();
  7111. asCString str;
  7112. str.Format(TXT_UNKNOWN_SCOPE_s, currScope.AddressOf());
  7113. Error(str, errNode);
  7114. return -1;
  7115. }
  7116. }
  7117. }
  7118. if( !found )
  7119. {
  7120. if( currScope == "" || currScope == "::" )
  7121. break;
  7122. // Move up to parent namespace
  7123. int pos = currScope.FindLast("::");
  7124. if( pos >= 0 )
  7125. currScope = currScope.SubString(0, pos);
  7126. else
  7127. currScope = "::";
  7128. }
  7129. }
  7130. // The name doesn't match any variable
  7131. if( !found )
  7132. {
  7133. // Give dummy value
  7134. ctx->type.SetDummy();
  7135. if( !isOptional )
  7136. {
  7137. // Prepend the scope to the name for the error message
  7138. asCString ename;
  7139. if( scope != "" && scope != "::" )
  7140. ename = scope + "::";
  7141. else
  7142. ename = scope;
  7143. ename += name;
  7144. asCString str;
  7145. str.Format(TXT_s_NOT_DECLARED, ename.AddressOf());
  7146. Error(str, errNode);
  7147. // Declare the variable now so that it will not be reported again
  7148. variables->DeclareVariable(name.AddressOf(), asCDataType::CreatePrimitive(ttInt, false), 0x7FFF, true);
  7149. // Mark the variable as initialized so that the user will not be bother by it again
  7150. sVariable *v = variables->GetVariable(name.AddressOf());
  7151. asASSERT(v);
  7152. if( v ) v->isInitialized = true;
  7153. }
  7154. // Return -1 to signal that the variable wasn't found
  7155. return -1;
  7156. }
  7157. return 0;
  7158. }
  7159. int asCCompiler::CompileExpressionValue(asCScriptNode *node, asSExprContext *ctx)
  7160. {
  7161. // Shouldn't receive any byte code
  7162. asASSERT(ctx->bc.GetLastInstr() == -1);
  7163. asCScriptNode *vnode = node->firstChild;
  7164. ctx->exprNode = vnode;
  7165. if( vnode->nodeType == snVariableAccess )
  7166. {
  7167. // Determine the scope resolution of the variable
  7168. asCString scope = builder->GetScopeFromNode(vnode->firstChild, script, &vnode);
  7169. // Determine the name of the variable
  7170. asASSERT(vnode->nodeType == snIdentifier );
  7171. asCString name(&script->code[vnode->tokenPos], vnode->tokenLength);
  7172. return CompileVariableAccess(name, scope, ctx, node);
  7173. }
  7174. else if( vnode->nodeType == snConstant )
  7175. {
  7176. if( vnode->tokenType == ttIntConstant )
  7177. {
  7178. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  7179. asQWORD val = asStringScanUInt64(value.AddressOf(), 10, 0);
  7180. // Do we need 64 bits?
  7181. // If the 31st bit is set we'll treat the value as a signed 64bit number to avoid
  7182. // incorrect warnings about changing signs if the value is assigned to a 64bit variable
  7183. if( val>>31 )
  7184. {
  7185. // Only if the value uses the last bit of a 64bit word do we consider the number unsigned
  7186. if( val>>63 )
  7187. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  7188. else
  7189. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttInt64, true), val);
  7190. }
  7191. else
  7192. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttInt, true), asDWORD(val));
  7193. }
  7194. else if( vnode->tokenType == ttBitsConstant )
  7195. {
  7196. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  7197. // Let the function determine the radix from the prefix 0x = 16, 0d = 10, 0o = 8, or 0b = 2
  7198. // TODO: Check for overflow
  7199. asQWORD val = asStringScanUInt64(value.AddressOf(), 0, 0);
  7200. // Do we need 64 bits?
  7201. if( val>>32 )
  7202. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  7203. else
  7204. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  7205. }
  7206. else if( vnode->tokenType == ttFloatConstant )
  7207. {
  7208. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  7209. // TODO: Check for overflow
  7210. size_t numScanned;
  7211. float v = float(asStringScanDouble(value.AddressOf(), &numScanned));
  7212. ctx->type.SetConstantF(asCDataType::CreatePrimitive(ttFloat, true), v);
  7213. #ifndef AS_USE_DOUBLE_AS_FLOAT
  7214. // Don't check this if we have double as float, because then the whole token would be scanned (i.e. no f suffix)
  7215. asASSERT(numScanned == vnode->tokenLength - 1);
  7216. #endif
  7217. }
  7218. else if( vnode->tokenType == ttDoubleConstant )
  7219. {
  7220. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  7221. // TODO: Check for overflow
  7222. size_t numScanned;
  7223. double v = asStringScanDouble(value.AddressOf(), &numScanned);
  7224. ctx->type.SetConstantD(asCDataType::CreatePrimitive(ttDouble, true), v);
  7225. asASSERT(numScanned == vnode->tokenLength);
  7226. }
  7227. else if( vnode->tokenType == ttTrue ||
  7228. vnode->tokenType == ttFalse )
  7229. {
  7230. #if AS_SIZEOF_BOOL == 1
  7231. ctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  7232. #else
  7233. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  7234. #endif
  7235. }
  7236. else if( vnode->tokenType == ttStringConstant ||
  7237. vnode->tokenType == ttMultilineStringConstant ||
  7238. vnode->tokenType == ttHeredocStringConstant )
  7239. {
  7240. asCString str;
  7241. asCScriptNode *snode = vnode->firstChild;
  7242. if( script->code[snode->tokenPos] == '\'' && engine->ep.useCharacterLiterals )
  7243. {
  7244. // Treat the single quoted string as a single character literal
  7245. str.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  7246. asDWORD val = 0;
  7247. if( str.GetLength() && (unsigned char)str[0] > 127 && engine->ep.scanner == 1 )
  7248. {
  7249. // This is the start of a UTF8 encoded character. We need to decode it
  7250. val = asStringDecodeUTF8(str.AddressOf(), 0);
  7251. if( val == (asDWORD)-1 )
  7252. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  7253. }
  7254. else
  7255. {
  7256. val = ProcessStringConstant(str, snode);
  7257. if( val == (asDWORD)-1 )
  7258. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  7259. }
  7260. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), val);
  7261. }
  7262. else
  7263. {
  7264. // Process the string constants
  7265. while( snode )
  7266. {
  7267. asCString cat;
  7268. if( snode->tokenType == ttStringConstant )
  7269. {
  7270. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  7271. ProcessStringConstant(cat, snode);
  7272. }
  7273. else if( snode->tokenType == ttMultilineStringConstant )
  7274. {
  7275. if( !engine->ep.allowMultilineStrings )
  7276. Error(TXT_MULTILINE_STRINGS_NOT_ALLOWED, snode);
  7277. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  7278. ProcessStringConstant(cat, snode);
  7279. }
  7280. else if( snode->tokenType == ttHeredocStringConstant )
  7281. {
  7282. cat.Assign(&script->code[snode->tokenPos+3], snode->tokenLength-6);
  7283. ProcessHeredocStringConstant(cat, snode);
  7284. }
  7285. str += cat;
  7286. snode = snode->next;
  7287. }
  7288. // Call the string factory function to create a string object
  7289. asCScriptFunction *descr = engine->stringFactory;
  7290. if( descr == 0 )
  7291. {
  7292. // Error
  7293. Error(TXT_STRINGS_NOT_RECOGNIZED, vnode);
  7294. // Give dummy value
  7295. ctx->type.SetDummy();
  7296. return -1;
  7297. }
  7298. else
  7299. {
  7300. // Register the constant string with the engine
  7301. int id = engine->AddConstantString(str.AddressOf(), str.GetLength());
  7302. ctx->bc.InstrWORD(asBC_STR, (asWORD)id);
  7303. bool useVariable = false;
  7304. int stackOffset = 0;
  7305. if( descr->DoesReturnOnStack() )
  7306. {
  7307. useVariable = true;
  7308. stackOffset = AllocateVariable(descr->returnType, true);
  7309. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  7310. }
  7311. PerformFunctionCall(descr->id, ctx, false, 0, 0, useVariable, stackOffset);
  7312. }
  7313. }
  7314. }
  7315. else if( vnode->tokenType == ttNull )
  7316. {
  7317. ctx->bc.Instr(asBC_PshNull);
  7318. ctx->type.SetNullConstant();
  7319. }
  7320. else
  7321. asASSERT(false);
  7322. }
  7323. else if( vnode->nodeType == snFunctionCall )
  7324. {
  7325. // Determine the scope resolution
  7326. asCString scope = builder->GetScopeFromNode(vnode->firstChild, script);
  7327. return CompileFunctionCall(vnode, ctx, 0, false, scope);
  7328. }
  7329. else if( vnode->nodeType == snConstructCall )
  7330. {
  7331. CompileConstructCall(vnode, ctx);
  7332. }
  7333. else if( vnode->nodeType == snAssignment )
  7334. {
  7335. asSExprContext e(engine);
  7336. int r = CompileAssignment(vnode, &e);
  7337. if( r < 0 )
  7338. {
  7339. ctx->type.SetDummy();
  7340. return r;
  7341. }
  7342. MergeExprBytecodeAndType(ctx, &e);
  7343. }
  7344. else if( vnode->nodeType == snCast )
  7345. {
  7346. // Implement the cast operator
  7347. CompileConversion(vnode, ctx);
  7348. }
  7349. else if( vnode->nodeType == snUndefined && vnode->tokenType == ttVoid )
  7350. {
  7351. // This is a void expression
  7352. ctx->type.SetVoidExpression();
  7353. }
  7354. else
  7355. asASSERT(false);
  7356. return 0;
  7357. }
  7358. asUINT asCCompiler::ProcessStringConstant(asCString &cstr, asCScriptNode *node, bool processEscapeSequences)
  7359. {
  7360. int charLiteral = -1;
  7361. // Process escape sequences
  7362. asCArray<char> str((int)cstr.GetLength());
  7363. for( asUINT n = 0; n < cstr.GetLength(); n++ )
  7364. {
  7365. #ifdef AS_DOUBLEBYTE_CHARSET
  7366. // Double-byte charset is only allowed for ASCII and not UTF16 encoded strings
  7367. if( (cstr[n] & 0x80) && engine->ep.scanner == 0 && engine->ep.stringEncoding != 1 )
  7368. {
  7369. // This is the lead character of a double byte character
  7370. // include the trail character without checking it's value.
  7371. str.PushLast(cstr[n]);
  7372. n++;
  7373. str.PushLast(cstr[n]);
  7374. continue;
  7375. }
  7376. #endif
  7377. asUINT val;
  7378. if( processEscapeSequences && cstr[n] == '\\' )
  7379. {
  7380. ++n;
  7381. if( n == cstr.GetLength() )
  7382. {
  7383. if( charLiteral == -1 ) charLiteral = 0;
  7384. return charLiteral;
  7385. }
  7386. // Hexadecimal escape sequences will allow the construction of
  7387. // invalid unicode sequences, but the string should also work as
  7388. // a bytearray so we must support this. The code for working with
  7389. // unicode text must be prepared to handle invalid unicode sequences
  7390. if( cstr[n] == 'x' || cstr[n] == 'X' )
  7391. {
  7392. ++n;
  7393. if( n == cstr.GetLength() ) break;
  7394. val = 0;
  7395. int c = engine->ep.stringEncoding == 1 ? 4 : 2;
  7396. for( ; c > 0 && n < cstr.GetLength(); c--, n++ )
  7397. {
  7398. if( cstr[n] >= '0' && cstr[n] <= '9' )
  7399. val = val*16 + cstr[n] - '0';
  7400. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  7401. val = val*16 + cstr[n] - 'a' + 10;
  7402. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  7403. val = val*16 + cstr[n] - 'A' + 10;
  7404. else
  7405. break;
  7406. }
  7407. // Rewind one, since the loop will increment it again
  7408. n--;
  7409. // Hexadecimal escape sequences produce exact value, even if it is not proper unicode chars
  7410. if( engine->ep.stringEncoding == 0 )
  7411. {
  7412. str.PushLast((asBYTE)val);
  7413. }
  7414. else
  7415. {
  7416. #ifndef AS_BIG_ENDIAN
  7417. str.PushLast((asBYTE)val);
  7418. str.PushLast((asBYTE)(val>>8));
  7419. #else
  7420. str.PushLast((asBYTE)(val>>8));
  7421. str.PushLast((asBYTE)val);
  7422. #endif
  7423. }
  7424. if( charLiteral == -1 ) charLiteral = val;
  7425. continue;
  7426. }
  7427. else if( cstr[n] == 'u' || cstr[n] == 'U' )
  7428. {
  7429. // \u expects 4 hex digits
  7430. // \U expects 8 hex digits
  7431. bool expect2 = cstr[n] == 'u';
  7432. int c = expect2 ? 4 : 8;
  7433. val = 0;
  7434. for( ; c > 0; c-- )
  7435. {
  7436. ++n;
  7437. if( n == cstr.GetLength() ) break;
  7438. if( cstr[n] >= '0' && cstr[n] <= '9' )
  7439. val = val*16 + cstr[n] - '0';
  7440. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  7441. val = val*16 + cstr[n] - 'a' + 10;
  7442. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  7443. val = val*16 + cstr[n] - 'A' + 10;
  7444. else
  7445. break;
  7446. }
  7447. if( c != 0 )
  7448. {
  7449. // Give warning about invalid code point
  7450. // TODO: Need code position for warning
  7451. asCString msg;
  7452. msg.Format(TXT_INVALID_UNICODE_FORMAT_EXPECTED_d, expect2 ? 4 : 8);
  7453. Warning(msg, node);
  7454. continue;
  7455. }
  7456. }
  7457. else
  7458. {
  7459. if( cstr[n] == '"' )
  7460. val = '"';
  7461. else if( cstr[n] == '\'' )
  7462. val = '\'';
  7463. else if( cstr[n] == 'n' )
  7464. val = '\n';
  7465. else if( cstr[n] == 'r' )
  7466. val = '\r';
  7467. else if( cstr[n] == 't' )
  7468. val = '\t';
  7469. else if( cstr[n] == '0' )
  7470. val = '\0';
  7471. else if( cstr[n] == '\\' )
  7472. val = '\\';
  7473. else
  7474. {
  7475. // Invalid escape sequence
  7476. Warning(TXT_INVALID_ESCAPE_SEQUENCE, node);
  7477. continue;
  7478. }
  7479. }
  7480. }
  7481. else
  7482. {
  7483. if( engine->ep.scanner == 1 && (cstr[n] & 0x80) )
  7484. {
  7485. unsigned int len;
  7486. val = asStringDecodeUTF8(&cstr[n], &len);
  7487. if( val == 0xFFFFFFFF )
  7488. {
  7489. // Incorrect UTF8 encoding. Use only the first byte
  7490. // TODO: Need code position for warning
  7491. Warning(TXT_INVALID_UNICODE_SEQUENCE_IN_SRC, node);
  7492. val = (unsigned char)cstr[n];
  7493. }
  7494. else
  7495. n += len-1;
  7496. }
  7497. else
  7498. val = (unsigned char)cstr[n];
  7499. }
  7500. // Add the character to the final string
  7501. char encodedValue[5];
  7502. int len;
  7503. if( engine->ep.scanner == 1 && engine->ep.stringEncoding == 0 )
  7504. {
  7505. // Convert to UTF8 encoded
  7506. len = asStringEncodeUTF8(val, encodedValue);
  7507. }
  7508. else if( engine->ep.stringEncoding == 1 )
  7509. {
  7510. // Convert to 16bit wide character string (even if the script is scanned as ASCII)
  7511. len = asStringEncodeUTF16(val, encodedValue);
  7512. }
  7513. else
  7514. {
  7515. // Do not convert ASCII characters
  7516. encodedValue[0] = (asBYTE)val;
  7517. len = 1;
  7518. }
  7519. if( len < 0 )
  7520. {
  7521. // Give warning about invalid code point
  7522. // TODO: Need code position for warning
  7523. Warning(TXT_INVALID_UNICODE_VALUE, node);
  7524. }
  7525. else
  7526. {
  7527. // Add the encoded value to the final string
  7528. str.Concatenate(encodedValue, len);
  7529. if( charLiteral == -1 ) charLiteral = val;
  7530. }
  7531. }
  7532. cstr.Assign(str.AddressOf(), str.GetLength());
  7533. return charLiteral;
  7534. }
  7535. void asCCompiler::ProcessHeredocStringConstant(asCString &str, asCScriptNode *node)
  7536. {
  7537. // Remove first line if it only contains whitespace
  7538. int start;
  7539. for( start = 0; start < (int)str.GetLength(); start++ )
  7540. {
  7541. if( str[start] == '\n' )
  7542. {
  7543. // Remove the linebreak as well
  7544. start++;
  7545. break;
  7546. }
  7547. if( str[start] != ' ' &&
  7548. str[start] != '\t' &&
  7549. str[start] != '\r' )
  7550. {
  7551. // Don't remove anything
  7552. start = 0;
  7553. break;
  7554. }
  7555. }
  7556. // Remove the line after the last line break if it only contains whitespaces
  7557. int end;
  7558. for( end = (int)str.GetLength() - 1; end >= 0; end-- )
  7559. {
  7560. if( str[end] == '\n' )
  7561. {
  7562. // Don't remove the last line break
  7563. end++;
  7564. break;
  7565. }
  7566. if( str[end] != ' ' &&
  7567. str[end] != '\t' &&
  7568. str[end] != '\r' )
  7569. {
  7570. // Don't remove anything
  7571. end = (int)str.GetLength();
  7572. break;
  7573. }
  7574. }
  7575. if( end < 0 ) end = 0;
  7576. asCString tmp;
  7577. if( end > start )
  7578. tmp.Assign(&str[start], end-start);
  7579. ProcessStringConstant(tmp, node, false);
  7580. str = tmp;
  7581. }
  7582. void asCCompiler::CompileConversion(asCScriptNode *node, asSExprContext *ctx)
  7583. {
  7584. asSExprContext expr(engine);
  7585. asCDataType to;
  7586. bool anyErrors = false;
  7587. EImplicitConv convType;
  7588. if( node->nodeType == snConstructCall )
  7589. {
  7590. convType = asIC_EXPLICIT_VAL_CAST;
  7591. // Verify that there is only one argument
  7592. if( node->lastChild->firstChild == 0 ||
  7593. node->lastChild->firstChild != node->lastChild->lastChild )
  7594. {
  7595. Error(TXT_ONLY_ONE_ARGUMENT_IN_CAST, node->lastChild);
  7596. expr.type.SetDummy();
  7597. anyErrors = true;
  7598. }
  7599. else
  7600. {
  7601. // Compile the expression
  7602. int r = CompileAssignment(node->lastChild->firstChild, &expr);
  7603. if( r < 0 )
  7604. anyErrors = true;
  7605. }
  7606. // Determine the requested type
  7607. to = builder->CreateDataTypeFromNode(node->firstChild, script, outFunc->nameSpace);
  7608. to.MakeReadOnly(true); // Default to const
  7609. asASSERT(to.IsPrimitive());
  7610. }
  7611. else
  7612. {
  7613. convType = asIC_EXPLICIT_REF_CAST;
  7614. // Compile the expression
  7615. int r = CompileAssignment(node->lastChild, &expr);
  7616. if( r < 0 )
  7617. anyErrors = true;
  7618. // Determine the requested type
  7619. to = builder->CreateDataTypeFromNode(node->firstChild, script, outFunc->nameSpace);
  7620. to = builder->ModifyDataTypeFromNode(to, node->firstChild->next, script, 0, 0);
  7621. // If the type support object handles, then use it
  7622. if( to.SupportHandles() )
  7623. {
  7624. to.MakeHandle(true);
  7625. }
  7626. else if( !to.IsObjectHandle() )
  7627. {
  7628. // The cast<type> operator can only be used for reference casts
  7629. Error(TXT_ILLEGAL_TARGET_TYPE_FOR_REF_CAST, node->firstChild);
  7630. anyErrors = true;
  7631. }
  7632. }
  7633. // Do not allow casting to non shared type if we're compiling a shared method
  7634. if( outFunc->IsShared() &&
  7635. to.GetObjectType() && !to.GetObjectType()->IsShared() )
  7636. {
  7637. asCString msg;
  7638. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, to.GetObjectType()->name.AddressOf());
  7639. Error(msg, node);
  7640. anyErrors = true;
  7641. }
  7642. if( anyErrors )
  7643. {
  7644. // Assume that the error can be fixed and allow the compilation to continue
  7645. ctx->type.SetConstantDW(to, 0);
  7646. return;
  7647. }
  7648. ProcessPropertyGetAccessor(&expr, node);
  7649. // Don't allow any operators on expressions that take address of class method
  7650. if( expr.IsClassMethod() )
  7651. {
  7652. Error(TXT_INVALID_OP_ON_METHOD, node);
  7653. return;
  7654. }
  7655. // We don't want a reference for conversion casts
  7656. if( convType == asIC_EXPLICIT_VAL_CAST && expr.type.dataType.IsReference() )
  7657. {
  7658. if( expr.type.dataType.IsObject() )
  7659. Dereference(&expr, true);
  7660. else
  7661. ConvertToVariable(&expr);
  7662. }
  7663. ImplicitConversion(&expr, to, node, convType);
  7664. IsVariableInitialized(&expr.type, node);
  7665. // If no type conversion is really tried ignore it
  7666. if( to == expr.type.dataType )
  7667. {
  7668. // This will keep information about constant type
  7669. MergeExprBytecode(ctx, &expr);
  7670. ctx->type = expr.type;
  7671. return;
  7672. }
  7673. if( to.IsEqualExceptRefAndConst(expr.type.dataType) && to.IsPrimitive() )
  7674. {
  7675. MergeExprBytecode(ctx, &expr);
  7676. ctx->type = expr.type;
  7677. ctx->type.dataType.MakeReadOnly(true);
  7678. return;
  7679. }
  7680. // The implicit conversion already does most of the conversions permitted,
  7681. // here we'll only treat those conversions that require an explicit cast.
  7682. bool conversionOK = false;
  7683. if( !expr.type.isConstant && expr.type.dataType != asCDataType::CreatePrimitive(ttVoid, false) )
  7684. {
  7685. if( !expr.type.dataType.IsObject() )
  7686. ConvertToTempVariable(&expr);
  7687. if( to.IsObjectHandle() &&
  7688. expr.type.dataType.IsObjectHandle() &&
  7689. !(!to.IsHandleToConst() && expr.type.dataType.IsHandleToConst()) )
  7690. {
  7691. conversionOK = CompileRefCast(&expr, to, true, node);
  7692. MergeExprBytecode(ctx, &expr);
  7693. ctx->type = expr.type;
  7694. }
  7695. }
  7696. if( conversionOK )
  7697. return;
  7698. // Conversion not available
  7699. ctx->type.SetDummy();
  7700. asCString strTo, strFrom;
  7701. strTo = to.Format();
  7702. strFrom = expr.type.dataType.Format();
  7703. asCString msg;
  7704. msg.Format(TXT_NO_CONVERSION_s_TO_s, strFrom.AddressOf(), strTo.AddressOf());
  7705. Error(msg, node);
  7706. }
  7707. void asCCompiler::AfterFunctionCall(int funcID, asCArray<asSExprContext*> &args, asSExprContext *ctx, bool deferAll)
  7708. {
  7709. // deferAll is set to true if for example the function returns a reference, since in
  7710. // this case the function might be returning a reference to one of the arguments.
  7711. asCScriptFunction *descr = builder->GetFunctionDescription(funcID);
  7712. // Parameters that are sent by reference should be assigned
  7713. // to the evaluated expression if it is an lvalue
  7714. // Evaluate the arguments from last to first
  7715. int n = (int)descr->parameterTypes.GetLength() - 1;
  7716. for( ; n >= 0; n-- )
  7717. {
  7718. // All &out arguments must be deferred
  7719. // If deferAll is set all objects passed by reference or handle must be deferred
  7720. if( (descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] & asTM_OUTREF)) ||
  7721. (descr->parameterTypes[n].IsObject() && deferAll && (descr->parameterTypes[n].IsReference() || descr->parameterTypes[n].IsObjectHandle())) )
  7722. {
  7723. asASSERT( !(descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] == asTM_OUTREF)) || args[n]->origExpr );
  7724. // For &inout, only store the argument if it is for a temporary variable
  7725. if( engine->ep.allowUnsafeReferences ||
  7726. descr->inOutFlags[n] != asTM_INOUTREF || args[n]->type.isTemporary )
  7727. {
  7728. // Store the argument for later processing
  7729. asSDeferredParam outParam;
  7730. outParam.argNode = args[n]->exprNode;
  7731. outParam.argType = args[n]->type;
  7732. outParam.argInOutFlags = descr->inOutFlags[n];
  7733. outParam.origExpr = args[n]->origExpr;
  7734. ctx->deferredParams.PushLast(outParam);
  7735. }
  7736. }
  7737. else
  7738. {
  7739. // Release the temporary variable now
  7740. ReleaseTemporaryVariable(args[n]->type, &ctx->bc);
  7741. }
  7742. // Move the argument's deferred expressions over to the final expression
  7743. for( asUINT m = 0; m < args[n]->deferredParams.GetLength(); m++ )
  7744. {
  7745. ctx->deferredParams.PushLast(args[n]->deferredParams[m]);
  7746. args[n]->deferredParams[m].origExpr = 0;
  7747. }
  7748. args[n]->deferredParams.SetLength(0);
  7749. }
  7750. }
  7751. void asCCompiler::ProcessDeferredParams(asSExprContext *ctx)
  7752. {
  7753. if( isProcessingDeferredParams ) return;
  7754. isProcessingDeferredParams = true;
  7755. for( asUINT n = 0; n < ctx->deferredParams.GetLength(); n++ )
  7756. {
  7757. asSDeferredParam outParam = ctx->deferredParams[n];
  7758. if( outParam.argInOutFlags < asTM_OUTREF ) // &in, or not reference
  7759. {
  7760. // Just release the variable
  7761. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  7762. }
  7763. else if( outParam.argInOutFlags == asTM_OUTREF )
  7764. {
  7765. asSExprContext *expr = outParam.origExpr;
  7766. outParam.origExpr = 0;
  7767. if( outParam.argType.dataType.IsObjectHandle() )
  7768. {
  7769. // Implicitly convert the value to a handle
  7770. if( expr->type.dataType.IsObjectHandle() )
  7771. expr->type.isExplicitHandle = true;
  7772. }
  7773. // Verify that the expression result in a lvalue, or a property accessor
  7774. if( IsLValue(expr->type) || expr->property_get || expr->property_set )
  7775. {
  7776. asSExprContext rctx(engine);
  7777. rctx.type = outParam.argType;
  7778. if( rctx.type.dataType.IsPrimitive() )
  7779. rctx.type.dataType.MakeReference(false);
  7780. else
  7781. {
  7782. rctx.bc.InstrSHORT(asBC_PSF, outParam.argType.stackOffset);
  7783. rctx.type.dataType.MakeReference(IsVariableOnHeap(outParam.argType.stackOffset));
  7784. if( expr->type.isExplicitHandle )
  7785. rctx.type.isExplicitHandle = true;
  7786. }
  7787. asSExprContext o(engine);
  7788. DoAssignment(&o, expr, &rctx, outParam.argNode, outParam.argNode, ttAssignment, outParam.argNode);
  7789. if( !o.type.dataType.IsPrimitive() ) o.bc.Instr(asBC_PopPtr);
  7790. // The assignment may itself have resulted in a new temporary variable, e.g. if
  7791. // the opAssign returns a non-reference. We must release this temporary variable
  7792. // since it won't be used
  7793. ReleaseTemporaryVariable(o.type, &o.bc);
  7794. MergeExprBytecode(ctx, &o);
  7795. }
  7796. else
  7797. {
  7798. // We must still evaluate the expression
  7799. MergeExprBytecode(ctx, expr);
  7800. if( !expr->type.IsVoidExpression() && (!expr->type.isConstant || expr->type.IsNullConstant()) )
  7801. ctx->bc.Instr(asBC_PopPtr);
  7802. // Give a warning, except if the argument is void, null or 0 which indicate the argument is really to be ignored
  7803. if( !expr->type.IsVoidExpression() && !expr->type.IsNullConstant() && !(expr->type.isConstant && expr->type.qwordValue == 0) )
  7804. Warning(TXT_ARG_NOT_LVALUE, outParam.argNode);
  7805. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  7806. }
  7807. ReleaseTemporaryVariable(expr->type, &ctx->bc);
  7808. // Delete the original expression context
  7809. asDELETE(expr,asSExprContext);
  7810. }
  7811. else // &inout
  7812. {
  7813. if( outParam.argType.isTemporary )
  7814. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  7815. else if( !outParam.argType.isVariable )
  7816. {
  7817. if( outParam.argType.dataType.IsObject() &&
  7818. ((outParam.argType.dataType.GetBehaviour()->addref &&
  7819. outParam.argType.dataType.GetBehaviour()->release) ||
  7820. (outParam.argType.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) )
  7821. {
  7822. // Release the object handle that was taken to guarantee the reference
  7823. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  7824. }
  7825. }
  7826. }
  7827. }
  7828. ctx->deferredParams.SetLength(0);
  7829. isProcessingDeferredParams = false;
  7830. }
  7831. void asCCompiler::CompileConstructCall(asCScriptNode *node, asSExprContext *ctx)
  7832. {
  7833. // The first node is a datatype node
  7834. asCString name;
  7835. asCTypeInfo tempObj;
  7836. bool onHeap = true;
  7837. asCArray<int> funcs;
  7838. // It is possible that the name is really a constructor
  7839. asCDataType dt;
  7840. dt = builder->CreateDataTypeFromNode(node->firstChild, script, outFunc->nameSpace);
  7841. if( dt.IsPrimitive() )
  7842. {
  7843. // This is a cast to a primitive type
  7844. CompileConversion(node, ctx);
  7845. return;
  7846. }
  7847. // Do not allow constructing non-shared types in shared functions
  7848. if( outFunc->IsShared() &&
  7849. dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  7850. {
  7851. asCString msg;
  7852. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  7853. Error(msg, node);
  7854. }
  7855. // Compile the arguments
  7856. asCArray<asSExprContext *> args;
  7857. asCArray<asSNamedArgument> namedArgs;
  7858. asCArray<asCTypeInfo> temporaryVariables;
  7859. if( CompileArgumentList(node->lastChild, args, namedArgs) >= 0 )
  7860. {
  7861. // Check for a value cast behaviour
  7862. if( args.GetLength() == 1 && args[0]->type.dataType.GetObjectType() )
  7863. {
  7864. asSExprContext conv(engine);
  7865. conv.type = args[0]->type;
  7866. asUINT cost = ImplicitConversion(&conv, dt, node->lastChild, asIC_EXPLICIT_VAL_CAST, false);
  7867. // Don't use this if the cost is 0 because it would mean that nothing
  7868. // is done and the scipt wants a new value to be constructed
  7869. if( conv.type.dataType.IsEqualExceptRef(dt) && cost > 0 )
  7870. {
  7871. ImplicitConversion(args[0], dt, node->lastChild, asIC_EXPLICIT_VAL_CAST);
  7872. ctx->bc.AddCode(&args[0]->bc);
  7873. ctx->type = args[0]->type;
  7874. asDELETE(args[0],asSExprContext);
  7875. return;
  7876. }
  7877. }
  7878. // Check for possible constructor/factory
  7879. name = dt.Format();
  7880. asSTypeBehaviour *beh = dt.GetBehaviour();
  7881. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  7882. {
  7883. funcs = beh->constructors;
  7884. // Value types and script types are allocated through the constructor
  7885. tempObj.dataType = dt;
  7886. tempObj.stackOffset = (short)AllocateVariable(dt, true);
  7887. tempObj.dataType.MakeReference(true);
  7888. tempObj.isTemporary = true;
  7889. tempObj.isVariable = true;
  7890. onHeap = IsVariableOnHeap(tempObj.stackOffset);
  7891. // Push the address of the object on the stack
  7892. if( onHeap )
  7893. ctx->bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  7894. }
  7895. else
  7896. funcs = beh->factories;
  7897. // Special case: Allow calling func(void) with a void expression.
  7898. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  7899. {
  7900. // Evaluate the expression before the function call
  7901. MergeExprBytecode(ctx, args[0]);
  7902. asDELETE(args[0],asSExprContext);
  7903. args.SetLength(0);
  7904. }
  7905. // Special case: If this is an object constructor and there are no arguments use the default constructor.
  7906. // If none has been registered, just allocate the variable and push it on the stack.
  7907. if( args.GetLength() == 0 )
  7908. {
  7909. asSTypeBehaviour *beh = tempObj.dataType.GetBehaviour();
  7910. if( beh && beh->construct == 0 && !(dt.GetObjectType()->flags & asOBJ_REF) )
  7911. {
  7912. // Call the default constructor
  7913. ctx->type = tempObj;
  7914. if( onHeap )
  7915. {
  7916. asASSERT(ctx->bc.GetLastInstr() == asBC_VAR);
  7917. ctx->bc.RemoveLastInstr();
  7918. }
  7919. CallDefaultConstructor(tempObj.dataType, tempObj.stackOffset, IsVariableOnHeap(tempObj.stackOffset), &ctx->bc, node);
  7920. // Push the reference on the stack
  7921. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  7922. return;
  7923. }
  7924. }
  7925. // Special case: If this is a construction of a delegate and the expression names an object method
  7926. if( dt.GetFuncDef() && args.GetLength() == 1 && args[0]->methodName != "" )
  7927. {
  7928. // TODO: delegate: It is possible that the argument returns a function pointer already, in which
  7929. // case no object delegate will be created, but instead a delegate for a function pointer
  7930. // In theory a simple cast would be good in this case, but this is a construct call so it
  7931. // is expected that a new object is created.
  7932. dt.MakeHandle(true);
  7933. ctx->type.Set(dt);
  7934. // The delegate must be able to hold on to a reference to the object
  7935. if( !args[0]->type.dataType.SupportHandles() )
  7936. Error(TXT_CANNOT_CREATE_DELEGATE_FOR_NOREF_TYPES, node);
  7937. else
  7938. {
  7939. // Filter the available object methods to find the one that matches the func def
  7940. asCObjectType *type = args[0]->type.dataType.GetObjectType();
  7941. asCScriptFunction *bestMethod = 0;
  7942. for( asUINT n = 0; n < type->methods.GetLength(); n++ )
  7943. {
  7944. asCScriptFunction *func = engine->scriptFunctions[type->methods[n]];
  7945. if( func->name != args[0]->methodName )
  7946. continue;
  7947. // If the expression is for a const object, then only const methods should be accepted
  7948. if( args[0]->type.dataType.IsReadOnly() && !func->IsReadOnly() )
  7949. continue;
  7950. if( func->IsSignatureExceptNameAndObjectTypeEqual(dt.GetFuncDef()) )
  7951. {
  7952. bestMethod = func;
  7953. // If the expression is non-const the non-const overloaded method has priority
  7954. if( args[0]->type.dataType.IsReadOnly() == func->IsReadOnly() )
  7955. break;
  7956. }
  7957. }
  7958. if( bestMethod )
  7959. {
  7960. // The object pointer is already on the stack
  7961. MergeExprBytecode(ctx, args[0]);
  7962. // Push the function pointer as an additional argument
  7963. ctx->bc.InstrPTR(asBC_FuncPtr, bestMethod);
  7964. // Call the factory function for the delegate
  7965. asCArray<int> funcs;
  7966. builder->GetFunctionDescriptions(DELEGATE_FACTORY, funcs, engine->nameSpaces[0]);
  7967. asASSERT( funcs.GetLength() == 1 );
  7968. ctx->bc.Call(asBC_CALLSYS , funcs[0], 2*AS_PTR_SIZE);
  7969. // Store the returned delegate in a temporary variable
  7970. int returnOffset = AllocateVariable(dt, true, false);
  7971. dt.MakeReference(true);
  7972. ctx->type.SetVariable(dt, returnOffset, true);
  7973. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  7974. // Push a reference to the temporary variable on the stack
  7975. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  7976. }
  7977. else
  7978. {
  7979. asCString msg;
  7980. msg.Format(TXT_NO_MATCHING_SIGNATURES_TO_s, dt.GetFuncDef()->GetDeclaration());
  7981. Error(msg.AddressOf(), node);
  7982. }
  7983. }
  7984. // Clean-up arg
  7985. asDELETE(args[0],asSExprContext);
  7986. return;
  7987. }
  7988. MatchFunctions(funcs, args, node, name.AddressOf(), &namedArgs, 0, false);
  7989. if( funcs.GetLength() != 1 )
  7990. {
  7991. // The error was reported by MatchFunctions()
  7992. // Dummy value
  7993. ctx->type.SetDummy();
  7994. }
  7995. else
  7996. {
  7997. // TODO: Clean up: Merge this with MakeFunctionCall
  7998. // Add the default values for arguments not explicitly supplied
  7999. int r = CompileDefaultAndNamedArgs(node, args, funcs[0], dt.GetObjectType(), &namedArgs);
  8000. if( r == asSUCCESS )
  8001. {
  8002. asCByteCode objBC(engine);
  8003. PrepareFunctionCall(funcs[0], &ctx->bc, args);
  8004. MoveArgsToStack(funcs[0], &ctx->bc, args, false);
  8005. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  8006. {
  8007. // If the object is allocated on the stack, then call the constructor as a normal function
  8008. if( onHeap )
  8009. {
  8010. int offset = 0;
  8011. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  8012. for( asUINT n = 0; n < args.GetLength(); n++ )
  8013. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  8014. ctx->bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  8015. }
  8016. else
  8017. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  8018. PerformFunctionCall(funcs[0], ctx, onHeap, &args, tempObj.dataType.GetObjectType());
  8019. // Add tag that the object has been initialized
  8020. ctx->bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  8021. // The constructor doesn't return anything,
  8022. // so we have to manually inform the type of
  8023. // the return value
  8024. ctx->type = tempObj;
  8025. if( !onHeap )
  8026. ctx->type.dataType.MakeReference(false);
  8027. // Push the address of the object on the stack again
  8028. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  8029. }
  8030. else
  8031. {
  8032. // Call the factory to create the reference type
  8033. PerformFunctionCall(funcs[0], ctx, false, &args);
  8034. }
  8035. }
  8036. }
  8037. }
  8038. else
  8039. {
  8040. // Failed to compile the argument list, set the result to the dummy type
  8041. ctx->type.SetDummy();
  8042. }
  8043. // Cleanup
  8044. for( asUINT n = 0; n < args.GetLength(); n++ )
  8045. if( args[n] )
  8046. {
  8047. asDELETE(args[n],asSExprContext);
  8048. }
  8049. for( asUINT n = 0; n < namedArgs.GetLength(); n++ )
  8050. if( namedArgs[n].ctx )
  8051. {
  8052. asDELETE(namedArgs[n].ctx,asSExprContext);
  8053. }
  8054. }
  8055. int asCCompiler::CompileFunctionCall(asCScriptNode *node, asSExprContext *ctx, asCObjectType *objectType, bool objIsConst, const asCString &scope)
  8056. {
  8057. asCTypeInfo tempObj;
  8058. asCArray<int> funcs;
  8059. int localVar = -1;
  8060. bool initializeMembers = false;
  8061. asSExprContext funcExpr(engine);
  8062. asCScriptNode *nm = node->lastChild->prev;
  8063. asCString name(&script->code[nm->tokenPos], nm->tokenLength);
  8064. // First check for a local variable as it would take precedence
  8065. // Must not allow function names, nor global variables to be returned in this instance
  8066. // If objectType is set then this is a post op expression and we shouldn't look for local variables
  8067. if( objectType == 0 )
  8068. {
  8069. localVar = CompileVariableAccess(name, scope, &funcExpr, node, true, true, true);
  8070. if( localVar >= 0 &&
  8071. !(funcExpr.type.dataType.GetFuncDef() || funcExpr.type.dataType.IsObject()) &&
  8072. funcExpr.methodName == "" )
  8073. {
  8074. // The variable is not a function or object with opCall
  8075. asCString msg;
  8076. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  8077. Error(msg, node);
  8078. return -1;
  8079. }
  8080. // If the name matches a method name, then reset the indicator that nothing was found
  8081. if( funcExpr.methodName != "" )
  8082. localVar = -1;
  8083. }
  8084. if( localVar < 0 )
  8085. {
  8086. // If this is an expression post op, or if a class method is
  8087. // being compiled, then we should look for matching class methods
  8088. if( objectType || (outFunc && outFunc->objectType && scope != "::") )
  8089. {
  8090. // If we're compiling a constructor and the name of the function is super then
  8091. // the constructor of the base class is being called.
  8092. // super cannot be prefixed with a scope operator
  8093. if( scope == "" && m_isConstructor && name == SUPER_TOKEN )
  8094. {
  8095. // If the class is not derived from anyone else, calling super should give an error
  8096. if( outFunc && outFunc->objectType->derivedFrom )
  8097. funcs = outFunc->objectType->derivedFrom->beh.constructors;
  8098. // Must not allow calling base class' constructor multiple times
  8099. if( continueLabels.GetLength() > 0 )
  8100. {
  8101. // If a continue label is set we are in a loop
  8102. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_LOOPS, node);
  8103. }
  8104. else if( breakLabels.GetLength() > 0 )
  8105. {
  8106. // TODO: inheritance: Should eventually allow constructors in switch statements
  8107. // If a break label is set we are either in a loop or a switch statements
  8108. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_SWITCH, node);
  8109. }
  8110. else if( m_isConstructorCalled )
  8111. {
  8112. Error(TXT_CANNOT_CALL_CONSTRUCTOR_TWICE, node);
  8113. }
  8114. m_isConstructorCalled = true;
  8115. // We need to initialize the class members, but only after all the deferred arguments have been completed
  8116. initializeMembers = true;
  8117. }
  8118. else
  8119. {
  8120. // The scope is can be used to specify the base class
  8121. builder->GetObjectMethodDescriptions(name.AddressOf(), objectType ? objectType : outFunc->objectType, funcs, objIsConst, scope);
  8122. }
  8123. // It is still possible that there is a class member of a function type or a type with opCall methods
  8124. if( funcs.GetLength() == 0 )
  8125. {
  8126. int r = CompileVariableAccess(name, scope, &funcExpr, node, true, true, true, objectType);
  8127. if( r >= 0 &&
  8128. !(funcExpr.type.dataType.GetFuncDef() || funcExpr.type.dataType.IsObject()) &&
  8129. funcExpr.methodName == "" )
  8130. {
  8131. // The variable is not a function
  8132. asCString msg;
  8133. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  8134. Error(msg, node);
  8135. return -1;
  8136. }
  8137. // If the name is an access property, make sure the original value isn't
  8138. // dereferenced when calling the access property as part a dot post operator
  8139. if( objectType && (funcExpr.property_get || funcExpr.property_set) && !ctx->type.dataType.IsReference() )
  8140. funcExpr.property_ref = false;
  8141. }
  8142. // If a class method is being called implicitly, then add the this pointer for the call
  8143. if( funcs.GetLength() && !objectType )
  8144. {
  8145. objectType = outFunc->objectType;
  8146. asCDataType dt = asCDataType::CreateObject(objectType, false);
  8147. // The object pointer is located at stack position 0
  8148. ctx->bc.InstrSHORT(asBC_PSF, 0);
  8149. ctx->type.SetVariable(dt, 0, false);
  8150. ctx->type.dataType.MakeReference(true);
  8151. Dereference(ctx, true);
  8152. }
  8153. }
  8154. // If it is not a class method or member function pointer,
  8155. // then look for global functions or global function pointers,
  8156. // unless this is an expression post op, incase only member
  8157. // functions are expected
  8158. if( objectType == 0 && funcs.GetLength() == 0 && (funcExpr.type.dataType.GetFuncDef() == 0 || funcExpr.type.dataType.IsObject()) )
  8159. {
  8160. // The scope is used to define the namespace
  8161. asSNameSpace *ns = DetermineNameSpace(scope);
  8162. if( ns )
  8163. {
  8164. // Search recursively in parent namespaces
  8165. while( ns && funcs.GetLength() == 0 && funcExpr.type.dataType.GetFuncDef() == 0 )
  8166. {
  8167. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  8168. if( funcs.GetLength() == 0 )
  8169. {
  8170. int r = CompileVariableAccess(name, scope, &funcExpr, node, true, true);
  8171. if( r >= 0 &&
  8172. !(funcExpr.type.dataType.GetFuncDef() || funcExpr.type.dataType.IsObject()) &&
  8173. funcExpr.methodName == "" )
  8174. {
  8175. // The variable is not a function
  8176. asCString msg;
  8177. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  8178. Error(msg, node);
  8179. return -1;
  8180. }
  8181. }
  8182. ns = builder->GetParentNameSpace(ns);
  8183. }
  8184. }
  8185. else
  8186. {
  8187. asCString msg;
  8188. msg.Format(TXT_NAMESPACE_s_DOESNT_EXIST, scope.AddressOf());
  8189. Error(msg, node);
  8190. return -1;
  8191. }
  8192. }
  8193. }
  8194. if( funcs.GetLength() == 0 )
  8195. {
  8196. if( funcExpr.type.dataType.GetFuncDef() )
  8197. {
  8198. funcs.PushLast(funcExpr.type.dataType.GetFuncDef()->id);
  8199. }
  8200. else if( funcExpr.type.dataType.IsObject() )
  8201. {
  8202. // Keep information about temporary variables as deferred expression so it can be properly cleaned up after the call
  8203. if( ctx->type.isTemporary )
  8204. {
  8205. asASSERT( objectType );
  8206. asSDeferredParam deferred;
  8207. deferred.origExpr = 0;
  8208. deferred.argInOutFlags = asTM_INREF;
  8209. deferred.argNode = 0;
  8210. deferred.argType.SetVariable(ctx->type.dataType, ctx->type.stackOffset, true);
  8211. ctx->deferredParams.PushLast(deferred);
  8212. }
  8213. if( funcExpr.property_get == 0 )
  8214. Dereference(ctx, true);
  8215. // Add the bytecode for accessing the object on which opCall will be called
  8216. MergeExprBytecodeAndType(ctx, &funcExpr);
  8217. ProcessPropertyGetAccessor(ctx, node);
  8218. Dereference(ctx, true);
  8219. objectType = funcExpr.type.dataType.GetObjectType();
  8220. // Get the opCall methods from the object type
  8221. if( funcExpr.type.dataType.IsObjectHandle() )
  8222. objIsConst = funcExpr.type.dataType.IsHandleToConst();
  8223. else
  8224. objIsConst = funcExpr.type.dataType.IsReadOnly();
  8225. builder->GetObjectMethodDescriptions("opCall", funcExpr.type.dataType.GetObjectType(), funcs, objIsConst);
  8226. }
  8227. }
  8228. // Compile the arguments
  8229. asCArray<asSExprContext *> args;
  8230. asCArray<asSNamedArgument> namedArgs;
  8231. bool isOK = true;
  8232. if( CompileArgumentList(node->lastChild, args, namedArgs) >= 0 )
  8233. {
  8234. // Special case: Allow calling func(void) with an expression that evaluates to no datatype, but isn't exactly 'void'
  8235. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) && !args[0]->type.IsVoidExpression() )
  8236. {
  8237. // Evaluate the expression before the function call
  8238. MergeExprBytecode(ctx, args[0]);
  8239. asDELETE(args[0],asSExprContext);
  8240. args.SetLength(0);
  8241. }
  8242. MatchFunctions(funcs, args, node, name.AddressOf(), &namedArgs, objectType, objIsConst, false, true, scope);
  8243. if( funcs.GetLength() != 1 )
  8244. {
  8245. // The error was reported by MatchFunctions()
  8246. // Dummy value
  8247. ctx->type.SetDummy();
  8248. isOK = false;
  8249. }
  8250. else
  8251. {
  8252. // Add the default values for arguments not explicitly supplied
  8253. int r = CompileDefaultAndNamedArgs(node, args, funcs[0], objectType, &namedArgs);
  8254. // TODO: funcdef: Do we have to make sure the handle is stored in a temporary variable, or
  8255. // is it enough to make sure it is in a local variable?
  8256. // For function pointer we must guarantee that the function is safe, i.e.
  8257. // by first storing the function pointer in a local variable (if it isn't already in one)
  8258. if( r == asSUCCESS )
  8259. {
  8260. asCScriptFunction *func = builder->GetFunctionDescription(funcs[0]);
  8261. if( func->funcType == asFUNC_FUNCDEF )
  8262. {
  8263. if( objectType && funcExpr.property_get <= 0 )
  8264. {
  8265. Dereference(ctx, true); // Dereference the object pointer to access the member
  8266. // The actual function should be called as if a global function
  8267. objectType = 0;
  8268. }
  8269. if( funcExpr.property_get > 0 )
  8270. {
  8271. ProcessPropertyGetAccessor(&funcExpr, node);
  8272. Dereference(&funcExpr, true);
  8273. }
  8274. else
  8275. {
  8276. Dereference(&funcExpr, true);
  8277. ConvertToVariable(&funcExpr);
  8278. }
  8279. // The function call will be made directly from the local variable so the function pointer shouldn't be on the stack
  8280. funcExpr.bc.Instr(asBC_PopPtr);
  8281. asCTypeInfo tmp = ctx->type;
  8282. MergeExprBytecodeAndType(ctx, &funcExpr);
  8283. ReleaseTemporaryVariable(tmp, &ctx->bc);
  8284. }
  8285. MakeFunctionCall(ctx, funcs[0], objectType, args, node, false, 0, funcExpr.type.stackOffset);
  8286. }
  8287. else
  8288. isOK = false;
  8289. }
  8290. }
  8291. else
  8292. {
  8293. // Failed to compile the argument list, set the dummy type and continue compilation
  8294. ctx->type.SetDummy();
  8295. isOK = false;
  8296. }
  8297. // Cleanup
  8298. for( asUINT n = 0; n < args.GetLength(); n++ )
  8299. if( args[n] )
  8300. {
  8301. asDELETE(args[n],asSExprContext);
  8302. }
  8303. for( asUINT n = 0; n < namedArgs.GetLength(); n++ )
  8304. if( namedArgs[n].ctx )
  8305. {
  8306. asDELETE(namedArgs[n].ctx,asSExprContext);
  8307. }
  8308. if( initializeMembers )
  8309. {
  8310. asASSERT( m_isConstructor );
  8311. // Need to initialize members here, as they may use the properties of the base class
  8312. // If there are multiple paths that call super(), then there will also be multiple
  8313. // locations with initializations of the members. It is not possible to consolidate
  8314. // these in one place, as the expressions for the initialization are evaluated where
  8315. // they are compiled, which means that they may access different variables depending
  8316. // on the scope where super() is called.
  8317. // Members that don't have an explicit initialization expression will be initialized
  8318. // beginning of the constructor as they are guaranteed not to use at the any
  8319. // members of the base class.
  8320. CompileMemberInitialization(&ctx->bc, false);
  8321. }
  8322. return isOK ? 0 : -1;
  8323. }
  8324. asSNameSpace *asCCompiler::DetermineNameSpace(const asCString &scope)
  8325. {
  8326. asSNameSpace *ns;
  8327. if( scope == "" )
  8328. {
  8329. if( outFunc->nameSpace->name != "" )
  8330. ns = outFunc->nameSpace;
  8331. else if( outFunc->objectType && outFunc->objectType->nameSpace->name != "" )
  8332. ns = outFunc->objectType->nameSpace;
  8333. else
  8334. ns = engine->nameSpaces[0];
  8335. }
  8336. else if( scope == "::" )
  8337. ns = engine->nameSpaces[0];
  8338. else
  8339. ns = engine->FindNameSpace(scope.AddressOf());
  8340. return ns;
  8341. }
  8342. int asCCompiler::CompileExpressionPreOp(asCScriptNode *node, asSExprContext *ctx)
  8343. {
  8344. int op = node->tokenType;
  8345. // Don't allow any prefix operators except handle on expressions that take address of class method
  8346. if( ctx->IsClassMethod() && op != ttHandle )
  8347. {
  8348. Error(TXT_INVALID_OP_ON_METHOD, node);
  8349. return -1;
  8350. }
  8351. // Don't allow any operators on void expressions
  8352. if( ctx->type.IsVoidExpression() )
  8353. {
  8354. Error(TXT_VOID_CANT_BE_OPERAND, node);
  8355. return -1;
  8356. }
  8357. IsVariableInitialized(&ctx->type, node);
  8358. if( op == ttHandle )
  8359. {
  8360. if( ctx->methodName != "" )
  8361. {
  8362. // Don't allow taking the handle of a handle
  8363. if( ctx->type.isExplicitHandle )
  8364. {
  8365. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  8366. return -1;
  8367. }
  8368. }
  8369. else
  8370. {
  8371. // Don't allow taking handle of a handle, i.e. @@
  8372. if( ctx->type.isExplicitHandle )
  8373. {
  8374. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  8375. return -1;
  8376. }
  8377. // @null is allowed even though it is implicit
  8378. if( !ctx->type.IsNullConstant() )
  8379. {
  8380. // Verify that the type allow its handle to be taken
  8381. if( !ctx->type.dataType.IsObject() ||
  8382. !(((ctx->type.dataType.GetObjectType()->beh.addref && ctx->type.dataType.GetObjectType()->beh.release) || (ctx->type.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) ||
  8383. (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  8384. {
  8385. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  8386. return -1;
  8387. }
  8388. // Objects that are not local variables are not references
  8389. // Objects allocated on the stack are also not marked as references
  8390. if( !ctx->type.dataType.IsReference() &&
  8391. !(ctx->type.dataType.IsObject() && !ctx->type.isVariable) &&
  8392. !(ctx->type.isVariable && !IsVariableOnHeap(ctx->type.stackOffset)) )
  8393. {
  8394. Error(TXT_NOT_VALID_REFERENCE, node);
  8395. return -1;
  8396. }
  8397. // Convert the expression to a handle
  8398. if( !ctx->type.dataType.IsObjectHandle() && !(ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  8399. {
  8400. asCDataType to = ctx->type.dataType;
  8401. to.MakeHandle(true);
  8402. to.MakeReference(true);
  8403. to.MakeHandleToConst(ctx->type.dataType.IsReadOnly());
  8404. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV, true, false);
  8405. asASSERT( ctx->type.dataType.IsObjectHandle() );
  8406. }
  8407. else if( ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  8408. {
  8409. // For the ASHANDLE type we'll simply set the expression as a handle
  8410. ctx->type.dataType.MakeHandle(true);
  8411. }
  8412. }
  8413. }
  8414. // Mark the expression as an explicit handle to avoid implicit conversions to non-handle expressions
  8415. ctx->type.isExplicitHandle = true;
  8416. }
  8417. else if( (op == ttMinus || op == ttPlus || op == ttBitNot || op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  8418. {
  8419. // Look for the appropriate method
  8420. // There is no overloadable operator for unary plus
  8421. const char *opName = 0;
  8422. switch( op )
  8423. {
  8424. case ttMinus: opName = "opNeg"; break;
  8425. case ttBitNot: opName = "opCom"; break;
  8426. case ttInc: opName = "opPreInc"; break;
  8427. case ttDec: opName = "opPreDec"; break;
  8428. }
  8429. if( opName )
  8430. {
  8431. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  8432. ProcessPropertyGetAccessor(ctx, node);
  8433. // 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
  8434. // Find the correct method
  8435. bool isConst = ctx->type.dataType.IsObjectConst();
  8436. asCArray<int> funcs;
  8437. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  8438. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  8439. {
  8440. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  8441. if( func->name == opName &&
  8442. func->parameterTypes.GetLength() == 0 &&
  8443. (!isConst || func->isReadOnly) )
  8444. {
  8445. funcs.PushLast(func->id);
  8446. }
  8447. }
  8448. // Did we find the method?
  8449. if( funcs.GetLength() == 1 )
  8450. {
  8451. asCArray<asSExprContext *> args;
  8452. MakeFunctionCall(ctx, funcs[0], ctx->type.dataType.GetObjectType(), args, node);
  8453. return 0;
  8454. }
  8455. else if( funcs.GetLength() == 0 )
  8456. {
  8457. asCString str;
  8458. str = asCString(opName) + "()";
  8459. if( isConst )
  8460. str += " const";
  8461. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  8462. Error(str, node);
  8463. ctx->type.SetDummy();
  8464. return -1;
  8465. }
  8466. else if( funcs.GetLength() > 1 )
  8467. {
  8468. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  8469. PrintMatchingFuncs(funcs, node);
  8470. ctx->type.SetDummy();
  8471. return -1;
  8472. }
  8473. }
  8474. else if( op == ttPlus )
  8475. {
  8476. Error(TXT_ILLEGAL_OPERATION, node);
  8477. ctx->type.SetDummy();
  8478. return -1;
  8479. }
  8480. }
  8481. else if( op == ttPlus || op == ttMinus )
  8482. {
  8483. // This is only for primitives. Objects are treated in the above block
  8484. // Make sure the type is a math type
  8485. if( !(ctx->type.dataType.IsIntegerType() ||
  8486. ctx->type.dataType.IsUnsignedType() ||
  8487. ctx->type.dataType.IsFloatType() ||
  8488. ctx->type.dataType.IsDoubleType() ) )
  8489. {
  8490. Error(TXT_ILLEGAL_OPERATION, node);
  8491. return -1;
  8492. }
  8493. ProcessPropertyGetAccessor(ctx, node);
  8494. asCDataType to = ctx->type.dataType;
  8495. if( ctx->type.dataType.IsUnsignedType() )
  8496. {
  8497. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  8498. to = asCDataType::CreatePrimitive(ttInt8, false);
  8499. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  8500. to = asCDataType::CreatePrimitive(ttInt16, false);
  8501. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  8502. to = asCDataType::CreatePrimitive(ttInt, false);
  8503. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  8504. to = asCDataType::CreatePrimitive(ttInt64, false);
  8505. else
  8506. {
  8507. Error(TXT_INVALID_TYPE, node);
  8508. return -1;
  8509. }
  8510. }
  8511. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  8512. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  8513. if( !ctx->type.isConstant )
  8514. {
  8515. ConvertToTempVariable(ctx);
  8516. asASSERT(!ctx->type.isLValue);
  8517. if( op == ttMinus )
  8518. {
  8519. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8520. ctx->bc.InstrSHORT(asBC_NEGi, ctx->type.stackOffset);
  8521. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8522. ctx->bc.InstrSHORT(asBC_NEGi64, ctx->type.stackOffset);
  8523. else if( ctx->type.dataType.IsFloatType() )
  8524. ctx->bc.InstrSHORT(asBC_NEGf, ctx->type.stackOffset);
  8525. else if( ctx->type.dataType.IsDoubleType() )
  8526. ctx->bc.InstrSHORT(asBC_NEGd, ctx->type.stackOffset);
  8527. else
  8528. {
  8529. Error(TXT_ILLEGAL_OPERATION, node);
  8530. return -1;
  8531. }
  8532. return 0;
  8533. }
  8534. }
  8535. else
  8536. {
  8537. if( op == ttMinus )
  8538. {
  8539. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8540. ctx->type.intValue = -ctx->type.intValue;
  8541. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8542. ctx->type.qwordValue = -(asINT64)ctx->type.qwordValue;
  8543. else if( ctx->type.dataType.IsFloatType() )
  8544. ctx->type.floatValue = -ctx->type.floatValue;
  8545. else if( ctx->type.dataType.IsDoubleType() )
  8546. ctx->type.doubleValue = -ctx->type.doubleValue;
  8547. else
  8548. {
  8549. Error(TXT_ILLEGAL_OPERATION, node);
  8550. return -1;
  8551. }
  8552. return 0;
  8553. }
  8554. }
  8555. }
  8556. else if( op == ttNot )
  8557. {
  8558. if( ctx->type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  8559. {
  8560. if( ctx->type.isConstant )
  8561. {
  8562. ctx->type.dwordValue = (ctx->type.dwordValue == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  8563. return 0;
  8564. }
  8565. ProcessPropertyGetAccessor(ctx, node);
  8566. ConvertToTempVariable(ctx);
  8567. asASSERT(!ctx->type.isLValue);
  8568. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  8569. }
  8570. else
  8571. {
  8572. Error(TXT_ILLEGAL_OPERATION, node);
  8573. return -1;
  8574. }
  8575. }
  8576. else if( op == ttBitNot )
  8577. {
  8578. ProcessPropertyGetAccessor(ctx, node);
  8579. asCDataType to = ctx->type.dataType;
  8580. if( ctx->type.dataType.IsIntegerType() )
  8581. {
  8582. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  8583. to = asCDataType::CreatePrimitive(ttUInt8, false);
  8584. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  8585. to = asCDataType::CreatePrimitive(ttUInt16, false);
  8586. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  8587. to = asCDataType::CreatePrimitive(ttUInt, false);
  8588. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  8589. to = asCDataType::CreatePrimitive(ttUInt64, false);
  8590. else
  8591. {
  8592. Error(TXT_INVALID_TYPE, node);
  8593. return -1;
  8594. }
  8595. }
  8596. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  8597. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  8598. if( ctx->type.dataType.IsUnsignedType() )
  8599. {
  8600. if( ctx->type.isConstant )
  8601. {
  8602. ctx->type.qwordValue = ~ctx->type.qwordValue;
  8603. return 0;
  8604. }
  8605. ConvertToTempVariable(ctx);
  8606. asASSERT(!ctx->type.isLValue);
  8607. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8608. ctx->bc.InstrSHORT(asBC_BNOT, ctx->type.stackOffset);
  8609. else
  8610. ctx->bc.InstrSHORT(asBC_BNOT64, ctx->type.stackOffset);
  8611. }
  8612. else
  8613. {
  8614. Error(TXT_ILLEGAL_OPERATION, node);
  8615. return -1;
  8616. }
  8617. }
  8618. else if( op == ttInc || op == ttDec )
  8619. {
  8620. // Need a reference to the primitive that will be updated
  8621. // The result of this expression is the same reference as before
  8622. // Make sure the reference isn't a temporary variable
  8623. if( ctx->type.isTemporary )
  8624. {
  8625. Error(TXT_REF_IS_TEMP, node);
  8626. return -1;
  8627. }
  8628. if( ctx->type.dataType.IsReadOnly() )
  8629. {
  8630. Error(TXT_REF_IS_READ_ONLY, node);
  8631. return -1;
  8632. }
  8633. if( ctx->property_get || ctx->property_set )
  8634. {
  8635. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  8636. return -1;
  8637. }
  8638. if( !ctx->type.isLValue )
  8639. {
  8640. Error(TXT_NOT_LVALUE, node);
  8641. return -1;
  8642. }
  8643. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  8644. ConvertToReference(ctx);
  8645. else if( !ctx->type.dataType.IsReference() )
  8646. {
  8647. Error(TXT_NOT_VALID_REFERENCE, node);
  8648. return -1;
  8649. }
  8650. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  8651. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  8652. {
  8653. if( op == ttInc )
  8654. ctx->bc.Instr(asBC_INCi64);
  8655. else
  8656. ctx->bc.Instr(asBC_DECi64);
  8657. }
  8658. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt, false)) ||
  8659. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt, false)) )
  8660. {
  8661. if( op == ttInc )
  8662. ctx->bc.Instr(asBC_INCi);
  8663. else
  8664. ctx->bc.Instr(asBC_DECi);
  8665. }
  8666. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  8667. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  8668. {
  8669. if( op == ttInc )
  8670. ctx->bc.Instr(asBC_INCi16);
  8671. else
  8672. ctx->bc.Instr(asBC_DECi16);
  8673. }
  8674. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  8675. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  8676. {
  8677. if( op == ttInc )
  8678. ctx->bc.Instr(asBC_INCi8);
  8679. else
  8680. ctx->bc.Instr(asBC_DECi8);
  8681. }
  8682. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttFloat, false)) )
  8683. {
  8684. if( op == ttInc )
  8685. ctx->bc.Instr(asBC_INCf);
  8686. else
  8687. ctx->bc.Instr(asBC_DECf);
  8688. }
  8689. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttDouble, false)) )
  8690. {
  8691. if( op == ttInc )
  8692. ctx->bc.Instr(asBC_INCd);
  8693. else
  8694. ctx->bc.Instr(asBC_DECd);
  8695. }
  8696. else
  8697. {
  8698. Error(TXT_ILLEGAL_OPERATION, node);
  8699. return -1;
  8700. }
  8701. }
  8702. else
  8703. {
  8704. // Unknown operator
  8705. asASSERT(false);
  8706. return -1;
  8707. }
  8708. return 0;
  8709. }
  8710. void asCCompiler::ConvertToReference(asSExprContext *ctx)
  8711. {
  8712. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  8713. {
  8714. ctx->bc.InstrSHORT(asBC_LDV, ctx->type.stackOffset);
  8715. ctx->type.dataType.MakeReference(true);
  8716. ctx->type.SetVariable(ctx->type.dataType, ctx->type.stackOffset, ctx->type.isTemporary);
  8717. }
  8718. }
  8719. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asCScriptNode *node, asSNameSpace *ns, bool isThisAccess)
  8720. {
  8721. return FindPropertyAccessor(name, ctx, 0, node, ns, isThisAccess);
  8722. }
  8723. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node, asSNameSpace *ns, bool isThisAccess)
  8724. {
  8725. if( engine->ep.propertyAccessorMode == 0 )
  8726. {
  8727. // Property accessors have been disabled by the application
  8728. return 0;
  8729. }
  8730. int getId = 0, setId = 0;
  8731. asCString getName = "get_" + name;
  8732. asCString setName = "set_" + name;
  8733. asCArray<int> multipleGetFuncs, multipleSetFuncs;
  8734. if( ctx->type.dataType.IsObject() )
  8735. {
  8736. asASSERT( ns == 0 );
  8737. // Don't look for property accessors in script classes if the script
  8738. // property accessors have been disabled by the application
  8739. if( !(ctx->type.dataType.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) ||
  8740. engine->ep.propertyAccessorMode == 2 )
  8741. {
  8742. // Check if the object has any methods with the corresponding accessor name(s)
  8743. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  8744. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  8745. {
  8746. asCScriptFunction *f = engine->scriptFunctions[ot->methods[n]];
  8747. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  8748. if( f->name == getName && (int)f->parameterTypes.GetLength() == (arg?1:0) )
  8749. {
  8750. if( getId == 0 )
  8751. getId = ot->methods[n];
  8752. else
  8753. {
  8754. if( multipleGetFuncs.GetLength() == 0 )
  8755. multipleGetFuncs.PushLast(getId);
  8756. multipleGetFuncs.PushLast(ot->methods[n]);
  8757. }
  8758. }
  8759. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  8760. if( f->name == setName && (int)f->parameterTypes.GetLength() == (arg?2:1) )
  8761. {
  8762. if( setId == 0 )
  8763. setId = ot->methods[n];
  8764. else
  8765. {
  8766. if( multipleSetFuncs.GetLength() == 0 )
  8767. multipleSetFuncs.PushLast(setId);
  8768. multipleSetFuncs.PushLast(ot->methods[n]);
  8769. }
  8770. }
  8771. }
  8772. }
  8773. }
  8774. else
  8775. {
  8776. asASSERT( ns != 0 );
  8777. // Look for appropriate global functions.
  8778. asCArray<int> funcs;
  8779. asUINT n;
  8780. builder->GetFunctionDescriptions(getName.AddressOf(), funcs, ns);
  8781. for( n = 0; n < funcs.GetLength(); n++ )
  8782. {
  8783. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  8784. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  8785. if( (int)f->parameterTypes.GetLength() == (arg?1:0) )
  8786. {
  8787. if( getId == 0 )
  8788. getId = funcs[n];
  8789. else
  8790. {
  8791. if( multipleGetFuncs.GetLength() == 0 )
  8792. multipleGetFuncs.PushLast(getId);
  8793. multipleGetFuncs.PushLast(funcs[n]);
  8794. }
  8795. }
  8796. }
  8797. funcs.SetLength(0);
  8798. builder->GetFunctionDescriptions(setName.AddressOf(), funcs, ns);
  8799. for( n = 0; n < funcs.GetLength(); n++ )
  8800. {
  8801. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  8802. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  8803. if( (int)f->parameterTypes.GetLength() == (arg?2:1) )
  8804. {
  8805. if( setId == 0 )
  8806. setId = funcs[n];
  8807. else
  8808. {
  8809. if( multipleSetFuncs.GetLength() == 0 )
  8810. multipleSetFuncs.PushLast(getId);
  8811. multipleSetFuncs.PushLast(funcs[n]);
  8812. }
  8813. }
  8814. }
  8815. }
  8816. bool isConst = ctx->type.dataType.IsObjectConst();
  8817. // Check for multiple matches
  8818. if( multipleGetFuncs.GetLength() > 0 )
  8819. {
  8820. // Filter the list by constness
  8821. FilterConst(multipleGetFuncs, !isConst);
  8822. if( multipleGetFuncs.GetLength() > 1 )
  8823. {
  8824. asCString str;
  8825. str.Format(TXT_MULTIPLE_PROP_GET_ACCESSOR_FOR_s, name.AddressOf());
  8826. Error(str, node);
  8827. PrintMatchingFuncs(multipleGetFuncs, node);
  8828. return -1;
  8829. }
  8830. else
  8831. {
  8832. // The id may have changed
  8833. getId = multipleGetFuncs[0];
  8834. }
  8835. }
  8836. if( multipleSetFuncs.GetLength() > 0 )
  8837. {
  8838. // Filter the list by constness
  8839. FilterConst(multipleSetFuncs, !isConst);
  8840. if( multipleSetFuncs.GetLength() > 1 )
  8841. {
  8842. asCString str;
  8843. str.Format(TXT_MULTIPLE_PROP_SET_ACCESSOR_FOR_s, name.AddressOf());
  8844. Error(str, node);
  8845. PrintMatchingFuncs(multipleSetFuncs, node);
  8846. return -1;
  8847. }
  8848. else
  8849. {
  8850. // The id may have changed
  8851. setId = multipleSetFuncs[0];
  8852. }
  8853. }
  8854. // Check for type compatibility between get and set accessor
  8855. if( getId && setId )
  8856. {
  8857. asCScriptFunction *getFunc = builder->GetFunctionDescription(getId);
  8858. asCScriptFunction *setFunc = builder->GetFunctionDescription(setId);
  8859. // It is permitted for a getter to return a handle and the setter to take a reference
  8860. int idx = (arg?1:0);
  8861. if( !getFunc->returnType.IsEqualExceptRefAndConst(setFunc->parameterTypes[idx]) &&
  8862. !((getFunc->returnType.IsObjectHandle() && !setFunc->parameterTypes[idx].IsObjectHandle()) &&
  8863. (getFunc->returnType.GetObjectType() == setFunc->parameterTypes[idx].GetObjectType())) )
  8864. {
  8865. asCString str;
  8866. str.Format(TXT_GET_SET_ACCESSOR_TYPE_MISMATCH_FOR_s, name.AddressOf());
  8867. Error(str, node);
  8868. asCArray<int> funcs;
  8869. funcs.PushLast(getId);
  8870. funcs.PushLast(setId);
  8871. PrintMatchingFuncs(funcs, node);
  8872. return -1;
  8873. }
  8874. }
  8875. // Check if we are within one of the accessors
  8876. int realGetId = getId;
  8877. int realSetId = setId;
  8878. if( outFunc->objectType && isThisAccess )
  8879. {
  8880. // The property accessors would be virtual functions, so we need to find the real implementation
  8881. asCScriptFunction *getFunc = getId ? builder->GetFunctionDescription(getId) : 0;
  8882. if( getFunc &&
  8883. getFunc->funcType == asFUNC_VIRTUAL &&
  8884. outFunc->objectType->DerivesFrom(getFunc->objectType) )
  8885. realGetId = outFunc->objectType->virtualFunctionTable[getFunc->vfTableIdx]->id;
  8886. asCScriptFunction *setFunc = setId ? builder->GetFunctionDescription(setId) : 0;
  8887. if( setFunc &&
  8888. setFunc->funcType == asFUNC_VIRTUAL &&
  8889. outFunc->objectType->DerivesFrom(setFunc->objectType) )
  8890. realSetId = outFunc->objectType->virtualFunctionTable[setFunc->vfTableIdx]->id;
  8891. }
  8892. // Avoid recursive call, by not treating this as a property accessor call.
  8893. // This will also allow having the real property with the same name as the accessors.
  8894. if( (isThisAccess || outFunc->objectType == 0) &&
  8895. ((realGetId && realGetId == outFunc->id) ||
  8896. (realSetId && realSetId == outFunc->id)) )
  8897. {
  8898. getId = 0;
  8899. setId = 0;
  8900. }
  8901. // Check if the application has disabled script written property accessors
  8902. if( engine->ep.propertyAccessorMode == 1 )
  8903. {
  8904. if( getId && builder->GetFunctionDescription(getId)->funcType != asFUNC_SYSTEM )
  8905. getId = 0;
  8906. if( setId && builder->GetFunctionDescription(setId)->funcType != asFUNC_SYSTEM )
  8907. setId = 0;
  8908. }
  8909. if( getId || setId )
  8910. {
  8911. // Property accessors were found, but we don't know which is to be used yet, so
  8912. // we just prepare the bytecode for the method call, and then store the function ids
  8913. // so that the right one can be used when we get there.
  8914. ctx->property_get = getId;
  8915. ctx->property_set = setId;
  8916. if( ctx->type.dataType.IsObject() )
  8917. {
  8918. // If the object is read-only then we need to remember that
  8919. if( (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) ||
  8920. (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) )
  8921. ctx->property_const = true;
  8922. else
  8923. ctx->property_const = false;
  8924. // If the object is a handle then we need to remember that
  8925. ctx->property_handle = ctx->type.dataType.IsObjectHandle();
  8926. ctx->property_ref = ctx->type.dataType.IsReference();
  8927. }
  8928. // The setter's parameter type is used as the property type,
  8929. // unless only the getter is available
  8930. asCDataType dt;
  8931. if( setId )
  8932. dt = builder->GetFunctionDescription(setId)->parameterTypes[(arg?1:0)];
  8933. else
  8934. dt = builder->GetFunctionDescription(getId)->returnType;
  8935. // Just change the type, the context must still maintain information
  8936. // about previous variable offset and the indicator of temporary variable.
  8937. int offset = ctx->type.stackOffset;
  8938. bool isTemp = ctx->type.isTemporary;
  8939. ctx->type.Set(dt);
  8940. ctx->type.stackOffset = (short)offset;
  8941. ctx->type.isTemporary = isTemp;
  8942. ctx->exprNode = node;
  8943. // Store the argument for later use
  8944. if( arg )
  8945. {
  8946. ctx->property_arg = asNEW(asSExprContext)(engine);
  8947. if( ctx->property_arg == 0 )
  8948. {
  8949. // Out of memory
  8950. return -1;
  8951. }
  8952. MergeExprBytecodeAndType(ctx->property_arg, arg);
  8953. }
  8954. return 1;
  8955. }
  8956. // No accessor was found
  8957. return 0;
  8958. }
  8959. int asCCompiler::ProcessPropertySetAccessor(asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node)
  8960. {
  8961. // TODO: A lot of this code is similar to ProcessPropertyGetAccessor. Can we unify them?
  8962. if( !ctx->property_set )
  8963. {
  8964. Error(TXT_PROPERTY_HAS_NO_SET_ACCESSOR, node);
  8965. return -1;
  8966. }
  8967. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_set);
  8968. // Make sure the arg match the property
  8969. asCArray<int> funcs;
  8970. funcs.PushLast(ctx->property_set);
  8971. asCArray<asSExprContext *> args;
  8972. if( ctx->property_arg )
  8973. args.PushLast(ctx->property_arg);
  8974. args.PushLast(arg);
  8975. MatchFunctions(funcs, args, node, func->GetName(), 0, func->objectType, ctx->property_const);
  8976. if( funcs.GetLength() == 0 )
  8977. {
  8978. // MatchFunctions already reported the error
  8979. if( ctx->property_arg )
  8980. {
  8981. asDELETE(ctx->property_arg, asSExprContext);
  8982. ctx->property_arg = 0;
  8983. }
  8984. return -1;
  8985. }
  8986. if( func->objectType )
  8987. {
  8988. // Setup the context with the original type so the method call gets built correctly
  8989. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  8990. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  8991. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  8992. // Don't allow the call if the object is read-only and the property accessor is not const
  8993. if( ctx->property_const && !func->isReadOnly )
  8994. {
  8995. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  8996. asCArray<int> funcs;
  8997. funcs.PushLast(ctx->property_set);
  8998. PrintMatchingFuncs(funcs, node);
  8999. }
  9000. }
  9001. // Call the accessor
  9002. MakeFunctionCall(ctx, ctx->property_set, func->objectType, args, node);
  9003. ctx->property_get = 0;
  9004. ctx->property_set = 0;
  9005. if( ctx->property_arg )
  9006. {
  9007. asDELETE(ctx->property_arg, asSExprContext);
  9008. ctx->property_arg = 0;
  9009. }
  9010. return 0;
  9011. }
  9012. void asCCompiler::ProcessPropertyGetAccessor(asSExprContext *ctx, asCScriptNode *node)
  9013. {
  9014. // If no property accessor has been prepared then don't do anything
  9015. if( !ctx->property_get && !ctx->property_set )
  9016. return;
  9017. if( !ctx->property_get )
  9018. {
  9019. // Raise error on missing accessor
  9020. Error(TXT_PROPERTY_HAS_NO_GET_ACCESSOR, node);
  9021. ctx->type.SetDummy();
  9022. return;
  9023. }
  9024. asCTypeInfo objType = ctx->type;
  9025. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_get);
  9026. // Make sure the arg match the property
  9027. asCArray<int> funcs;
  9028. funcs.PushLast(ctx->property_get);
  9029. asCArray<asSExprContext *> args;
  9030. if( ctx->property_arg )
  9031. args.PushLast(ctx->property_arg);
  9032. MatchFunctions(funcs, args, node, func->GetName(), 0, func->objectType, ctx->property_const);
  9033. if( funcs.GetLength() == 0 )
  9034. {
  9035. // MatchFunctions already reported the error
  9036. if( ctx->property_arg )
  9037. {
  9038. asDELETE(ctx->property_arg, asSExprContext);
  9039. ctx->property_arg = 0;
  9040. }
  9041. ctx->type.SetDummy();
  9042. return;
  9043. }
  9044. if( func->objectType )
  9045. {
  9046. // Setup the context with the original type so the method call gets built correctly
  9047. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  9048. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  9049. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  9050. // Don't allow the call if the object is read-only and the property accessor is not const
  9051. if( ctx->property_const && !func->isReadOnly )
  9052. {
  9053. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  9054. asCArray<int> funcs;
  9055. funcs.PushLast(ctx->property_get);
  9056. PrintMatchingFuncs(funcs, node);
  9057. }
  9058. }
  9059. // Call the accessor
  9060. MakeFunctionCall(ctx, ctx->property_get, func->objectType, args, node);
  9061. ctx->property_get = 0;
  9062. ctx->property_set = 0;
  9063. if( ctx->property_arg )
  9064. {
  9065. asDELETE(ctx->property_arg, asSExprContext);
  9066. ctx->property_arg = 0;
  9067. }
  9068. }
  9069. int asCCompiler::CompileExpressionPostOp(asCScriptNode *node, asSExprContext *ctx)
  9070. {
  9071. // Don't allow any postfix operators on expressions that take address of class method
  9072. if( ctx->IsClassMethod() )
  9073. {
  9074. Error(TXT_INVALID_OP_ON_METHOD, node);
  9075. return -1;
  9076. }
  9077. // Don't allow any operators on void expressions
  9078. if( ctx->type.IsVoidExpression() )
  9079. {
  9080. Error(TXT_VOID_CANT_BE_OPERAND, node);
  9081. return -1;
  9082. }
  9083. // Check if the variable is initialized (if it indeed is a variable)
  9084. IsVariableInitialized(&ctx->type, node);
  9085. int op = node->tokenType;
  9086. if( (op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  9087. {
  9088. const char *opName = 0;
  9089. switch( op )
  9090. {
  9091. case ttInc: opName = "opPostInc"; break;
  9092. case ttDec: opName = "opPostDec"; break;
  9093. }
  9094. if( opName )
  9095. {
  9096. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  9097. ProcessPropertyGetAccessor(ctx, node);
  9098. // 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
  9099. // Find the correct method
  9100. bool isConst = ctx->type.dataType.IsObjectConst();
  9101. asCArray<int> funcs;
  9102. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  9103. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  9104. {
  9105. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  9106. if( func->name == opName &&
  9107. func->parameterTypes.GetLength() == 0 &&
  9108. (!isConst || func->isReadOnly) )
  9109. {
  9110. funcs.PushLast(func->id);
  9111. }
  9112. }
  9113. // Did we find the method?
  9114. if( funcs.GetLength() == 1 )
  9115. {
  9116. asCArray<asSExprContext *> args;
  9117. MakeFunctionCall(ctx, funcs[0], ctx->type.dataType.GetObjectType(), args, node);
  9118. return 0;
  9119. }
  9120. else if( funcs.GetLength() == 0 )
  9121. {
  9122. asCString str;
  9123. str = asCString(opName) + "()";
  9124. if( isConst )
  9125. str += " const";
  9126. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  9127. Error(str, node);
  9128. ctx->type.SetDummy();
  9129. return -1;
  9130. }
  9131. else if( funcs.GetLength() > 1 )
  9132. {
  9133. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  9134. PrintMatchingFuncs(funcs, node);
  9135. ctx->type.SetDummy();
  9136. return -1;
  9137. }
  9138. }
  9139. }
  9140. else if( op == ttInc || op == ttDec )
  9141. {
  9142. // Make sure the reference isn't a temporary variable
  9143. if( ctx->type.isTemporary )
  9144. {
  9145. Error(TXT_REF_IS_TEMP, node);
  9146. return -1;
  9147. }
  9148. if( ctx->type.dataType.IsReadOnly() )
  9149. {
  9150. Error(TXT_REF_IS_READ_ONLY, node);
  9151. return -1;
  9152. }
  9153. if( ctx->property_get || ctx->property_set )
  9154. {
  9155. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  9156. return -1;
  9157. }
  9158. if( !ctx->type.isLValue )
  9159. {
  9160. Error(TXT_NOT_LVALUE, node);
  9161. return -1;
  9162. }
  9163. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  9164. ConvertToReference(ctx);
  9165. else if( !ctx->type.dataType.IsReference() )
  9166. {
  9167. Error(TXT_NOT_VALID_REFERENCE, node);
  9168. return -1;
  9169. }
  9170. // Copy the value to a temp before changing it
  9171. ConvertToTempVariable(ctx);
  9172. asASSERT(!ctx->type.isLValue);
  9173. // Increment the value pointed to by the reference still in the register
  9174. asEBCInstr iInc = asBC_INCi, iDec = asBC_DECi;
  9175. if( ctx->type.dataType.IsDoubleType() )
  9176. {
  9177. iInc = asBC_INCd;
  9178. iDec = asBC_DECd;
  9179. }
  9180. else if( ctx->type.dataType.IsFloatType() )
  9181. {
  9182. iInc = asBC_INCf;
  9183. iDec = asBC_DECf;
  9184. }
  9185. else if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() )
  9186. {
  9187. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  9188. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  9189. {
  9190. iInc = asBC_INCi16;
  9191. iDec = asBC_DECi16;
  9192. }
  9193. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  9194. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  9195. {
  9196. iInc = asBC_INCi8;
  9197. iDec = asBC_DECi8;
  9198. }
  9199. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  9200. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  9201. {
  9202. iInc = asBC_INCi64;
  9203. iDec = asBC_DECi64;
  9204. }
  9205. }
  9206. else
  9207. {
  9208. Error(TXT_ILLEGAL_OPERATION, node);
  9209. return -1;
  9210. }
  9211. if( op == ttInc ) ctx->bc.Instr(iInc); else ctx->bc.Instr(iDec);
  9212. }
  9213. else if( op == ttDot )
  9214. {
  9215. if( node->firstChild->nodeType == snIdentifier )
  9216. {
  9217. ProcessPropertyGetAccessor(ctx, node);
  9218. // Get the property name
  9219. asCString name(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  9220. if( ctx->type.dataType.IsObject() )
  9221. {
  9222. // We need to look for get/set property accessors.
  9223. // If found, the context stores information on the get/set accessors
  9224. // until it is known which is to be used.
  9225. int r = 0;
  9226. if( node->next && node->next->tokenType == ttOpenBracket )
  9227. {
  9228. // The property accessor should take an index arg
  9229. asSExprContext dummyArg(engine);
  9230. r = FindPropertyAccessor(name, ctx, &dummyArg, node, 0);
  9231. }
  9232. if( r == 0 )
  9233. r = FindPropertyAccessor(name, ctx, node, 0);
  9234. if( r != 0 )
  9235. return r;
  9236. if( !ctx->type.dataType.IsPrimitive() )
  9237. Dereference(ctx, true);
  9238. if( ctx->type.dataType.IsObjectHandle() )
  9239. {
  9240. // Convert the handle to a normal object
  9241. asCDataType dt = ctx->type.dataType;
  9242. dt.MakeHandle(false);
  9243. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  9244. // The handle may not have been an lvalue, but the dereferenced object is
  9245. ctx->type.isLValue = true;
  9246. }
  9247. bool isConst = ctx->type.dataType.IsObjectConst();
  9248. asCObjectProperty *prop = builder->GetObjectProperty(ctx->type.dataType, name.AddressOf());
  9249. if( prop )
  9250. {
  9251. // Is the property access allowed?
  9252. if( prop->isPrivate && (!outFunc || outFunc->objectType != ctx->type.dataType.GetObjectType()) )
  9253. {
  9254. asCString msg;
  9255. msg.Format(TXT_PRIVATE_PROP_ACCESS_s, name.AddressOf());
  9256. Error(msg, node);
  9257. }
  9258. // Put the offset on the stack
  9259. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(ctx->type.dataType.GetObjectType(), false)));
  9260. if( prop->type.IsReference() )
  9261. ctx->bc.Instr(asBC_RDSPtr);
  9262. // Reference to primitive must be stored in the temp register
  9263. if( prop->type.IsPrimitive() )
  9264. {
  9265. ctx->bc.Instr(asBC_PopRPtr);
  9266. }
  9267. // Keep information about temporary variables as deferred expression
  9268. if( ctx->type.isTemporary )
  9269. {
  9270. // Add the release of this reference, as a deferred expression
  9271. asSDeferredParam deferred;
  9272. deferred.origExpr = 0;
  9273. deferred.argInOutFlags = asTM_INREF;
  9274. deferred.argNode = 0;
  9275. deferred.argType.SetVariable(ctx->type.dataType, ctx->type.stackOffset, true);
  9276. ctx->deferredParams.PushLast(deferred);
  9277. }
  9278. // Set the new type and make sure it is not treated as a variable anymore
  9279. ctx->type.dataType = prop->type;
  9280. ctx->type.dataType.MakeReference(true);
  9281. ctx->type.isVariable = false;
  9282. ctx->type.isTemporary = false;
  9283. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  9284. {
  9285. // Objects that are members are not references
  9286. ctx->type.dataType.MakeReference(false);
  9287. }
  9288. ctx->type.dataType.MakeReadOnly(isConst ? true : prop->type.IsReadOnly());
  9289. }
  9290. else
  9291. {
  9292. // If the name is not a property, the compiler must check if the name matches
  9293. // a method, which can be used for constructing delegates
  9294. asIScriptFunction *func = 0;
  9295. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  9296. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  9297. {
  9298. if( engine->scriptFunctions[ot->methods[n]]->name == name )
  9299. {
  9300. func = engine->scriptFunctions[ot->methods[n]];
  9301. break;
  9302. }
  9303. }
  9304. if( func )
  9305. {
  9306. // An object method was found. Keep the name of the method in the expression, but
  9307. // don't actually modify the bytecode at this point since it is not yet known what
  9308. // the method will be used for, or even what overloaded method should be used.
  9309. ctx->methodName = name;
  9310. }
  9311. else
  9312. {
  9313. asCString str;
  9314. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  9315. Error(str, node);
  9316. return -1;
  9317. }
  9318. }
  9319. }
  9320. else
  9321. {
  9322. asCString str;
  9323. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  9324. Error(str, node);
  9325. return -1;
  9326. }
  9327. }
  9328. else
  9329. {
  9330. // Make sure it is an object we are accessing
  9331. if( !ctx->type.dataType.IsObject() )
  9332. {
  9333. asCString str;
  9334. str.Format(TXT_ILLEGAL_OPERATION_ON_s, ctx->type.dataType.Format().AddressOf());
  9335. Error(str, node);
  9336. return -1;
  9337. }
  9338. // Process the get property accessor
  9339. ProcessPropertyGetAccessor(ctx, node);
  9340. // Compile function call
  9341. int r = CompileFunctionCall(node->firstChild, ctx, ctx->type.dataType.GetObjectType(), ctx->type.dataType.IsObjectConst());
  9342. if( r < 0 ) return r;
  9343. }
  9344. }
  9345. else if( op == ttOpenBracket )
  9346. {
  9347. // If the property access takes an index arg and the argument hasn't been evaluated yet,
  9348. // then we should use that instead of processing it now. If the argument has already been
  9349. // evaluated, then we should process the property accessor as a get access now as the new
  9350. // index operator is on the result of that accessor.
  9351. asCString propertyName;
  9352. asSNameSpace *ns = 0;
  9353. if( ((ctx->property_get && builder->GetFunctionDescription(ctx->property_get)->GetParamCount() == 1) ||
  9354. (ctx->property_set && builder->GetFunctionDescription(ctx->property_set)->GetParamCount() == 2)) &&
  9355. (ctx->property_arg && ctx->property_arg->type.dataType.GetTokenType() == ttUnrecognizedToken) )
  9356. {
  9357. // Determine the name of the property accessor
  9358. asCScriptFunction *func = 0;
  9359. if( ctx->property_get )
  9360. func = builder->GetFunctionDescription(ctx->property_get);
  9361. else
  9362. func = builder->GetFunctionDescription(ctx->property_set);
  9363. propertyName = func->GetName();
  9364. propertyName = propertyName.SubString(4);
  9365. // Set the original type of the expression so we can re-evaluate the property accessor
  9366. if( func->objectType )
  9367. {
  9368. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  9369. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  9370. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  9371. }
  9372. else
  9373. {
  9374. // Store the namespace where the function is declared
  9375. // so the same function can be found later
  9376. ctx->type.SetDummy();
  9377. ns = func->nameSpace;
  9378. }
  9379. ctx->property_get = ctx->property_set = 0;
  9380. if( ctx->property_arg )
  9381. {
  9382. asDELETE(ctx->property_arg, asSExprContext);
  9383. ctx->property_arg = 0;
  9384. }
  9385. }
  9386. else
  9387. {
  9388. if( !ctx->type.dataType.IsObject() )
  9389. {
  9390. asCString str;
  9391. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  9392. Error(str, node);
  9393. return -1;
  9394. }
  9395. ProcessPropertyGetAccessor(ctx, node);
  9396. }
  9397. // Compile the expression
  9398. bool isOK = true;
  9399. asCArray<asSExprContext *> args;
  9400. asCArray<asSNamedArgument> namedArgs;
  9401. asASSERT( node->firstChild->nodeType == snArgList );
  9402. if( CompileArgumentList(node->firstChild, args, namedArgs) >= 0 )
  9403. {
  9404. // Check for the existence of the opIndex method
  9405. bool lookForProperty = true;
  9406. if( propertyName == "" )
  9407. {
  9408. bool isConst = ctx->type.dataType.IsObjectConst();
  9409. asCObjectType *objectType = ctx->type.dataType.GetObjectType();
  9410. asCArray<int> funcs;
  9411. builder->GetObjectMethodDescriptions("opIndex", objectType, funcs, isConst);
  9412. if( funcs.GetLength() > 0 )
  9413. {
  9414. // Since there are opIndex methods, the compiler should not look for get/set_opIndex accessors
  9415. lookForProperty = false;
  9416. // Determine which of opIndex methods that match
  9417. MatchFunctions(funcs, args, node, "opIndex", 0, objectType, isConst);
  9418. if( funcs.GetLength() != 1 )
  9419. {
  9420. // The error has already been reported by MatchFunctions
  9421. isOK = false;
  9422. }
  9423. else
  9424. {
  9425. // Add the default values for arguments not explicitly supplied
  9426. int r = CompileDefaultAndNamedArgs(node, args, funcs[0], objectType);
  9427. if( r == 0 )
  9428. MakeFunctionCall(ctx, funcs[0], objectType, args, node, false, 0, ctx->type.stackOffset);
  9429. else
  9430. isOK = false;
  9431. }
  9432. }
  9433. }
  9434. if( lookForProperty && isOK )
  9435. {
  9436. if( args.GetLength() != 1 )
  9437. {
  9438. // TODO: opIndex: Implement this
  9439. Error("Property accessor with index only support 1 index argument for now", node);
  9440. isOK = false;
  9441. }
  9442. Dereference(ctx, true);
  9443. asSExprContext lctx(engine);
  9444. MergeExprBytecodeAndType(&lctx, ctx);
  9445. // Check for accessors methods for the opIndex, either as get/set_opIndex or as get/set with the property name
  9446. int r = FindPropertyAccessor(propertyName == "" ? "opIndex" : propertyName.AddressOf(), &lctx, args[0], node, ns);
  9447. if( r == 0 )
  9448. {
  9449. asCString str;
  9450. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  9451. Error(str, node);
  9452. isOK = false;
  9453. }
  9454. else if( r < 0 )
  9455. isOK = false;
  9456. if( isOK )
  9457. MergeExprBytecodeAndType(ctx, &lctx);
  9458. }
  9459. }
  9460. else
  9461. isOK = false;
  9462. // Cleanup
  9463. for( asUINT n = 0; n < args.GetLength(); n++ )
  9464. if( args[n] )
  9465. {
  9466. asDELETE(args[n],asSExprContext);
  9467. }
  9468. if( !isOK )
  9469. return -1;
  9470. }
  9471. else if( op == ttOpenParanthesis )
  9472. {
  9473. // TODO: Most of this is already done by CompileFunctionCall(). Can we share the code?
  9474. // Make sure the expression is a funcdef or an object that may have opCall methods
  9475. if( !ctx->type.dataType.GetFuncDef() && !ctx->type.dataType.IsObject() )
  9476. {
  9477. Error(TXT_EXPR_DOESNT_EVAL_TO_FUNC, node);
  9478. return -1;
  9479. }
  9480. // Compile arguments
  9481. asCArray<asSExprContext *> args;
  9482. asCArray<asSNamedArgument> namedArgs;
  9483. if( CompileArgumentList(node->lastChild, args, namedArgs) >= 0 )
  9484. {
  9485. // Match arguments with the funcdef
  9486. asCArray<int> funcs;
  9487. if( ctx->type.dataType.GetFuncDef() )
  9488. {
  9489. funcs.PushLast(ctx->type.dataType.GetFuncDef()->id);
  9490. MatchFunctions(funcs, args, node, ctx->type.dataType.GetFuncDef()->name.AddressOf(), &namedArgs);
  9491. }
  9492. else
  9493. {
  9494. bool isConst = ctx->type.dataType.IsObjectConst();
  9495. builder->GetObjectMethodDescriptions("opCall", ctx->type.dataType.GetObjectType(), funcs, isConst);
  9496. MatchFunctions(funcs, args, node, "opCall", &namedArgs, ctx->type.dataType.GetObjectType(), isConst);
  9497. }
  9498. if( funcs.GetLength() != 1 )
  9499. {
  9500. // The error was reported by MatchFunctions()
  9501. // Dummy value
  9502. ctx->type.SetDummy();
  9503. }
  9504. else
  9505. {
  9506. // Add the default values for arguments not explicitly supplied
  9507. int r = CompileDefaultAndNamedArgs(node, args, funcs[0], ctx->type.dataType.GetObjectType(), &namedArgs);
  9508. // TODO: funcdef: Do we have to make sure the handle is stored in a temporary variable, or
  9509. // is it enough to make sure it is in a local variable?
  9510. // For function pointer we must guarantee that the function is safe, i.e.
  9511. // by first storing the function pointer in a local variable (if it isn't already in one)
  9512. if( r == asSUCCESS )
  9513. {
  9514. Dereference(ctx, true);
  9515. if( ctx->type.dataType.GetFuncDef() )
  9516. {
  9517. if( !ctx->type.isVariable )
  9518. ConvertToVariable(ctx);
  9519. // Remove the reference from the stack as the asBC_CALLPTR instruction takes the variable as argument
  9520. ctx->bc.Instr(asBC_PopPtr);
  9521. }
  9522. MakeFunctionCall(ctx, funcs[0], 0, args, node, false, 0, ctx->type.stackOffset);
  9523. }
  9524. }
  9525. }
  9526. else
  9527. ctx->type.SetDummy();
  9528. // Cleanup
  9529. for( asUINT n = 0; n < args.GetLength(); n++ )
  9530. if( args[n] )
  9531. {
  9532. asDELETE(args[n],asSExprContext);
  9533. }
  9534. for( asUINT n = 0; n < namedArgs.GetLength(); n++ )
  9535. if( namedArgs[n].ctx )
  9536. {
  9537. asDELETE(namedArgs[n].ctx,asSExprContext);
  9538. }
  9539. }
  9540. return 0;
  9541. }
  9542. int asCCompiler::GetPrecedence(asCScriptNode *op)
  9543. {
  9544. // x ** y
  9545. // x * y, x / y, x % y
  9546. // x + y, x - y
  9547. // x <= y, x < y, x >= y, x > y
  9548. // x = =y, x != y, x xor y, x is y, x !is y
  9549. // x and y
  9550. // x or y
  9551. // The following are not used in this function,
  9552. // but should have lower precedence than the above
  9553. // x ? y : z
  9554. // x = y
  9555. // The expression term have the highest precedence
  9556. if( op->nodeType == snExprTerm )
  9557. return 1;
  9558. // Evaluate operators by token
  9559. int tokenType = op->tokenType;
  9560. if( tokenType == ttStarStar )
  9561. return 0;
  9562. if( tokenType == ttStar || tokenType == ttSlash || tokenType == ttPercent )
  9563. return -1;
  9564. if( tokenType == ttPlus || tokenType == ttMinus )
  9565. return -2;
  9566. if( tokenType == ttBitShiftLeft ||
  9567. tokenType == ttBitShiftRight ||
  9568. tokenType == ttBitShiftRightArith )
  9569. return -3;
  9570. if( tokenType == ttAmp )
  9571. return -4;
  9572. if( tokenType == ttBitXor )
  9573. return -5;
  9574. if( tokenType == ttBitOr )
  9575. return -6;
  9576. if( tokenType == ttLessThanOrEqual ||
  9577. tokenType == ttLessThan ||
  9578. tokenType == ttGreaterThanOrEqual ||
  9579. tokenType == ttGreaterThan )
  9580. return -7;
  9581. if( tokenType == ttEqual || tokenType == ttNotEqual || tokenType == ttXor || tokenType == ttIs || tokenType == ttNotIs )
  9582. return -8;
  9583. if( tokenType == ttAnd )
  9584. return -9;
  9585. if( tokenType == ttOr )
  9586. return -10;
  9587. // Unknown operator
  9588. asASSERT(false);
  9589. return 0;
  9590. }
  9591. asUINT asCCompiler::MatchArgument(asCArray<int> &funcs, asCArray<asSOverloadCandidate> &matches, const asSExprContext *argExpr, int paramNum, bool allowObjectConstruct)
  9592. {
  9593. matches.SetLength(0);
  9594. for( asUINT n = 0; n < funcs.GetLength(); n++ )
  9595. {
  9596. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  9597. // Does the function have arguments enough?
  9598. if( (int)desc->parameterTypes.GetLength() <= paramNum )
  9599. continue;
  9600. int cost = MatchArgument(desc, argExpr, paramNum, allowObjectConstruct);
  9601. if( cost != -1 )
  9602. matches.PushLast(asSOverloadCandidate(funcs[n], asUINT(cost)));
  9603. }
  9604. return (asUINT)matches.GetLength();
  9605. }
  9606. int asCCompiler::MatchArgument(asCScriptFunction *desc, const asSExprContext *argExpr, int paramNum, bool allowObjectConstruct)
  9607. {
  9608. // void expressions can match any out parameter, but nothing else
  9609. if( argExpr->type.IsVoidExpression() )
  9610. {
  9611. if( desc->inOutFlags[paramNum] == asTM_OUTREF )
  9612. return 0;
  9613. return -1;
  9614. }
  9615. // Can we make the match by implicit conversion?
  9616. asSExprContext ti(engine);
  9617. ti.type = argExpr->type;
  9618. ti.methodName = argExpr->methodName;
  9619. ti.enumValue = argExpr->enumValue;
  9620. if( argExpr->type.dataType.IsPrimitive() )
  9621. ti.type.dataType.MakeReference(false);
  9622. int cost = ImplicitConversion(&ti, desc->parameterTypes[paramNum], 0, asIC_IMPLICIT_CONV, false, allowObjectConstruct);
  9623. // If the function parameter is an inout-reference then it must not be possible to call the
  9624. // function with an incorrect argument type, even though the type can normally be converted.
  9625. if( desc->parameterTypes[paramNum].IsReference() &&
  9626. desc->inOutFlags[paramNum] == asTM_INOUTREF &&
  9627. desc->parameterTypes[paramNum].GetTokenType() != ttQuestion )
  9628. {
  9629. // Observe, that the below checks are only necessary for when unsafe references have been
  9630. // enabled by the application. Without this the &inout reference form wouldn't be allowed
  9631. // for these value types.
  9632. // Don't allow a primitive to be converted to a reference of another primitive type
  9633. if( desc->parameterTypes[paramNum].IsPrimitive() &&
  9634. desc->parameterTypes[paramNum].GetTokenType() != argExpr->type.dataType.GetTokenType() )
  9635. {
  9636. asASSERT( engine->ep.allowUnsafeReferences );
  9637. return -1;
  9638. }
  9639. // Don't allow an enum to be converted to a reference of another enum type
  9640. if( desc->parameterTypes[paramNum].IsEnumType() &&
  9641. desc->parameterTypes[paramNum].GetObjectType() != argExpr->type.dataType.GetObjectType() )
  9642. {
  9643. asASSERT( engine->ep.allowUnsafeReferences );
  9644. return -1;
  9645. }
  9646. // Don't allow a non-handle expression to be converted to a reference to a handle
  9647. if( desc->parameterTypes[paramNum].IsObjectHandle() &&
  9648. !argExpr->type.dataType.IsObjectHandle() )
  9649. {
  9650. asASSERT( engine->ep.allowUnsafeReferences );
  9651. return -1;
  9652. }
  9653. // Don't allow a value type to be converted
  9654. if( (desc->parameterTypes[paramNum].GetObjectType() && (desc->parameterTypes[paramNum].GetObjectType()->GetFlags() & asOBJ_VALUE)) &&
  9655. (desc->parameterTypes[paramNum].GetObjectType() != argExpr->type.dataType.GetObjectType()) )
  9656. {
  9657. asASSERT( engine->ep.allowUnsafeReferences );
  9658. return -1;
  9659. }
  9660. }
  9661. // How well does the argument match the function parameter?
  9662. if( desc->parameterTypes[paramNum].IsEqualExceptRef(ti.type.dataType) )
  9663. return cost;
  9664. // No match is available
  9665. return -1;
  9666. }
  9667. void asCCompiler::PrepareArgument2(asSExprContext *ctx, asSExprContext *arg, asCDataType *paramType, bool isFunction, int refType, bool isMakingCopy)
  9668. {
  9669. // Reference parameters whose value won't be used don't evaluate the expression
  9670. if( paramType->IsReference() && !(refType & asTM_INREF) )
  9671. {
  9672. // Store the original bytecode so that it can be reused when processing the deferred output parameter
  9673. asSExprContext *orig = asNEW(asSExprContext)(engine);
  9674. if( orig == 0 )
  9675. {
  9676. // Out of memory
  9677. return;
  9678. }
  9679. MergeExprBytecodeAndType(orig, arg);
  9680. arg->origExpr = orig;
  9681. }
  9682. PrepareArgument(paramType, arg, arg->exprNode, isFunction, refType, isMakingCopy);
  9683. // arg still holds the original expression for output parameters
  9684. ctx->bc.AddCode(&arg->bc);
  9685. }
  9686. bool asCCompiler::CompileOverloadedDualOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx, bool isHandle)
  9687. {
  9688. DetermineSingleFunc(lctx, node);
  9689. DetermineSingleFunc(rctx, node);
  9690. ctx->exprNode = node;
  9691. // What type of operator is it?
  9692. int token = node->tokenType;
  9693. if( token == ttUnrecognizedToken )
  9694. {
  9695. // This happens when the compiler is inferring an assignment
  9696. // operation from another action, for example in preparing a value
  9697. // as a function argument
  9698. token = ttAssignment;
  9699. }
  9700. // boolean operators are not overloadable
  9701. if( token == ttAnd ||
  9702. token == ttOr ||
  9703. token == ttXor )
  9704. return false;
  9705. // Dual operators can also be implemented as class methods
  9706. if( token == ttEqual ||
  9707. token == ttNotEqual )
  9708. {
  9709. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  9710. // Find the matching opEquals method
  9711. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  9712. if( r == 0 )
  9713. {
  9714. // Try again by switching the order of the operands
  9715. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  9716. }
  9717. if( r == 1 )
  9718. {
  9719. if( token == ttNotEqual )
  9720. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  9721. // Success, don't continue
  9722. return true;
  9723. }
  9724. else if( r < 0 )
  9725. {
  9726. // Compiler error, don't continue
  9727. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  9728. return true;
  9729. }
  9730. }
  9731. if( token == ttEqual ||
  9732. token == ttNotEqual ||
  9733. token == ttLessThan ||
  9734. token == ttLessThanOrEqual ||
  9735. token == ttGreaterThan ||
  9736. token == ttGreaterThanOrEqual )
  9737. {
  9738. bool swappedOrder = false;
  9739. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  9740. // Find the matching opCmp method
  9741. int r = CompileOverloadedDualOperator2(node, "opCmp", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  9742. if( r == 0 )
  9743. {
  9744. // Try again by switching the order of the operands
  9745. swappedOrder = true;
  9746. r = CompileOverloadedDualOperator2(node, "opCmp", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  9747. }
  9748. if( r == 1 )
  9749. {
  9750. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  9751. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  9752. ctx->bc.InstrW_DW(asBC_CMPIi, ctx->type.stackOffset, 0);
  9753. if( token == ttEqual )
  9754. ctx->bc.Instr(asBC_TZ);
  9755. else if( token == ttNotEqual )
  9756. ctx->bc.Instr(asBC_TNZ);
  9757. else if( (token == ttLessThan && !swappedOrder) ||
  9758. (token == ttGreaterThan && swappedOrder) )
  9759. ctx->bc.Instr(asBC_TS);
  9760. else if( (token == ttLessThanOrEqual && !swappedOrder) ||
  9761. (token == ttGreaterThanOrEqual && swappedOrder) )
  9762. ctx->bc.Instr(asBC_TNP);
  9763. else if( (token == ttGreaterThan && !swappedOrder) ||
  9764. (token == ttLessThan && swappedOrder) )
  9765. ctx->bc.Instr(asBC_TP);
  9766. else if( (token == ttGreaterThanOrEqual && !swappedOrder) ||
  9767. (token == ttLessThanOrEqual && swappedOrder) )
  9768. ctx->bc.Instr(asBC_TNS);
  9769. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9770. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), a, true);
  9771. // Success, don't continue
  9772. return true;
  9773. }
  9774. else if( r < 0 )
  9775. {
  9776. // Compiler error, don't continue
  9777. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  9778. return true;
  9779. }
  9780. }
  9781. // The rest of the operators are not commutative, and doesn't require specific return type
  9782. const char *op = 0, *op_r = 0;
  9783. switch( token )
  9784. {
  9785. case ttPlus: op = "opAdd"; op_r = "opAdd_r"; break;
  9786. case ttMinus: op = "opSub"; op_r = "opSub_r"; break;
  9787. case ttStar: op = "opMul"; op_r = "opMul_r"; break;
  9788. case ttSlash: op = "opDiv"; op_r = "opDiv_r"; break;
  9789. case ttPercent: op = "opMod"; op_r = "opMod_r"; break;
  9790. case ttStarStar: op = "opPow"; op_r = "opPow_r"; break;
  9791. case ttBitOr: op = "opOr"; op_r = "opOr_r"; break;
  9792. case ttAmp: op = "opAnd"; op_r = "opAnd_r"; break;
  9793. case ttBitXor: op = "opXor"; op_r = "opXor_r"; break;
  9794. case ttBitShiftLeft: op = "opShl"; op_r = "opShl_r"; break;
  9795. case ttBitShiftRight: op = "opShr"; op_r = "opShr_r"; break;
  9796. case ttBitShiftRightArith: op = "opUShr"; op_r = "opUShr_r"; break;
  9797. }
  9798. // TODO: Might be interesting to support a concatenation operator, e.g. ~
  9799. if( op && op_r )
  9800. {
  9801. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  9802. // Find the matching operator method
  9803. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  9804. if( r == 0 )
  9805. {
  9806. // Try again by switching the order of the operands, and using the reversed operator
  9807. r = CompileOverloadedDualOperator2(node, op_r, rctx, lctx, ctx);
  9808. }
  9809. if( r == 1 )
  9810. {
  9811. // Success, don't continue
  9812. return true;
  9813. }
  9814. else if( r < 0 )
  9815. {
  9816. // Compiler error, don't continue
  9817. ctx->type.SetDummy();
  9818. return true;
  9819. }
  9820. }
  9821. // Assignment operators
  9822. op = 0;
  9823. if( isHandle )
  9824. {
  9825. // Only asOBJ_ASHANDLE types can get here
  9826. asASSERT( lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) );
  9827. asASSERT( token == ttAssignment );
  9828. if( token == ttAssignment )
  9829. op = "opHndlAssign";
  9830. }
  9831. else
  9832. {
  9833. switch( token )
  9834. {
  9835. case ttAssignment: op = "opAssign"; break;
  9836. case ttAddAssign: op = "opAddAssign"; break;
  9837. case ttSubAssign: op = "opSubAssign"; break;
  9838. case ttMulAssign: op = "opMulAssign"; break;
  9839. case ttDivAssign: op = "opDivAssign"; break;
  9840. case ttModAssign: op = "opModAssign"; break;
  9841. case ttPowAssign: op = "opPowAssign"; break;
  9842. case ttOrAssign: op = "opOrAssign"; break;
  9843. case ttAndAssign: op = "opAndAssign"; break;
  9844. case ttXorAssign: op = "opXorAssign"; break;
  9845. case ttShiftLeftAssign: op = "opShlAssign"; break;
  9846. case ttShiftRightLAssign: op = "opShrAssign"; break;
  9847. case ttShiftRightAAssign: op = "opUShrAssign"; break;
  9848. }
  9849. }
  9850. if( op )
  9851. {
  9852. if( builder->engine->ep.disallowValueAssignForRefType &&
  9853. lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_REF) && !(lctx->type.dataType.GetObjectType()->flags & asOBJ_SCOPED) )
  9854. {
  9855. if( token == ttAssignment )
  9856. Error(TXT_DISALLOW_ASSIGN_ON_REF_TYPE, node);
  9857. else
  9858. Error(TXT_DISALLOW_COMPOUND_ASSIGN_ON_REF_TYPE, node);
  9859. // Set a dummy output
  9860. ctx->type.Set(lctx->type.dataType);
  9861. return true;
  9862. }
  9863. // TODO: Shouldn't accept const lvalue with the assignment operators
  9864. // Find the matching operator method
  9865. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  9866. if( r == 1 )
  9867. {
  9868. // Success, don't continue
  9869. return true;
  9870. }
  9871. else if( r < 0 )
  9872. {
  9873. // Compiler error, don't continue
  9874. ctx->type.SetDummy();
  9875. return true;
  9876. }
  9877. }
  9878. // No suitable operator was found
  9879. return false;
  9880. }
  9881. // Returns negative on compile error
  9882. // zero on no matching operator
  9883. // one on matching operator
  9884. int asCCompiler::CompileOverloadedDualOperator2(asCScriptNode *node, const char *methodName, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx, bool specificReturn, const asCDataType &returnType)
  9885. {
  9886. // Find the matching method
  9887. if( lctx->type.dataType.IsObject() &&
  9888. (!lctx->type.isExplicitHandle ||
  9889. lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  9890. {
  9891. asUINT n;
  9892. // Is the left value a const?
  9893. bool isConst = lctx->type.dataType.IsObjectConst();
  9894. asCArray<int> funcs;
  9895. asCObjectType *ot = lctx->type.dataType.GetObjectType();
  9896. for( n = 0; n < ot->methods.GetLength(); n++ )
  9897. {
  9898. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  9899. asASSERT( func );
  9900. if( func && func->name == methodName &&
  9901. (!specificReturn || func->returnType == returnType) &&
  9902. func->parameterTypes.GetLength() == 1 &&
  9903. (!isConst || func->isReadOnly) )
  9904. {
  9905. // Make sure the method is accessible by the module
  9906. if( builder->module->accessMask & func->accessMask )
  9907. {
  9908. funcs.PushLast(func->id);
  9909. }
  9910. }
  9911. }
  9912. // Which is the best matching function?
  9913. asCArray<asSOverloadCandidate> tempFuncs;
  9914. MatchArgument(funcs, tempFuncs, rctx, 0);
  9915. // Find the lowest cost operator(s)
  9916. asCArray<int> ops;
  9917. asUINT bestCost = asUINT(-1);
  9918. for( n = 0; n < tempFuncs.GetLength(); ++n )
  9919. {
  9920. asUINT cost = tempFuncs[n].cost;
  9921. if( cost < bestCost )
  9922. {
  9923. ops.SetLength(0);
  9924. bestCost = cost;
  9925. }
  9926. if( cost == bestCost )
  9927. ops.PushLast(tempFuncs[n].funcId);
  9928. }
  9929. // If the object is not const, then we need to prioritize non-const methods
  9930. if( !isConst )
  9931. FilterConst(ops);
  9932. // Did we find an operator?
  9933. if( ops.GetLength() == 1 )
  9934. {
  9935. // Process the lctx expression as get accessor
  9936. ProcessPropertyGetAccessor(lctx, node);
  9937. // Make sure the rvalue doesn't have deferred temporary variables that are also used in the lvalue,
  9938. // since that would cause the VM to overwrite the variable while executing the bytecode for the lvalue.
  9939. asCArray<int> usedVars;
  9940. lctx->bc.GetVarsUsed(usedVars);
  9941. size_t oldReservedVars = reservedVariables.GetLength();
  9942. for( asUINT n = 0; n < rctx->deferredParams.GetLength(); n++ )
  9943. {
  9944. if( usedVars.Exists(rctx->deferredParams[n].argType.stackOffset) )
  9945. {
  9946. if( reservedVariables.GetLength() == oldReservedVars )
  9947. reservedVariables.Concatenate(usedVars);
  9948. // Allocate a new variable for the deferred argument
  9949. int offset = AllocateVariableNotIn(rctx->deferredParams[n].argType.dataType, true, false, rctx);
  9950. int oldVar = rctx->deferredParams[n].argType.stackOffset;
  9951. rctx->deferredParams[n].argType.stackOffset = short(offset);
  9952. rctx->bc.ExchangeVar(oldVar, offset);
  9953. ReleaseTemporaryVariable(oldVar, 0);
  9954. }
  9955. }
  9956. reservedVariables.SetLength(oldReservedVars);
  9957. // Merge the bytecode so that it forms lvalue.methodName(rvalue)
  9958. asCArray<asSExprContext *> args;
  9959. args.PushLast(rctx);
  9960. MergeExprBytecode(ctx, lctx);
  9961. ctx->type = lctx->type;
  9962. MakeFunctionCall(ctx, ops[0], ctx->type.dataType.GetObjectType(), args, node);
  9963. // Found matching operator
  9964. return 1;
  9965. }
  9966. else if( ops.GetLength() > 1 )
  9967. {
  9968. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  9969. PrintMatchingFuncs(ops, node);
  9970. ctx->type.SetDummy();
  9971. // Compiler error
  9972. return -1;
  9973. }
  9974. }
  9975. // No matching operator
  9976. return 0;
  9977. }
  9978. void asCCompiler::MakeFunctionCall(asSExprContext *ctx, int funcId, asCObjectType *objectType, asCArray<asSExprContext*> &args, asCScriptNode * /*node*/, bool useVariable, int stackOffset, int funcPtrVar)
  9979. {
  9980. if( objectType )
  9981. {
  9982. Dereference(ctx, true);
  9983. // This following warning was removed as there may be valid reasons
  9984. // for calling non-const methods on temporary objects, and we shouldn't
  9985. // warn when there is no way of removing the warning.
  9986. /*
  9987. // Warn if the method is non-const and the object is temporary
  9988. // since the changes will be lost when the object is destroyed.
  9989. // If the object is accessed through a handle, then it is assumed
  9990. // the object is not temporary, even though the handle is.
  9991. if( ctx->type.isTemporary &&
  9992. !ctx->type.dataType.IsObjectHandle() &&
  9993. !engine->scriptFunctions[funcId]->isReadOnly )
  9994. {
  9995. Warning("A non-const method is called on temporary object. Changes to the object may be lost.", node);
  9996. Information(engine->scriptFunctions[funcId]->GetDeclaration(), node);
  9997. }
  9998. */ }
  9999. asCByteCode objBC(engine);
  10000. objBC.AddCode(&ctx->bc);
  10001. PrepareFunctionCall(funcId, &ctx->bc, args);
  10002. // Verify if any of the args variable offsets are used in the other code.
  10003. // If they are exchange the offset for a new one
  10004. asUINT n;
  10005. for( n = 0; n < args.GetLength(); n++ )
  10006. {
  10007. if( args[n]->type.isTemporary && objBC.IsVarUsed(args[n]->type.stackOffset) )
  10008. {
  10009. // Release the current temporary variable
  10010. ReleaseTemporaryVariable(args[n]->type, 0);
  10011. asCDataType dt = args[n]->type.dataType;
  10012. dt.MakeReference(false);
  10013. int l = int(reservedVariables.GetLength());
  10014. objBC.GetVarsUsed(reservedVariables);
  10015. ctx->bc.GetVarsUsed(reservedVariables);
  10016. int newOffset = AllocateVariable(dt, true, IsVariableOnHeap(args[n]->type.stackOffset));
  10017. reservedVariables.SetLength(l);
  10018. asASSERT( IsVariableOnHeap(args[n]->type.stackOffset) == IsVariableOnHeap(newOffset) );
  10019. ctx->bc.ExchangeVar(args[n]->type.stackOffset, newOffset);
  10020. args[n]->type.stackOffset = (short)newOffset;
  10021. args[n]->type.isTemporary = true;
  10022. args[n]->type.isVariable = true;
  10023. }
  10024. }
  10025. // If the function will return a value type on the stack, then we must allocate space
  10026. // for that here and push the address on the stack as a hidden argument to the function
  10027. asCScriptFunction *func = builder->GetFunctionDescription(funcId);
  10028. if( func->DoesReturnOnStack() )
  10029. {
  10030. asASSERT(!useVariable);
  10031. useVariable = true;
  10032. stackOffset = AllocateVariable(func->returnType, true);
  10033. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  10034. }
  10035. ctx->bc.AddCode(&objBC);
  10036. MoveArgsToStack(funcId, &ctx->bc, args, objectType ? true : false);
  10037. PerformFunctionCall(funcId, ctx, false, &args, 0, useVariable, stackOffset, funcPtrVar);
  10038. }
  10039. int asCCompiler::CompileOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  10040. {
  10041. // Don't allow any operators on expressions that take address of class method, but allow it on global functions
  10042. if( (lctx->IsClassMethod()) || (rctx->IsClassMethod()) )
  10043. {
  10044. Error(TXT_INVALID_OP_ON_METHOD, node);
  10045. return -1;
  10046. }
  10047. // Don't allow any operators on void expressions
  10048. if( lctx->type.IsVoidExpression() || rctx->type.IsVoidExpression() )
  10049. {
  10050. Error(TXT_VOID_CANT_BE_OPERAND, node);
  10051. return -1;
  10052. }
  10053. IsVariableInitialized(&lctx->type, node);
  10054. IsVariableInitialized(&rctx->type, node);
  10055. if( lctx->type.isExplicitHandle || rctx->type.isExplicitHandle ||
  10056. lctx->type.IsNullConstant() || rctx->type.IsNullConstant() ||
  10057. node->tokenType == ttIs || node->tokenType == ttNotIs )
  10058. {
  10059. CompileOperatorOnHandles(node, lctx, rctx, ctx);
  10060. return 0;
  10061. }
  10062. else
  10063. {
  10064. // Compile an overloaded operator for the two operands
  10065. if( CompileOverloadedDualOperator(node, lctx, rctx, ctx) )
  10066. return 0;
  10067. // If both operands are objects, then we shouldn't continue
  10068. if( lctx->type.dataType.IsObject() && rctx->type.dataType.IsObject() )
  10069. {
  10070. asCString str;
  10071. str.Format(TXT_NO_MATCHING_OP_FOUND_FOR_TYPES_s_AND_s, lctx->type.dataType.Format().AddressOf(), rctx->type.dataType.Format().AddressOf());
  10072. Error(str, node);
  10073. ctx->type.SetDummy();
  10074. return -1;
  10075. }
  10076. // Process the property get accessors (if any)
  10077. ProcessPropertyGetAccessor(lctx, node);
  10078. ProcessPropertyGetAccessor(rctx, node);
  10079. // Make sure we have two variables or constants
  10080. if( lctx->type.dataType.IsReference() ) ConvertToVariableNotIn(lctx, rctx);
  10081. if( rctx->type.dataType.IsReference() ) ConvertToVariableNotIn(rctx, lctx);
  10082. // Make sure lctx doesn't end up with a variable used in rctx
  10083. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  10084. {
  10085. int offset = AllocateVariableNotIn(lctx->type.dataType, true, false, rctx);
  10086. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  10087. ReleaseTemporaryVariable(offset, 0);
  10088. }
  10089. // Math operators
  10090. // + - * / % ** += -= *= /= %= **=
  10091. int op = node->tokenType;
  10092. if( op == ttPlus || op == ttAddAssign ||
  10093. op == ttMinus || op == ttSubAssign ||
  10094. op == ttStar || op == ttMulAssign ||
  10095. op == ttSlash || op == ttDivAssign ||
  10096. op == ttPercent || op == ttModAssign ||
  10097. op == ttStarStar || op == ttPowAssign )
  10098. {
  10099. CompileMathOperator(node, lctx, rctx, ctx);
  10100. return 0;
  10101. }
  10102. // Bitwise operators
  10103. // << >> >>> & | ^ <<= >>= >>>= &= |= ^=
  10104. if( op == ttAmp || op == ttAndAssign ||
  10105. op == ttBitOr || op == ttOrAssign ||
  10106. op == ttBitXor || op == ttXorAssign ||
  10107. op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  10108. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  10109. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  10110. {
  10111. CompileBitwiseOperator(node, lctx, rctx, ctx);
  10112. return 0;
  10113. }
  10114. // Comparison operators
  10115. // == != < > <= >=
  10116. if( op == ttEqual || op == ttNotEqual ||
  10117. op == ttLessThan || op == ttLessThanOrEqual ||
  10118. op == ttGreaterThan || op == ttGreaterThanOrEqual )
  10119. {
  10120. CompileComparisonOperator(node, lctx, rctx, ctx);
  10121. return 0;
  10122. }
  10123. // Boolean operators
  10124. // && || ^^
  10125. if( op == ttAnd || op == ttOr || op == ttXor )
  10126. {
  10127. CompileBooleanOperator(node, lctx, rctx, ctx);
  10128. return 0;
  10129. }
  10130. }
  10131. asASSERT(false);
  10132. return -1;
  10133. }
  10134. void asCCompiler::ConvertToTempVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  10135. {
  10136. int l = int(reservedVariables.GetLength());
  10137. if( exclude ) exclude->bc.GetVarsUsed(reservedVariables);
  10138. ConvertToTempVariable(ctx);
  10139. reservedVariables.SetLength(l);
  10140. }
  10141. void asCCompiler::ConvertToTempVariable(asSExprContext *ctx)
  10142. {
  10143. // This is only used for primitive types and null handles
  10144. asASSERT( ctx->type.dataType.IsPrimitive() || ctx->type.dataType.IsNullHandle() );
  10145. ConvertToVariable(ctx);
  10146. if( !ctx->type.isTemporary )
  10147. {
  10148. if( ctx->type.dataType.IsPrimitive() )
  10149. {
  10150. // Copy the variable to a temporary variable
  10151. int offset = AllocateVariable(ctx->type.dataType, true);
  10152. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10153. ctx->bc.InstrW_W(asBC_CpyVtoV4, offset, ctx->type.stackOffset);
  10154. else
  10155. ctx->bc.InstrW_W(asBC_CpyVtoV8, offset, ctx->type.stackOffset);
  10156. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  10157. }
  10158. else
  10159. {
  10160. // We should never get here
  10161. asASSERT(false);
  10162. }
  10163. }
  10164. }
  10165. void asCCompiler::ConvertToVariable(asSExprContext *ctx)
  10166. {
  10167. // We should never get here while the context is still an unprocessed property accessor
  10168. asASSERT(ctx->property_get == 0 && ctx->property_set == 0);
  10169. int offset;
  10170. if( !ctx->type.isVariable &&
  10171. (ctx->type.dataType.IsObjectHandle() ||
  10172. (ctx->type.dataType.IsObject() && ctx->type.dataType.SupportHandles())) )
  10173. {
  10174. offset = AllocateVariable(ctx->type.dataType, true);
  10175. if( ctx->type.IsNullConstant() )
  10176. {
  10177. if( ctx->bc.GetLastInstr() == asBC_PshNull )
  10178. ctx->bc.Instr(asBC_PopPtr); // Pop the null constant pushed onto the stack
  10179. ctx->bc.InstrSHORT(asBC_ClrVPtr, (short)offset);
  10180. }
  10181. else
  10182. {
  10183. Dereference(ctx, true);
  10184. // Copy the object handle to a variable
  10185. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  10186. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  10187. ctx->bc.Instr(asBC_PopPtr);
  10188. }
  10189. // As this is an object the reference must be placed on the stack
  10190. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  10191. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  10192. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  10193. ctx->type.dataType.MakeHandle(true);
  10194. ctx->type.dataType.MakeReference(true);
  10195. }
  10196. else if( (!ctx->type.isVariable || ctx->type.dataType.IsReference()) &&
  10197. ctx->type.dataType.IsPrimitive() )
  10198. {
  10199. if( ctx->type.isConstant )
  10200. {
  10201. offset = AllocateVariable(ctx->type.dataType, true);
  10202. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  10203. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, ctx->type.byteValue);
  10204. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  10205. ctx->bc.InstrSHORT_W(asBC_SetV2, (short)offset, ctx->type.wordValue);
  10206. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  10207. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, ctx->type.dwordValue);
  10208. else
  10209. ctx->bc.InstrSHORT_QW(asBC_SetV8, (short)offset, ctx->type.qwordValue);
  10210. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  10211. return;
  10212. }
  10213. else
  10214. {
  10215. asASSERT(ctx->type.dataType.IsPrimitive());
  10216. asASSERT(ctx->type.dataType.IsReference());
  10217. ctx->type.dataType.MakeReference(false);
  10218. offset = AllocateVariable(ctx->type.dataType, true);
  10219. // Read the value from the address in the register directly into the variable
  10220. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  10221. ctx->bc.InstrSHORT(asBC_RDR1, (short)offset);
  10222. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  10223. ctx->bc.InstrSHORT(asBC_RDR2, (short)offset);
  10224. else if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10225. ctx->bc.InstrSHORT(asBC_RDR4, (short)offset);
  10226. else
  10227. ctx->bc.InstrSHORT(asBC_RDR8, (short)offset);
  10228. }
  10229. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  10230. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  10231. }
  10232. }
  10233. void asCCompiler::ConvertToVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  10234. {
  10235. int l = int(reservedVariables.GetLength());
  10236. if( exclude ) exclude->bc.GetVarsUsed(reservedVariables);
  10237. ConvertToVariable(ctx);
  10238. reservedVariables.SetLength(l);
  10239. }
  10240. void asCCompiler::ImplicitConvObjectToBestMathType(asSExprContext *ctx, asCScriptNode *node)
  10241. {
  10242. asCArray<int> funcs;
  10243. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  10244. if( beh )
  10245. {
  10246. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  10247. {
  10248. // Consider only implicit casts
  10249. // TODO: 2.29.0: Look for opImplConv methods instead
  10250. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  10251. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  10252. funcs.PushLast(beh->operators[n+1]);
  10253. }
  10254. // Use the one with the highest precision
  10255. const eTokenType match[10] = {ttDouble, ttFloat, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8};
  10256. while( funcs.GetLength() > 1 )
  10257. {
  10258. eTokenType returnType = builder->GetFunctionDescription(funcs[0])->returnType.GetTokenType();
  10259. int value1 = 11, value2 = 11;
  10260. for( asUINT i = 0; i < 10; i++ )
  10261. {
  10262. if( returnType == match[i] )
  10263. {
  10264. value1 = i;
  10265. break;
  10266. }
  10267. }
  10268. for( asUINT n = 1; n < funcs.GetLength(); n++ )
  10269. {
  10270. returnType = builder->GetFunctionDescription(funcs[n])->returnType.GetTokenType();
  10271. for( asUINT i = 0; i < 10; i++ )
  10272. {
  10273. if( returnType == match[i] )
  10274. {
  10275. value2 = i;
  10276. break;
  10277. }
  10278. }
  10279. if( value2 >= value1 )
  10280. {
  10281. // Remove this and continue searching
  10282. funcs.RemoveIndexUnordered(n--);
  10283. }
  10284. else
  10285. {
  10286. // Remove the first, and start over
  10287. funcs.RemoveIndexUnordered(0);
  10288. break;
  10289. }
  10290. }
  10291. }
  10292. // Do the conversion
  10293. if( funcs.GetLength() )
  10294. ImplicitConvObjectToPrimitive(ctx, builder->GetFunctionDescription(funcs[0])->returnType, node, asIC_IMPLICIT_CONV);
  10295. }
  10296. }
  10297. void asCCompiler::CompileMathOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  10298. {
  10299. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  10300. // TODO: clean up: This initial part is identical to CompileComparisonOperator. Make a common function out of it
  10301. // If either operand is a non-primitive then use the primitive type
  10302. if( !lctx->type.dataType.IsPrimitive() )
  10303. ImplicitConvObjectToBestMathType(lctx, node);
  10304. if( !rctx->type.dataType.IsPrimitive() )
  10305. ImplicitConvObjectToBestMathType(rctx, node);
  10306. // Both types must now be primitives. Implicitly convert them so they match
  10307. asCDataType to;
  10308. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  10309. to.SetTokenType(ttDouble);
  10310. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  10311. to.SetTokenType(ttFloat);
  10312. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  10313. {
  10314. // Convert to int64 if both are signed or if one is non-constant and signed
  10315. if( (lctx->type.dataType.IsIntegerType() && !lctx->type.isConstant) ||
  10316. (rctx->type.dataType.IsIntegerType() && !rctx->type.isConstant) )
  10317. to.SetTokenType(ttInt64);
  10318. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  10319. to.SetTokenType(ttUInt64);
  10320. else
  10321. to.SetTokenType(ttInt64);
  10322. }
  10323. else
  10324. {
  10325. // Convert to int32 if both are signed or if one is non-constant and signed
  10326. if( (lctx->type.dataType.IsIntegerType() && !lctx->type.isConstant) ||
  10327. (rctx->type.dataType.IsIntegerType() && !rctx->type.isConstant) )
  10328. to.SetTokenType(ttInt);
  10329. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  10330. to.SetTokenType(ttUInt);
  10331. else
  10332. to.SetTokenType(ttInt);
  10333. }
  10334. // If doing an operation with double constant and float variable, the constant should be converted to float
  10335. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  10336. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  10337. to.SetTokenType(ttFloat);
  10338. // Do the actual conversion
  10339. int l = int(reservedVariables.GetLength());
  10340. rctx->bc.GetVarsUsed(reservedVariables);
  10341. lctx->bc.GetVarsUsed(reservedVariables);
  10342. if( lctx->type.dataType.IsReference() )
  10343. ConvertToVariable(lctx);
  10344. if( rctx->type.dataType.IsReference() )
  10345. ConvertToVariable(rctx);
  10346. int op = node->tokenType;
  10347. if( to.IsPrimitive() )
  10348. {
  10349. // ttStarStar allows an integer, right-hand operand and a double
  10350. // left-hand operand.
  10351. if( (op == ttStarStar || op == ttPowAssign) &&
  10352. lctx->type.dataType.IsDoubleType() &&
  10353. (rctx->type.dataType.IsIntegerType() ||
  10354. rctx->type.dataType.IsUnsignedType()) )
  10355. {
  10356. to.SetTokenType(ttInt);
  10357. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true);
  10358. to.SetTokenType(ttDouble);
  10359. }
  10360. else
  10361. {
  10362. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  10363. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true);
  10364. }
  10365. }
  10366. reservedVariables.SetLength(l);
  10367. // Verify that the conversion was successful
  10368. if( !lctx->type.dataType.IsIntegerType() &&
  10369. !lctx->type.dataType.IsUnsignedType() &&
  10370. !lctx->type.dataType.IsFloatType() &&
  10371. !lctx->type.dataType.IsDoubleType() )
  10372. {
  10373. asCString str;
  10374. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, lctx->type.dataType.Format().AddressOf());
  10375. Error(str, node);
  10376. ctx->type.SetDummy();
  10377. return;
  10378. }
  10379. if( !rctx->type.dataType.IsIntegerType() &&
  10380. !rctx->type.dataType.IsUnsignedType() &&
  10381. !rctx->type.dataType.IsFloatType() &&
  10382. !rctx->type.dataType.IsDoubleType() )
  10383. {
  10384. asCString str;
  10385. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, rctx->type.dataType.Format().AddressOf());
  10386. Error(str, node);
  10387. ctx->type.SetDummy();
  10388. return;
  10389. }
  10390. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  10391. // Verify if we are dividing with a constant zero
  10392. if( rctx->type.isConstant && rctx->type.qwordValue == 0 &&
  10393. (op == ttSlash || op == ttDivAssign ||
  10394. op == ttPercent || op == ttModAssign) )
  10395. {
  10396. Error(TXT_DIVIDE_BY_ZERO, node);
  10397. }
  10398. if( !isConstant )
  10399. {
  10400. ConvertToVariableNotIn(lctx, rctx);
  10401. ConvertToVariableNotIn(rctx, lctx);
  10402. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  10403. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  10404. if( op == ttAddAssign || op == ttSubAssign ||
  10405. op == ttMulAssign || op == ttDivAssign ||
  10406. op == ttModAssign || op == ttPowAssign )
  10407. {
  10408. // Merge the operands in the different order so that they are evaluated correctly
  10409. MergeExprBytecode(ctx, rctx);
  10410. MergeExprBytecode(ctx, lctx);
  10411. // We must not process the deferred parameters yet, as
  10412. // it may overwrite the lvalue kept in the register
  10413. }
  10414. else
  10415. {
  10416. MergeExprBytecode(ctx, lctx);
  10417. MergeExprBytecode(ctx, rctx);
  10418. ProcessDeferredParams(ctx);
  10419. }
  10420. asEBCInstr instruction = asBC_ADDi;
  10421. if( lctx->type.dataType.IsIntegerType() ||
  10422. lctx->type.dataType.IsUnsignedType() )
  10423. {
  10424. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10425. {
  10426. if( op == ttPlus || op == ttAddAssign )
  10427. instruction = asBC_ADDi;
  10428. else if( op == ttMinus || op == ttSubAssign )
  10429. instruction = asBC_SUBi;
  10430. else if( op == ttStar || op == ttMulAssign )
  10431. instruction = asBC_MULi;
  10432. else if( op == ttSlash || op == ttDivAssign )
  10433. {
  10434. if( lctx->type.dataType.IsIntegerType() )
  10435. instruction = asBC_DIVi;
  10436. else
  10437. instruction = asBC_DIVu;
  10438. }
  10439. else if( op == ttPercent || op == ttModAssign )
  10440. {
  10441. if( lctx->type.dataType.IsIntegerType() )
  10442. instruction = asBC_MODi;
  10443. else
  10444. instruction = asBC_MODu;
  10445. }
  10446. else if( op == ttStarStar || op == ttPowAssign )
  10447. {
  10448. if( lctx->type.dataType.IsIntegerType() )
  10449. instruction = asBC_POWi;
  10450. else
  10451. instruction = asBC_POWu;
  10452. }
  10453. }
  10454. else
  10455. {
  10456. if( op == ttPlus || op == ttAddAssign )
  10457. instruction = asBC_ADDi64;
  10458. else if( op == ttMinus || op == ttSubAssign )
  10459. instruction = asBC_SUBi64;
  10460. else if( op == ttStar || op == ttMulAssign )
  10461. instruction = asBC_MULi64;
  10462. else if( op == ttSlash || op == ttDivAssign )
  10463. {
  10464. if( lctx->type.dataType.IsIntegerType() )
  10465. instruction = asBC_DIVi64;
  10466. else
  10467. instruction = asBC_DIVu64;
  10468. }
  10469. else if( op == ttPercent || op == ttModAssign )
  10470. {
  10471. if( lctx->type.dataType.IsIntegerType() )
  10472. instruction = asBC_MODi64;
  10473. else
  10474. instruction = asBC_MODu64;
  10475. }
  10476. else if( op == ttStarStar || op == ttPowAssign )
  10477. {
  10478. if( lctx->type.dataType.IsIntegerType() )
  10479. instruction = asBC_POWi64;
  10480. else
  10481. instruction = asBC_POWu64;
  10482. }
  10483. }
  10484. }
  10485. else if( lctx->type.dataType.IsFloatType() )
  10486. {
  10487. if( op == ttPlus || op == ttAddAssign )
  10488. instruction = asBC_ADDf;
  10489. else if( op == ttMinus || op == ttSubAssign )
  10490. instruction = asBC_SUBf;
  10491. else if( op == ttStar || op == ttMulAssign )
  10492. instruction = asBC_MULf;
  10493. else if( op == ttSlash || op == ttDivAssign )
  10494. instruction = asBC_DIVf;
  10495. else if( op == ttPercent || op == ttModAssign )
  10496. instruction = asBC_MODf;
  10497. else if( op == ttStarStar || op == ttPowAssign )
  10498. instruction = asBC_POWf;
  10499. }
  10500. else if( lctx->type.dataType.IsDoubleType() )
  10501. {
  10502. if( rctx->type.dataType.IsIntegerType() )
  10503. {
  10504. asASSERT(rctx->type.dataType.GetSizeInMemoryDWords() == 1);
  10505. if( op == ttStarStar || op == ttPowAssign )
  10506. instruction = asBC_POWdi;
  10507. else
  10508. asASSERT(false); // Should not be possible
  10509. }
  10510. else
  10511. {
  10512. if( op == ttPlus || op == ttAddAssign )
  10513. instruction = asBC_ADDd;
  10514. else if( op == ttMinus || op == ttSubAssign )
  10515. instruction = asBC_SUBd;
  10516. else if( op == ttStar || op == ttMulAssign )
  10517. instruction = asBC_MULd;
  10518. else if( op == ttSlash || op == ttDivAssign )
  10519. instruction = asBC_DIVd;
  10520. else if( op == ttPercent || op == ttModAssign )
  10521. instruction = asBC_MODd;
  10522. else if( op == ttStarStar || op == ttPowAssign )
  10523. instruction = asBC_POWd;
  10524. }
  10525. }
  10526. else
  10527. {
  10528. // Shouldn't be possible
  10529. asASSERT(false);
  10530. }
  10531. // Do the operation
  10532. int a = AllocateVariable(lctx->type.dataType, true);
  10533. int b = lctx->type.stackOffset;
  10534. int c = rctx->type.stackOffset;
  10535. ctx->bc.InstrW_W_W(instruction, a, b, c);
  10536. ctx->type.SetVariable(lctx->type.dataType, a, true);
  10537. }
  10538. else
  10539. {
  10540. // Both values are constants
  10541. if( lctx->type.dataType.IsIntegerType() ||
  10542. lctx->type.dataType.IsUnsignedType() )
  10543. {
  10544. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10545. {
  10546. int v = 0;
  10547. if( op == ttPlus )
  10548. v = lctx->type.intValue + rctx->type.intValue;
  10549. else if( op == ttMinus )
  10550. v = lctx->type.intValue - rctx->type.intValue;
  10551. else if( op == ttStar )
  10552. v = lctx->type.intValue * rctx->type.intValue;
  10553. else if( op == ttSlash )
  10554. {
  10555. // TODO: Should probably report an error, rather than silently convert the value to 0
  10556. if( rctx->type.intValue == 0 || (rctx->type.intValue == -1 && lctx->type.dwordValue == 0x80000000) )
  10557. v = 0;
  10558. else
  10559. if( lctx->type.dataType.IsIntegerType() )
  10560. v = lctx->type.intValue / rctx->type.intValue;
  10561. else
  10562. v = lctx->type.dwordValue / rctx->type.dwordValue;
  10563. }
  10564. else if( op == ttPercent )
  10565. {
  10566. // TODO: Should probably report an error, rather than silently convert the value to 0
  10567. if( rctx->type.intValue == 0 || (rctx->type.intValue == -1 && lctx->type.dwordValue == 0x80000000) )
  10568. v = 0;
  10569. else
  10570. if( lctx->type.dataType.IsIntegerType() )
  10571. v = lctx->type.intValue % rctx->type.intValue;
  10572. else
  10573. v = lctx->type.dwordValue % rctx->type.dwordValue;
  10574. }
  10575. else if( op == ttStarStar )
  10576. {
  10577. bool isOverflow;
  10578. if( lctx->type.dataType.IsIntegerType() )
  10579. v = as_powi(lctx->type.intValue, rctx->type.intValue, isOverflow);
  10580. else
  10581. v = as_powu(lctx->type.dwordValue, rctx->type.dwordValue, isOverflow);
  10582. }
  10583. ctx->type.SetConstantDW(lctx->type.dataType, v);
  10584. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  10585. if( lctx->type.dataType.GetTokenType() == ttUInt && op == ttMinus && lctx->type.intValue < rctx->type.intValue )
  10586. ctx->type.dataType.SetTokenType(ttInt);
  10587. }
  10588. else
  10589. {
  10590. asQWORD v = 0;
  10591. if( op == ttPlus )
  10592. v = lctx->type.qwordValue + rctx->type.qwordValue;
  10593. else if( op == ttMinus )
  10594. v = lctx->type.qwordValue - rctx->type.qwordValue;
  10595. else if( op == ttStar )
  10596. v = lctx->type.qwordValue * rctx->type.qwordValue;
  10597. else if( op == ttSlash )
  10598. {
  10599. // TODO: Should probably report an error, rather than silently convert the value to 0
  10600. if( rctx->type.qwordValue == 0 || (rctx->type.qwordValue == asQWORD(-1) && lctx->type.qwordValue == (asQWORD(1)<<63)) )
  10601. v = 0;
  10602. else
  10603. if( lctx->type.dataType.IsIntegerType() )
  10604. v = asINT64(lctx->type.qwordValue) / asINT64(rctx->type.qwordValue);
  10605. else
  10606. v = lctx->type.qwordValue / rctx->type.qwordValue;
  10607. }
  10608. else if( op == ttPercent )
  10609. {
  10610. // TODO: Should probably report an error, rather than silently convert the value to 0
  10611. if( rctx->type.qwordValue == 0 || (rctx->type.qwordValue == asQWORD(-1) && lctx->type.qwordValue == (asQWORD(1)<<63)) )
  10612. v = 0;
  10613. else
  10614. if( lctx->type.dataType.IsIntegerType() )
  10615. v = asINT64(lctx->type.qwordValue) % asINT64(rctx->type.qwordValue);
  10616. else
  10617. v = lctx->type.qwordValue % rctx->type.qwordValue;
  10618. }
  10619. else if( op == ttStarStar )
  10620. {
  10621. bool isOverflow;
  10622. if( lctx->type.dataType.IsIntegerType() )
  10623. v = as_powi64(asINT64(lctx->type.qwordValue), asINT64(rctx->type.qwordValue), isOverflow);
  10624. else
  10625. v = as_powu64(lctx->type.qwordValue, rctx->type.qwordValue, isOverflow);
  10626. }
  10627. ctx->type.SetConstantQW(lctx->type.dataType, v);
  10628. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  10629. if( lctx->type.dataType.GetTokenType() == ttUInt64 && op == ttMinus && lctx->type.qwordValue < rctx->type.qwordValue )
  10630. ctx->type.dataType.SetTokenType(ttInt64);
  10631. }
  10632. }
  10633. else if( lctx->type.dataType.IsFloatType() )
  10634. {
  10635. float v = 0.0f;
  10636. if( op == ttPlus )
  10637. v = lctx->type.floatValue + rctx->type.floatValue;
  10638. else if( op == ttMinus )
  10639. v = lctx->type.floatValue - rctx->type.floatValue;
  10640. else if( op == ttStar )
  10641. v = lctx->type.floatValue * rctx->type.floatValue;
  10642. else if( op == ttSlash )
  10643. {
  10644. if( rctx->type.floatValue == 0 )
  10645. v = 0;
  10646. else
  10647. v = lctx->type.floatValue / rctx->type.floatValue;
  10648. }
  10649. else if( op == ttPercent )
  10650. {
  10651. if( rctx->type.floatValue == 0 )
  10652. v = 0;
  10653. else
  10654. v = fmodf(lctx->type.floatValue, rctx->type.floatValue);
  10655. }
  10656. else if( op == ttStarStar )
  10657. v = pow(lctx->type.floatValue, rctx->type.floatValue);
  10658. ctx->type.SetConstantF(lctx->type.dataType, v);
  10659. }
  10660. else if( lctx->type.dataType.IsDoubleType() )
  10661. {
  10662. double v = 0.0;
  10663. if( rctx->type.dataType.IsIntegerType() )
  10664. {
  10665. asASSERT(rctx->type.dataType.GetSizeInMemoryDWords() == 1);
  10666. if( op == ttStarStar || op == ttPowAssign )
  10667. v = pow(lctx->type.doubleValue, rctx->type.intValue);
  10668. else
  10669. asASSERT(false); // Should not be possible
  10670. }
  10671. else
  10672. {
  10673. if( op == ttPlus )
  10674. v = lctx->type.doubleValue + rctx->type.doubleValue;
  10675. else if( op == ttMinus )
  10676. v = lctx->type.doubleValue - rctx->type.doubleValue;
  10677. else if( op == ttStar )
  10678. v = lctx->type.doubleValue * rctx->type.doubleValue;
  10679. else if( op == ttSlash )
  10680. {
  10681. if( rctx->type.doubleValue == 0 )
  10682. v = 0;
  10683. else
  10684. v = lctx->type.doubleValue / rctx->type.doubleValue;
  10685. }
  10686. else if( op == ttPercent )
  10687. {
  10688. if( rctx->type.doubleValue == 0 )
  10689. v = 0;
  10690. else
  10691. v = fmod(lctx->type.doubleValue, rctx->type.doubleValue);
  10692. }
  10693. else if( op == ttStarStar )
  10694. v = pow(lctx->type.doubleValue, rctx->type.doubleValue);
  10695. }
  10696. ctx->type.SetConstantD(lctx->type.dataType, v);
  10697. }
  10698. else
  10699. {
  10700. // Shouldn't be possible
  10701. asASSERT(false);
  10702. }
  10703. }
  10704. }
  10705. void asCCompiler::CompileBitwiseOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  10706. {
  10707. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  10708. eTokenType op = node->tokenType;
  10709. if( op == ttAmp || op == ttAndAssign ||
  10710. op == ttBitOr || op == ttOrAssign ||
  10711. op == ttBitXor || op == ttXorAssign )
  10712. {
  10713. // Convert left hand operand to integer if it's not already one
  10714. asCDataType to;
  10715. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 ||
  10716. rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  10717. to.SetTokenType(ttInt64);
  10718. else
  10719. to.SetTokenType(ttInt);
  10720. // Do the actual conversion (keep sign/unsigned if possible)
  10721. int l = int(reservedVariables.GetLength());
  10722. rctx->bc.GetVarsUsed(reservedVariables);
  10723. if( lctx->type.dataType.IsUnsignedType() )
  10724. to.SetTokenType( to.GetSizeOnStackDWords() == 1 ? ttUInt : ttUInt64 );
  10725. else
  10726. to.SetTokenType( to.GetSizeOnStackDWords() == 1 ? ttInt : ttInt64 );
  10727. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  10728. reservedVariables.SetLength(l);
  10729. // Verify that the conversion was successful
  10730. if( lctx->type.dataType != to )
  10731. {
  10732. asCString str;
  10733. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  10734. Error(str, node);
  10735. }
  10736. // Convert right hand operand to same size as left hand
  10737. l = int(reservedVariables.GetLength());
  10738. lctx->bc.GetVarsUsed(reservedVariables);
  10739. if( rctx->type.dataType.IsUnsignedType() )
  10740. to.SetTokenType( to.GetSizeOnStackDWords() == 1 ? ttUInt : ttUInt64 );
  10741. else
  10742. to.SetTokenType( to.GetSizeOnStackDWords() == 1 ? ttInt : ttInt64 );
  10743. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true);
  10744. reservedVariables.SetLength(l);
  10745. if( rctx->type.dataType != to )
  10746. {
  10747. asCString str;
  10748. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  10749. Error(str, node);
  10750. }
  10751. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  10752. if( !isConstant )
  10753. {
  10754. ConvertToVariableNotIn(lctx, rctx);
  10755. ConvertToVariableNotIn(rctx, lctx);
  10756. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  10757. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  10758. if( op == ttAndAssign || op == ttOrAssign || op == ttXorAssign )
  10759. {
  10760. // Compound assignments execute the right hand value first
  10761. MergeExprBytecode(ctx, rctx);
  10762. MergeExprBytecode(ctx, lctx);
  10763. }
  10764. else
  10765. {
  10766. MergeExprBytecode(ctx, lctx);
  10767. MergeExprBytecode(ctx, rctx);
  10768. }
  10769. ProcessDeferredParams(ctx);
  10770. asEBCInstr instruction = asBC_BAND;
  10771. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10772. {
  10773. if( op == ttAmp || op == ttAndAssign )
  10774. instruction = asBC_BAND;
  10775. else if( op == ttBitOr || op == ttOrAssign )
  10776. instruction = asBC_BOR;
  10777. else if( op == ttBitXor || op == ttXorAssign )
  10778. instruction = asBC_BXOR;
  10779. }
  10780. else
  10781. {
  10782. if( op == ttAmp || op == ttAndAssign )
  10783. instruction = asBC_BAND64;
  10784. else if( op == ttBitOr || op == ttOrAssign )
  10785. instruction = asBC_BOR64;
  10786. else if( op == ttBitXor || op == ttXorAssign )
  10787. instruction = asBC_BXOR64;
  10788. }
  10789. // Do the operation
  10790. int a = AllocateVariable(lctx->type.dataType, true);
  10791. int b = lctx->type.stackOffset;
  10792. int c = rctx->type.stackOffset;
  10793. ctx->bc.InstrW_W_W(instruction, a, b, c);
  10794. ctx->type.SetVariable(lctx->type.dataType, a, true);
  10795. }
  10796. else
  10797. {
  10798. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  10799. {
  10800. asQWORD v = 0;
  10801. if( op == ttAmp )
  10802. v = lctx->type.qwordValue & rctx->type.qwordValue;
  10803. else if( op == ttBitOr )
  10804. v = lctx->type.qwordValue | rctx->type.qwordValue;
  10805. else if( op == ttBitXor )
  10806. v = lctx->type.qwordValue ^ rctx->type.qwordValue;
  10807. // Remember the result
  10808. ctx->type.SetConstantQW(lctx->type.dataType, v);
  10809. }
  10810. else
  10811. {
  10812. asDWORD v = 0;
  10813. if( op == ttAmp )
  10814. v = lctx->type.dwordValue & rctx->type.dwordValue;
  10815. else if( op == ttBitOr )
  10816. v = lctx->type.dwordValue | rctx->type.dwordValue;
  10817. else if( op == ttBitXor )
  10818. v = lctx->type.dwordValue ^ rctx->type.dwordValue;
  10819. // Remember the result
  10820. ctx->type.SetConstantDW(lctx->type.dataType, v);
  10821. }
  10822. }
  10823. }
  10824. else if( op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  10825. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  10826. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  10827. {
  10828. // Don't permit object to primitive conversion, since we don't know which integer type is the correct one
  10829. if( lctx->type.dataType.IsObject() )
  10830. {
  10831. asCString str;
  10832. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  10833. Error(str, node);
  10834. // Set an integer value and allow the compiler to continue
  10835. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttInt, true), 0);
  10836. return;
  10837. }
  10838. // Convert left hand operand to integer if it's not already one
  10839. asCDataType to = lctx->type.dataType;
  10840. if( lctx->type.dataType.IsUnsignedType() &&
  10841. lctx->type.dataType.GetSizeInMemoryBytes() < 4 )
  10842. {
  10843. to = asCDataType::CreatePrimitive(ttUInt, false);
  10844. }
  10845. else if( !lctx->type.dataType.IsUnsignedType() )
  10846. {
  10847. asCDataType to;
  10848. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  10849. to.SetTokenType(ttInt64);
  10850. else
  10851. to.SetTokenType(ttInt);
  10852. }
  10853. // Do the actual conversion
  10854. int l = int(reservedVariables.GetLength());
  10855. rctx->bc.GetVarsUsed(reservedVariables);
  10856. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  10857. reservedVariables.SetLength(l);
  10858. // Verify that the conversion was successful
  10859. if( lctx->type.dataType != to )
  10860. {
  10861. asCString str;
  10862. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  10863. Error(str, node);
  10864. }
  10865. // Right operand must be 32bit uint
  10866. l = int(reservedVariables.GetLength());
  10867. lctx->bc.GetVarsUsed(reservedVariables);
  10868. ImplicitConversion(rctx, asCDataType::CreatePrimitive(ttUInt, true), node, asIC_IMPLICIT_CONV, true);
  10869. reservedVariables.SetLength(l);
  10870. if( !rctx->type.dataType.IsUnsignedType() )
  10871. {
  10872. asCString str;
  10873. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "uint");
  10874. Error(str, node);
  10875. }
  10876. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  10877. if( !isConstant )
  10878. {
  10879. ConvertToVariableNotIn(lctx, rctx);
  10880. ConvertToVariableNotIn(rctx, lctx);
  10881. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  10882. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  10883. if( op == ttShiftLeftAssign || op == ttShiftRightLAssign || op == ttShiftRightAAssign )
  10884. {
  10885. // Compound assignments execute the right hand value first
  10886. MergeExprBytecode(ctx, rctx);
  10887. MergeExprBytecode(ctx, lctx);
  10888. }
  10889. else
  10890. {
  10891. MergeExprBytecode(ctx, lctx);
  10892. MergeExprBytecode(ctx, rctx);
  10893. }
  10894. ProcessDeferredParams(ctx);
  10895. asEBCInstr instruction = asBC_BSLL;
  10896. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10897. {
  10898. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  10899. instruction = asBC_BSLL;
  10900. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  10901. instruction = asBC_BSRL;
  10902. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  10903. instruction = asBC_BSRA;
  10904. }
  10905. else
  10906. {
  10907. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  10908. instruction = asBC_BSLL64;
  10909. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  10910. instruction = asBC_BSRL64;
  10911. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  10912. instruction = asBC_BSRA64;
  10913. }
  10914. // Do the operation
  10915. int a = AllocateVariable(lctx->type.dataType, true);
  10916. int b = lctx->type.stackOffset;
  10917. int c = rctx->type.stackOffset;
  10918. ctx->bc.InstrW_W_W(instruction, a, b, c);
  10919. ctx->type.SetVariable(lctx->type.dataType, a, true);
  10920. }
  10921. else
  10922. {
  10923. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  10924. {
  10925. asDWORD v = 0;
  10926. if( op == ttBitShiftLeft )
  10927. v = lctx->type.dwordValue << rctx->type.dwordValue;
  10928. else if( op == ttBitShiftRight )
  10929. v = lctx->type.dwordValue >> rctx->type.dwordValue;
  10930. else if( op == ttBitShiftRightArith )
  10931. v = lctx->type.intValue >> rctx->type.dwordValue;
  10932. ctx->type.SetConstantDW(lctx->type.dataType, v);
  10933. }
  10934. else
  10935. {
  10936. asQWORD v = 0;
  10937. if( op == ttBitShiftLeft )
  10938. v = lctx->type.qwordValue << rctx->type.dwordValue;
  10939. else if( op == ttBitShiftRight )
  10940. v = lctx->type.qwordValue >> rctx->type.dwordValue;
  10941. else if( op == ttBitShiftRightArith )
  10942. v = asINT64(lctx->type.qwordValue) >> rctx->type.dwordValue;
  10943. ctx->type.SetConstantQW(lctx->type.dataType, v);
  10944. }
  10945. }
  10946. }
  10947. }
  10948. void asCCompiler::CompileComparisonOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  10949. {
  10950. // Both operands must be of the same type
  10951. // If either operand is a non-primitive then first convert them to the best number type
  10952. if( !lctx->type.dataType.IsPrimitive() )
  10953. ImplicitConvObjectToBestMathType(lctx, node);
  10954. if( !rctx->type.dataType.IsPrimitive() )
  10955. ImplicitConvObjectToBestMathType(rctx, node);
  10956. // Implicitly convert the operands to matching types
  10957. asCDataType to;
  10958. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  10959. to.SetTokenType(ttDouble);
  10960. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  10961. to.SetTokenType(ttFloat);
  10962. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  10963. {
  10964. // Convert to int64 if both are signed or if one is non-constant and signed
  10965. if( (lctx->type.dataType.IsIntegerType() && !lctx->type.isConstant) ||
  10966. (rctx->type.dataType.IsIntegerType() && !rctx->type.isConstant) )
  10967. to.SetTokenType(ttInt64);
  10968. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  10969. to.SetTokenType(ttUInt64);
  10970. else
  10971. to.SetTokenType(ttInt64);
  10972. }
  10973. else
  10974. {
  10975. // Convert to int32 if both are signed or if one is non-constant and signed
  10976. if( (lctx->type.dataType.IsIntegerType() && !lctx->type.isConstant) ||
  10977. (rctx->type.dataType.IsIntegerType() && !rctx->type.isConstant) )
  10978. to.SetTokenType(ttInt);
  10979. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  10980. to.SetTokenType(ttUInt);
  10981. else if( lctx->type.dataType.IsBooleanType() || rctx->type.dataType.IsBooleanType() )
  10982. to.SetTokenType(ttBool);
  10983. else
  10984. to.SetTokenType(ttInt);
  10985. }
  10986. // If doing an operation with double constant and float variable, the constant should be converted to float
  10987. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  10988. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  10989. to.SetTokenType(ttFloat);
  10990. asASSERT( to.GetTokenType() != ttUnrecognizedToken );
  10991. // Do we have a mismatch between the sign of the operand?
  10992. bool signMismatch = false;
  10993. for( int n = 0; !signMismatch && n < 2; n++ )
  10994. {
  10995. asSExprContext *op = n ? rctx : lctx;
  10996. if( op->type.dataType.IsUnsignedType() != to.IsUnsignedType() )
  10997. {
  10998. // We have a mismatch, unless the value is a literal constant and the conversion won't affect its value
  10999. signMismatch = true;
  11000. if( op->type.isConstant )
  11001. {
  11002. if( op->type.dataType.GetTokenType() == ttUInt64 || op->type.dataType.GetTokenType() == ttInt64 )
  11003. {
  11004. if( !(op->type.qwordValue & (asQWORD(1)<<63)) )
  11005. signMismatch = false;
  11006. }
  11007. else
  11008. {
  11009. if( !(op->type.dwordValue & (1<<31)) )
  11010. signMismatch = false;
  11011. }
  11012. // It's not necessary to check for floats or double, because if
  11013. // it was then the types for the conversion will never be unsigned
  11014. }
  11015. }
  11016. }
  11017. // Check for signed/unsigned mismatch
  11018. if( signMismatch )
  11019. Warning(TXT_SIGNED_UNSIGNED_MISMATCH, node);
  11020. // Do the actual conversion
  11021. int l = int(reservedVariables.GetLength());
  11022. rctx->bc.GetVarsUsed(reservedVariables);
  11023. if( lctx->type.dataType.IsReference() )
  11024. ConvertToVariable(lctx);
  11025. if( rctx->type.dataType.IsReference() )
  11026. ConvertToVariable(rctx);
  11027. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  11028. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  11029. reservedVariables.SetLength(l);
  11030. // Verify that the conversion was successful
  11031. bool ok = true;
  11032. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  11033. {
  11034. asCString str;
  11035. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  11036. Error(str, node);
  11037. ok = false;
  11038. }
  11039. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  11040. {
  11041. asCString str;
  11042. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  11043. Error(str, node);
  11044. ok = false;
  11045. }
  11046. if( !ok )
  11047. {
  11048. // It wasn't possible to get two valid operands, so we just return
  11049. // a boolean result and let the compiler continue.
  11050. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  11051. return;
  11052. }
  11053. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  11054. int op = node->tokenType;
  11055. if( !isConstant )
  11056. {
  11057. if( to.IsBooleanType() )
  11058. {
  11059. int op = node->tokenType;
  11060. if( op == ttEqual || op == ttNotEqual )
  11061. {
  11062. // Must convert to temporary variable, because we are changing the value before comparison
  11063. ConvertToTempVariableNotIn(lctx, rctx);
  11064. ConvertToTempVariableNotIn(rctx, lctx);
  11065. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  11066. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  11067. // Make sure they are equal if not false
  11068. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  11069. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  11070. MergeExprBytecode(ctx, lctx);
  11071. MergeExprBytecode(ctx, rctx);
  11072. ProcessDeferredParams(ctx);
  11073. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  11074. int b = lctx->type.stackOffset;
  11075. int c = rctx->type.stackOffset;
  11076. if( op == ttEqual )
  11077. {
  11078. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  11079. ctx->bc.Instr(asBC_TZ);
  11080. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  11081. }
  11082. else if( op == ttNotEqual )
  11083. {
  11084. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  11085. ctx->bc.Instr(asBC_TNZ);
  11086. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  11087. }
  11088. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  11089. }
  11090. else
  11091. {
  11092. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  11093. Error(TXT_ILLEGAL_OPERATION, node);
  11094. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 0);
  11095. }
  11096. }
  11097. else
  11098. {
  11099. ConvertToVariableNotIn(lctx, rctx);
  11100. ConvertToVariableNotIn(rctx, lctx);
  11101. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  11102. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  11103. MergeExprBytecode(ctx, lctx);
  11104. MergeExprBytecode(ctx, rctx);
  11105. ProcessDeferredParams(ctx);
  11106. asEBCInstr iCmp = asBC_CMPi, iT = asBC_TZ;
  11107. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  11108. iCmp = asBC_CMPi;
  11109. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  11110. iCmp = asBC_CMPu;
  11111. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  11112. iCmp = asBC_CMPi64;
  11113. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  11114. iCmp = asBC_CMPu64;
  11115. else if( lctx->type.dataType.IsFloatType() )
  11116. iCmp = asBC_CMPf;
  11117. else if( lctx->type.dataType.IsDoubleType() )
  11118. iCmp = asBC_CMPd;
  11119. else
  11120. asASSERT(false);
  11121. if( op == ttEqual )
  11122. iT = asBC_TZ;
  11123. else if( op == ttNotEqual )
  11124. iT = asBC_TNZ;
  11125. else if( op == ttLessThan )
  11126. iT = asBC_TS;
  11127. else if( op == ttLessThanOrEqual )
  11128. iT = asBC_TNP;
  11129. else if( op == ttGreaterThan )
  11130. iT = asBC_TP;
  11131. else if( op == ttGreaterThanOrEqual )
  11132. iT = asBC_TNS;
  11133. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  11134. int b = lctx->type.stackOffset;
  11135. int c = rctx->type.stackOffset;
  11136. ctx->bc.InstrW_W(iCmp, b, c);
  11137. ctx->bc.Instr(iT);
  11138. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  11139. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  11140. }
  11141. }
  11142. else
  11143. {
  11144. if( to.IsBooleanType() )
  11145. {
  11146. int op = node->tokenType;
  11147. if( op == ttEqual || op == ttNotEqual )
  11148. {
  11149. // Make sure they are equal if not false
  11150. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  11151. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  11152. asDWORD v = 0;
  11153. if( op == ttEqual )
  11154. {
  11155. v = lctx->type.intValue - rctx->type.intValue;
  11156. if( v == 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  11157. }
  11158. else if( op == ttNotEqual )
  11159. {
  11160. v = lctx->type.intValue - rctx->type.intValue;
  11161. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  11162. }
  11163. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), v);
  11164. }
  11165. else
  11166. {
  11167. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  11168. Error(TXT_ILLEGAL_OPERATION, node);
  11169. }
  11170. }
  11171. else
  11172. {
  11173. int i = 0;
  11174. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  11175. {
  11176. int v = lctx->type.intValue - rctx->type.intValue;
  11177. if( v < 0 ) i = -1;
  11178. if( v > 0 ) i = 1;
  11179. }
  11180. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  11181. {
  11182. asDWORD v1 = lctx->type.dwordValue;
  11183. asDWORD v2 = rctx->type.dwordValue;
  11184. if( v1 < v2 ) i = -1;
  11185. if( v1 > v2 ) i = 1;
  11186. }
  11187. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  11188. {
  11189. asINT64 v = asINT64(lctx->type.qwordValue) - asINT64(rctx->type.qwordValue);
  11190. if( v < 0 ) i = -1;
  11191. if( v > 0 ) i = 1;
  11192. }
  11193. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  11194. {
  11195. asQWORD v1 = lctx->type.qwordValue;
  11196. asQWORD v2 = rctx->type.qwordValue;
  11197. if( v1 < v2 ) i = -1;
  11198. if( v1 > v2 ) i = 1;
  11199. }
  11200. else if( lctx->type.dataType.IsFloatType() )
  11201. {
  11202. float v = lctx->type.floatValue - rctx->type.floatValue;
  11203. if( v < 0 ) i = -1;
  11204. if( v > 0 ) i = 1;
  11205. }
  11206. else if( lctx->type.dataType.IsDoubleType() )
  11207. {
  11208. double v = lctx->type.doubleValue - rctx->type.doubleValue;
  11209. if( v < 0 ) i = -1;
  11210. if( v > 0 ) i = 1;
  11211. }
  11212. if( op == ttEqual )
  11213. i = (i == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  11214. else if( op == ttNotEqual )
  11215. i = (i != 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  11216. else if( op == ttLessThan )
  11217. i = (i < 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  11218. else if( op == ttLessThanOrEqual )
  11219. i = (i <= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  11220. else if( op == ttGreaterThan )
  11221. i = (i > 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  11222. else if( op == ttGreaterThanOrEqual )
  11223. i = (i >= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  11224. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), i);
  11225. }
  11226. }
  11227. }
  11228. void asCCompiler::PushVariableOnStack(asSExprContext *ctx, bool asReference)
  11229. {
  11230. // Put the result on the stack
  11231. if( asReference )
  11232. {
  11233. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  11234. ctx->type.dataType.MakeReference(true);
  11235. }
  11236. else
  11237. {
  11238. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  11239. ctx->bc.InstrSHORT(asBC_PshV4, ctx->type.stackOffset);
  11240. else
  11241. ctx->bc.InstrSHORT(asBC_PshV8, ctx->type.stackOffset);
  11242. }
  11243. }
  11244. void asCCompiler::CompileBooleanOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  11245. {
  11246. // Both operands must be booleans
  11247. asCDataType to;
  11248. to.SetTokenType(ttBool);
  11249. // Do the actual conversion
  11250. int l = int(reservedVariables.GetLength());
  11251. rctx->bc.GetVarsUsed(reservedVariables);
  11252. lctx->bc.GetVarsUsed(reservedVariables);
  11253. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  11254. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  11255. reservedVariables.SetLength(l);
  11256. // Verify that the conversion was successful
  11257. if( !lctx->type.dataType.IsBooleanType() )
  11258. {
  11259. asCString str;
  11260. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), "bool");
  11261. Error(str, node);
  11262. // Force the conversion to allow compilation to proceed
  11263. lctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  11264. }
  11265. if( !rctx->type.dataType.IsBooleanType() )
  11266. {
  11267. asCString str;
  11268. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "bool");
  11269. Error(str, node);
  11270. // Force the conversion to allow compilation to proceed
  11271. rctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  11272. }
  11273. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  11274. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  11275. // What kind of operator is it?
  11276. int op = node->tokenType;
  11277. if( op == ttXor )
  11278. {
  11279. if( !isConstant )
  11280. {
  11281. // Must convert to temporary variable, because we are changing the value before comparison
  11282. ConvertToTempVariableNotIn(lctx, rctx);
  11283. ConvertToTempVariableNotIn(rctx, lctx);
  11284. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  11285. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  11286. // Make sure they are equal if not false
  11287. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  11288. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  11289. MergeExprBytecode(ctx, lctx);
  11290. MergeExprBytecode(ctx, rctx);
  11291. ProcessDeferredParams(ctx);
  11292. int a = AllocateVariable(ctx->type.dataType, true);
  11293. int b = lctx->type.stackOffset;
  11294. int c = rctx->type.stackOffset;
  11295. ctx->bc.InstrW_W_W(asBC_BXOR,a,b,c);
  11296. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  11297. }
  11298. else
  11299. {
  11300. // Make sure they are equal if not false
  11301. #if AS_SIZEOF_BOOL == 1
  11302. if( lctx->type.byteValue != 0 ) lctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  11303. if( rctx->type.byteValue != 0 ) rctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  11304. asBYTE v = 0;
  11305. v = lctx->type.byteValue - rctx->type.byteValue;
  11306. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  11307. ctx->type.isConstant = true;
  11308. ctx->type.byteValue = v;
  11309. #else
  11310. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  11311. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  11312. asDWORD v = 0;
  11313. v = lctx->type.intValue - rctx->type.intValue;
  11314. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  11315. ctx->type.isConstant = true;
  11316. ctx->type.dwordValue = v;
  11317. #endif
  11318. }
  11319. }
  11320. else if( op == ttAnd ||
  11321. op == ttOr )
  11322. {
  11323. if( !isConstant )
  11324. {
  11325. // If or-operator and first value is 1 the second value shouldn't be calculated
  11326. // if and-operator and first value is 0 the second value shouldn't be calculated
  11327. ConvertToVariable(lctx);
  11328. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  11329. MergeExprBytecode(ctx, lctx);
  11330. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  11331. int label1 = nextLabel++;
  11332. int label2 = nextLabel++;
  11333. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  11334. ctx->bc.Instr(asBC_ClrHi);
  11335. if( op == ttAnd )
  11336. {
  11337. ctx->bc.InstrDWORD(asBC_JNZ, label1);
  11338. ctx->bc.InstrW_DW(asBC_SetV4, (asWORD)offset, 0);
  11339. ctx->bc.InstrINT(asBC_JMP, label2);
  11340. }
  11341. else if( op == ttOr )
  11342. {
  11343. ctx->bc.InstrDWORD(asBC_JZ, label1);
  11344. #if AS_SIZEOF_BOOL == 1
  11345. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  11346. #else
  11347. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  11348. #endif
  11349. ctx->bc.InstrINT(asBC_JMP, label2);
  11350. }
  11351. ctx->bc.Label((short)label1);
  11352. ConvertToVariable(rctx);
  11353. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  11354. rctx->bc.InstrW_W(asBC_CpyVtoV4, offset, rctx->type.stackOffset);
  11355. MergeExprBytecode(ctx, rctx);
  11356. ctx->bc.Label((short)label2);
  11357. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), offset, true);
  11358. }
  11359. else
  11360. {
  11361. #if AS_SIZEOF_BOOL == 1
  11362. asBYTE v = 0;
  11363. if( op == ttAnd )
  11364. v = lctx->type.byteValue && rctx->type.byteValue;
  11365. else if( op == ttOr )
  11366. v = lctx->type.byteValue || rctx->type.byteValue;
  11367. // Remember the result
  11368. ctx->type.isConstant = true;
  11369. ctx->type.byteValue = v;
  11370. #else
  11371. asDWORD v = 0;
  11372. if( op == ttAnd )
  11373. v = lctx->type.dwordValue && rctx->type.dwordValue;
  11374. else if( op == ttOr )
  11375. v = lctx->type.dwordValue || rctx->type.dwordValue;
  11376. // Remember the result
  11377. ctx->type.isConstant = true;
  11378. ctx->type.dwordValue = v;
  11379. #endif
  11380. }
  11381. }
  11382. }
  11383. void asCCompiler::CompileOperatorOnHandles(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  11384. {
  11385. // Process the property accessor as get
  11386. ProcessPropertyGetAccessor(lctx, node);
  11387. ProcessPropertyGetAccessor(rctx, node);
  11388. DetermineSingleFunc(lctx, node);
  11389. DetermineSingleFunc(rctx, node);
  11390. // Make sure lctx doesn't end up with a variable used in rctx
  11391. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  11392. {
  11393. asCArray<int> vars;
  11394. rctx->bc.GetVarsUsed(vars);
  11395. int offset = AllocateVariable(lctx->type.dataType, true);
  11396. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  11397. ReleaseTemporaryVariable(offset, 0);
  11398. }
  11399. // Warn if not both operands are explicit handles or null handles
  11400. if( (node->tokenType == ttEqual || node->tokenType == ttNotEqual) &&
  11401. ((!(lctx->type.isExplicitHandle || lctx->type.IsNullConstant()) && !(lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE))) ||
  11402. (!(rctx->type.isExplicitHandle || rctx->type.IsNullConstant()) && !(rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE)))) )
  11403. {
  11404. Warning(TXT_HANDLE_COMPARISON, node);
  11405. }
  11406. // If one of the operands is a value type used as handle, we should look for the opEquals method
  11407. if( ((lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) ||
  11408. (rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE))) &&
  11409. (node->tokenType == ttEqual || node->tokenType == ttIs ||
  11410. node->tokenType == ttNotEqual || node->tokenType == ttNotIs) )
  11411. {
  11412. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  11413. // Find the matching opEquals method
  11414. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  11415. if( r == 0 )
  11416. {
  11417. // Try again by switching the order of the operands
  11418. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  11419. }
  11420. if( r == 1 )
  11421. {
  11422. if( node->tokenType == ttNotEqual || node->tokenType == ttNotIs )
  11423. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  11424. // Success, don't continue
  11425. return;
  11426. }
  11427. else if( r == 0 )
  11428. {
  11429. // Couldn't find opEquals method
  11430. Error(TXT_NO_APPROPRIATE_OPEQUALS, node);
  11431. }
  11432. // Compiler error, don't continue
  11433. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  11434. return;
  11435. }
  11436. // Implicitly convert null to the other type
  11437. asCDataType to;
  11438. if( lctx->type.IsNullConstant() )
  11439. to = rctx->type.dataType;
  11440. else if( rctx->type.IsNullConstant() )
  11441. to = lctx->type.dataType;
  11442. else
  11443. {
  11444. // Find a common base type
  11445. asSExprContext tmp(engine);
  11446. tmp.type = rctx->type;
  11447. ImplicitConversion(&tmp, lctx->type.dataType, 0, asIC_IMPLICIT_CONV, false);
  11448. if( tmp.type.dataType.GetObjectType() == lctx->type.dataType.GetObjectType() )
  11449. to = lctx->type.dataType;
  11450. else
  11451. to = rctx->type.dataType;
  11452. }
  11453. // Need to pop the value if it is a null constant
  11454. if( lctx->type.IsNullConstant() )
  11455. lctx->bc.Instr(asBC_PopPtr);
  11456. if( rctx->type.IsNullConstant() )
  11457. rctx->bc.Instr(asBC_PopPtr);
  11458. // Convert both sides to explicit handles
  11459. to.MakeHandle(true);
  11460. to.MakeReference(false);
  11461. if( !to.IsObjectHandle() )
  11462. {
  11463. // Compiler error, don't continue
  11464. Error(TXT_OPERANDS_MUST_BE_HANDLES, node);
  11465. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  11466. return;
  11467. }
  11468. // Do the conversion
  11469. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  11470. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  11471. // Both operands must be of the same type
  11472. // Verify that the conversion was successful
  11473. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  11474. {
  11475. asCString str;
  11476. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  11477. Error(str, node);
  11478. }
  11479. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  11480. {
  11481. asCString str;
  11482. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  11483. Error(str, node);
  11484. }
  11485. // Make sure it really is handles that are being compared
  11486. if( !lctx->type.dataType.IsObjectHandle() )
  11487. {
  11488. Error(TXT_OPERANDS_MUST_BE_HANDLES, node);
  11489. }
  11490. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  11491. int op = node->tokenType;
  11492. if( op == ttEqual || op == ttNotEqual || op == ttIs || op == ttNotIs )
  11493. {
  11494. // TODO: runtime optimize: don't do REFCPY
  11495. ConvertToVariableNotIn(lctx, rctx);
  11496. ConvertToVariable(rctx);
  11497. // Pop the pointers from the stack as they will not be used
  11498. lctx->bc.Instr(asBC_PopPtr);
  11499. rctx->bc.Instr(asBC_PopPtr);
  11500. MergeExprBytecode(ctx, lctx);
  11501. MergeExprBytecode(ctx, rctx);
  11502. int a = AllocateVariable(ctx->type.dataType, true);
  11503. int b = lctx->type.stackOffset;
  11504. int c = rctx->type.stackOffset;
  11505. ctx->bc.InstrW_W(asBC_CmpPtr, b, c);
  11506. if( op == ttEqual || op == ttIs )
  11507. ctx->bc.Instr(asBC_TZ);
  11508. else if( op == ttNotEqual || op == ttNotIs )
  11509. ctx->bc.Instr(asBC_TNZ);
  11510. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  11511. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  11512. ReleaseTemporaryVariable(lctx->type, &ctx->bc);
  11513. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  11514. ProcessDeferredParams(ctx);
  11515. }
  11516. else
  11517. {
  11518. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  11519. Error(TXT_ILLEGAL_OPERATION, node);
  11520. }
  11521. }
  11522. void asCCompiler::PerformFunctionCall(int funcId, asSExprContext *ctx, bool isConstructor, asCArray<asSExprContext*> *args, asCObjectType *objType, bool useVariable, int varOffset, int funcPtrVar)
  11523. {
  11524. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  11525. // A shared object may not call non-shared functions
  11526. if( outFunc->IsShared() && !descr->IsShared() )
  11527. {
  11528. asCString msg;
  11529. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, descr->GetDeclarationStr().AddressOf());
  11530. Error(msg, ctx->exprNode);
  11531. }
  11532. // Check if the function is private
  11533. if( descr->isPrivate && descr->GetObjectType() != outFunc->GetObjectType() )
  11534. {
  11535. asCString msg;
  11536. msg.Format(TXT_PRIVATE_METHOD_CALL_s, descr->GetDeclarationStr().AddressOf());
  11537. Error(msg, ctx->exprNode);
  11538. }
  11539. int argSize = descr->GetSpaceNeededForArguments();
  11540. // If we're calling a class method we must make sure the object is guaranteed to stay
  11541. // alive throughout the call by holding on to a reference in a local variable. This must
  11542. // be done for any methods that return references, and any calls on script objects.
  11543. // Application registered objects are assumed to know to keep themselves alive even
  11544. // if the method doesn't return a refernce.
  11545. if( descr->objectType &&
  11546. (ctx->type.dataType.IsObjectHandle() || ctx->type.dataType.SupportHandles()) &&
  11547. (descr->returnType.IsReference() || (ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_SCRIPT_OBJECT)) &&
  11548. !(ctx->type.isVariable || ctx->type.isTemporary) &&
  11549. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_SCOPED) &&
  11550. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_ASHANDLE) )
  11551. {
  11552. // TODO: runtime optimize: This can be avoided for local variables (non-handles) as they have a well defined life time
  11553. int tempRef = AllocateVariable(ctx->type.dataType, true);
  11554. ctx->bc.InstrSHORT(asBC_PSF, (short)tempRef);
  11555. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  11556. // Add the release of this reference as a deferred expression
  11557. asSDeferredParam deferred;
  11558. deferred.origExpr = 0;
  11559. deferred.argInOutFlags = asTM_INREF;
  11560. deferred.argNode = 0;
  11561. deferred.argType.SetVariable(ctx->type.dataType, tempRef, true);
  11562. ctx->deferredParams.PushLast(deferred);
  11563. // Forget the current type
  11564. ctx->type.SetDummy();
  11565. }
  11566. // Check if there is a need to add a hidden pointer for when the function returns an object by value
  11567. if( descr->DoesReturnOnStack() && !useVariable )
  11568. {
  11569. useVariable = true;
  11570. varOffset = AllocateVariable(descr->returnType, true);
  11571. // Push the pointer to the pre-allocated space for the return value
  11572. ctx->bc.InstrSHORT(asBC_PSF, short(varOffset));
  11573. if( descr->objectType )
  11574. {
  11575. // The object pointer is already on the stack, but should be the top
  11576. // one, so we need to swap the pointers in order to get the correct
  11577. ctx->bc.Instr(asBC_SwapPtr);
  11578. }
  11579. }
  11580. if( isConstructor )
  11581. {
  11582. // Sometimes the value types are allocated on the heap,
  11583. // which is when this way of constructing them is used.
  11584. asASSERT(useVariable == false);
  11585. ctx->bc.Alloc(asBC_ALLOC, objType, descr->id, argSize+AS_PTR_SIZE);
  11586. // The instruction has already moved the returned object to the variable
  11587. ctx->type.Set(asCDataType::CreatePrimitive(ttVoid, false));
  11588. ctx->type.isLValue = false;
  11589. // Clean up arguments
  11590. if( args )
  11591. AfterFunctionCall(funcId, *args, ctx, false);
  11592. ProcessDeferredParams(ctx);
  11593. return;
  11594. }
  11595. else
  11596. {
  11597. if( descr->objectType )
  11598. argSize += AS_PTR_SIZE;
  11599. // If the function returns an object by value the address of the location
  11600. // where the value should be stored is passed as an argument too
  11601. if( descr->DoesReturnOnStack() )
  11602. argSize += AS_PTR_SIZE;
  11603. // TODO: runtime optimize: If it is known that a class method cannot be overridden the call
  11604. // should be made with asBC_CALL as it is faster. Examples where this
  11605. // is known is for example finalled methods where the class doesn't derive
  11606. // from any other, or even non-finalled methods but where it is known
  11607. // at compile time the true type of the object. The first should be
  11608. // quite easy to determine, but the latter will be quite complex and possibly
  11609. // not worth it.
  11610. if( descr->funcType == asFUNC_IMPORTED )
  11611. ctx->bc.Call(asBC_CALLBND , descr->id, argSize);
  11612. // TODO: Maybe we need two different byte codes
  11613. else if( descr->funcType == asFUNC_INTERFACE || descr->funcType == asFUNC_VIRTUAL )
  11614. ctx->bc.Call(asBC_CALLINTF, descr->id, argSize);
  11615. else if( descr->funcType == asFUNC_SCRIPT )
  11616. ctx->bc.Call(asBC_CALL , descr->id, argSize);
  11617. else if( descr->funcType == asFUNC_SYSTEM )
  11618. ctx->bc.Call(asBC_CALLSYS , descr->id, argSize);
  11619. else if( descr->funcType == asFUNC_FUNCDEF )
  11620. ctx->bc.CallPtr(asBC_CallPtr, funcPtrVar, argSize);
  11621. }
  11622. if( descr->returnType.IsObject() && !descr->returnType.IsReference() )
  11623. {
  11624. int returnOffset = 0;
  11625. asCTypeInfo tmpExpr = ctx->type;
  11626. if( descr->DoesReturnOnStack() )
  11627. {
  11628. asASSERT( useVariable );
  11629. // The variable was allocated before the function was called
  11630. returnOffset = varOffset;
  11631. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  11632. // The variable was initialized by the function, so we need to mark it as initialized here
  11633. ctx->bc.ObjInfo(varOffset, asOBJ_INIT);
  11634. }
  11635. else
  11636. {
  11637. if( useVariable )
  11638. {
  11639. // Use the given variable
  11640. returnOffset = varOffset;
  11641. ctx->type.SetVariable(descr->returnType, returnOffset, false);
  11642. }
  11643. else
  11644. {
  11645. // Allocate a temporary variable for the returned object
  11646. // The returned object will actually be allocated on the heap, so
  11647. // we must force the allocation of the variable to do the same
  11648. returnOffset = AllocateVariable(descr->returnType, true, !descr->returnType.IsObjectHandle());
  11649. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  11650. }
  11651. // Move the pointer from the object register to the temporary variable
  11652. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  11653. }
  11654. ReleaseTemporaryVariable(tmpExpr, &ctx->bc);
  11655. ctx->type.dataType.MakeReference(IsVariableOnHeap(returnOffset));
  11656. ctx->type.isLValue = false; // It is a reference, but not an lvalue
  11657. // Clean up arguments
  11658. if( args )
  11659. AfterFunctionCall(funcId, *args, ctx, false);
  11660. ProcessDeferredParams(ctx);
  11661. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  11662. }
  11663. else if( descr->returnType.IsReference() )
  11664. {
  11665. asASSERT(useVariable == false);
  11666. // We cannot clean up the arguments yet, because the
  11667. // reference might be pointing to one of them.
  11668. if( args )
  11669. AfterFunctionCall(funcId, *args, ctx, true);
  11670. // Do not process the output parameters yet, because it
  11671. // might invalidate the returned reference
  11672. // If the context holds a variable that needs cleanup
  11673. // store it as a deferred parameter so it will be cleaned up
  11674. // afterwards.
  11675. if( ctx->type.isTemporary )
  11676. {
  11677. asSDeferredParam defer;
  11678. defer.argNode = 0;
  11679. defer.argType = ctx->type;
  11680. defer.argInOutFlags = asTM_INOUTREF;
  11681. defer.origExpr = 0;
  11682. ctx->deferredParams.PushLast(defer);
  11683. }
  11684. ctx->type.Set(descr->returnType);
  11685. if( !descr->returnType.IsPrimitive() )
  11686. {
  11687. ctx->bc.Instr(asBC_PshRPtr);
  11688. if( descr->returnType.IsObject() &&
  11689. !descr->returnType.IsObjectHandle() )
  11690. {
  11691. // We are getting the pointer to the object
  11692. // not a pointer to a object variable
  11693. ctx->type.dataType.MakeReference(false);
  11694. }
  11695. }
  11696. // A returned reference can be used as lvalue
  11697. ctx->type.isLValue = true;
  11698. }
  11699. else
  11700. {
  11701. asASSERT(useVariable == false);
  11702. asCTypeInfo tmpExpr = ctx->type;
  11703. if( descr->returnType.GetSizeInMemoryBytes() )
  11704. {
  11705. // Allocate a temporary variable to hold the value, but make sure
  11706. // the temporary variable isn't used in any of the deferred arguments
  11707. int l = int(reservedVariables.GetLength());
  11708. for( asUINT n = 0; args && n < args->GetLength(); n++ )
  11709. {
  11710. asSExprContext *expr = (*args)[n]->origExpr;
  11711. if( expr )
  11712. expr->bc.GetVarsUsed(reservedVariables);
  11713. }
  11714. int offset = AllocateVariable(descr->returnType, true);
  11715. reservedVariables.SetLength(l);
  11716. ctx->type.SetVariable(descr->returnType, offset, true);
  11717. // Move the value from the return register to the variable
  11718. if( descr->returnType.GetSizeOnStackDWords() == 1 )
  11719. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)offset);
  11720. else if( descr->returnType.GetSizeOnStackDWords() == 2 )
  11721. ctx->bc.InstrSHORT(asBC_CpyRtoV8, (short)offset);
  11722. }
  11723. else
  11724. ctx->type.Set(descr->returnType);
  11725. ReleaseTemporaryVariable(tmpExpr, &ctx->bc);
  11726. ctx->type.isLValue = false;
  11727. // Clean up arguments
  11728. if( args )
  11729. AfterFunctionCall(funcId, *args, ctx, false);
  11730. ProcessDeferredParams(ctx);
  11731. }
  11732. }
  11733. // This only merges the bytecode, but doesn't modify the type of the final context
  11734. void asCCompiler::MergeExprBytecode(asSExprContext *before, asSExprContext *after)
  11735. {
  11736. before->bc.AddCode(&after->bc);
  11737. for( asUINT n = 0; n < after->deferredParams.GetLength(); n++ )
  11738. {
  11739. before->deferredParams.PushLast(after->deferredParams[n]);
  11740. after->deferredParams[n].origExpr = 0;
  11741. }
  11742. after->deferredParams.SetLength(0);
  11743. }
  11744. // This merges both bytecode and the type of the final context
  11745. void asCCompiler::MergeExprBytecodeAndType(asSExprContext *before, asSExprContext *after)
  11746. {
  11747. MergeExprBytecode(before, after);
  11748. before->type = after->type;
  11749. before->property_get = after->property_get;
  11750. before->property_set = after->property_set;
  11751. before->property_const = after->property_const;
  11752. before->property_handle = after->property_handle;
  11753. before->property_ref = after->property_ref;
  11754. before->property_arg = after->property_arg;
  11755. before->exprNode = after->exprNode;
  11756. before->methodName = after->methodName;
  11757. before->enumValue = after->enumValue;
  11758. after->property_arg = 0;
  11759. // Do not copy the origExpr member
  11760. }
  11761. void asCCompiler::FilterConst(asCArray<int> &funcs, bool removeConst)
  11762. {
  11763. if( funcs.GetLength() == 0 ) return;
  11764. // This is only done for object methods
  11765. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[0]);
  11766. if( desc->objectType == 0 ) return;
  11767. // Check if there are any non-const matches
  11768. asUINT n;
  11769. bool foundNonConst = false;
  11770. for( n = 0; n < funcs.GetLength(); n++ )
  11771. {
  11772. desc = builder->GetFunctionDescription(funcs[n]);
  11773. if( desc->isReadOnly != removeConst )
  11774. {
  11775. foundNonConst = true;
  11776. break;
  11777. }
  11778. }
  11779. if( foundNonConst )
  11780. {
  11781. // Remove all const methods
  11782. for( n = 0; n < funcs.GetLength(); n++ )
  11783. {
  11784. desc = builder->GetFunctionDescription(funcs[n]);
  11785. if( desc->isReadOnly == removeConst )
  11786. {
  11787. if( n == funcs.GetLength() - 1 )
  11788. funcs.PopLast();
  11789. else
  11790. funcs[n] = funcs.PopLast();
  11791. n--;
  11792. }
  11793. }
  11794. }
  11795. }
  11796. END_AS_NAMESPACE
  11797. #endif // AS_NO_COMPILER