as_compiler.cpp 350 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2012 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. // Modified by Lasse Öörni for Urho3D
  24. //
  25. // as_compiler.cpp
  26. //
  27. // The class that does the actual compilation of the functions
  28. //
  29. #include <math.h> // fmodf()
  30. #include "as_config.h"
  31. #ifndef AS_NO_COMPILER
  32. #include "as_compiler.h"
  33. #include "as_tokendef.h"
  34. #include "as_tokenizer.h"
  35. #include "as_string_util.h"
  36. #include "as_texts.h"
  37. #include "as_parser.h"
  38. BEGIN_AS_NAMESPACE
  39. // TODO: I must correct the interpretation of a references to objects in the compiler.
  40. // A reference should mean that a pointer to the object is on the stack.
  41. // No expression should end up as non-references to objects, as the actual object is
  42. // never put on the stack.
  43. // Local variables are declared as non-references, but the expression should be a reference to the variable.
  44. // Function parameters of called functions can also be non-references, but in that case it means the
  45. // object will be passed by value (currently on the heap, which will be moved to the application stack).
  46. //
  47. // The compiler shouldn't use the asCDataType::IsReference. The datatype should always be stored as non-references.
  48. // Instead the compiler should keep track of references in TypeInfo, where it should also state how the reference
  49. // is currently stored, i.e. in variable, in register, on stack, etc.
  50. asCCompiler::asCCompiler(asCScriptEngine *engine) : byteCode(engine)
  51. {
  52. builder = 0;
  53. script = 0;
  54. variables = 0;
  55. isProcessingDeferredParams = false;
  56. isCompilingDefaultArg = false;
  57. noCodeOutput = 0;
  58. }
  59. asCCompiler::~asCCompiler()
  60. {
  61. while( variables )
  62. {
  63. asCVariableScope *var = variables;
  64. variables = variables->parent;
  65. asDELETE(var,asCVariableScope);
  66. }
  67. }
  68. void asCCompiler::Reset(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  69. {
  70. this->builder = builder;
  71. this->engine = builder->engine;
  72. this->script = script;
  73. this->outFunc = outFunc;
  74. hasCompileErrors = false;
  75. m_isConstructor = false;
  76. m_isConstructorCalled = false;
  77. nextLabel = 0;
  78. breakLabels.SetLength(0);
  79. continueLabels.SetLength(0);
  80. byteCode.ClearAll();
  81. }
  82. int asCCompiler::CompileDefaultConstructor(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, asCScriptFunction *outFunc)
  83. {
  84. Reset(builder, script, outFunc);
  85. // Make sure all the class members can be initialized with default constructors
  86. for( asUINT n = 0; n < outFunc->objectType->properties.GetLength(); n++ )
  87. {
  88. asCDataType &dt = outFunc->objectType->properties[n]->type;
  89. if( dt.IsObject() && !dt.IsObjectHandle() &&
  90. (((dt.GetObjectType()->flags & asOBJ_REF) && dt.GetObjectType()->beh.factory == 0) ||
  91. ((dt.GetObjectType()->flags & asOBJ_VALUE) && !(dt.GetObjectType()->flags & asOBJ_POD) && dt.GetObjectType()->beh.construct == 0)) )
  92. {
  93. asCString str;
  94. if( dt.GetFuncDef() )
  95. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetFuncDef()->GetName());
  96. else
  97. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, dt.GetObjectType()->GetName());
  98. Error(str.AddressOf(), node);
  99. }
  100. }
  101. // If the class is derived from another, then the base class' default constructor must be called
  102. if( outFunc->objectType->derivedFrom )
  103. {
  104. // Call the base class' default constructor
  105. byteCode.InstrSHORT(asBC_PSF, 0);
  106. byteCode.Instr(asBC_RDSPtr);
  107. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  108. }
  109. // Pop the object pointer from the stack
  110. byteCode.Ret(AS_PTR_SIZE);
  111. FinalizeFunction();
  112. #ifdef AS_DEBUG
  113. // DEBUG: output byte code
  114. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + "__dc.txt").AddressOf(), engine, outFunc);
  115. #endif
  116. return 0;
  117. }
  118. int asCCompiler::CompileFactory(asCBuilder *builder, asCScriptCode *script, asCScriptFunction *outFunc)
  119. {
  120. Reset(builder, script, outFunc);
  121. unsigned int n;
  122. // Find the corresponding constructor
  123. asCDataType dt = asCDataType::CreateObject(outFunc->returnType.GetObjectType(), false);
  124. int constructor = 0;
  125. for( n = 0; n < dt.GetBehaviour()->factories.GetLength(); n++ )
  126. {
  127. if( dt.GetBehaviour()->factories[n] == outFunc->id )
  128. {
  129. constructor = dt.GetBehaviour()->constructors[n];
  130. break;
  131. }
  132. }
  133. // Allocate the class and instanciate it with the constructor
  134. int varOffset = AllocateVariable(dt, true);
  135. byteCode.Push(AS_PTR_SIZE);
  136. byteCode.InstrSHORT(asBC_PSF, (short)varOffset);
  137. // Copy all arguments to the top of the stack
  138. // TODO: bytecode: how will this work with platform independent bytecode, as the size of the args may vary?
  139. int argDwords = (int)outFunc->GetSpaceNeededForArguments();
  140. for( int a = argDwords-1; a >= 0; a-- )
  141. byteCode.InstrSHORT(asBC_PshV4, short(-a));
  142. byteCode.Alloc(asBC_ALLOC, dt.GetObjectType(), constructor, argDwords + AS_PTR_SIZE);
  143. // Return a handle to the newly created object
  144. byteCode.InstrSHORT(asBC_LOADOBJ, (short)varOffset);
  145. byteCode.Ret(argDwords);
  146. FinalizeFunction();
  147. // Tell the virtual machine not to clean up parameters on exception
  148. outFunc->dontCleanUpOnException = true;
  149. /*
  150. #ifdef AS_DEBUG
  151. // DEBUG: output byte code
  152. asCString args;
  153. args.Format("%d", outFunc->parameterTypes.GetLength());
  154. byteCode.DebugOutput(("__" + outFunc->name + "__factory" + args + ".txt").AddressOf(), engine);
  155. #endif
  156. */
  157. return 0;
  158. }
  159. void asCCompiler::FinalizeFunction()
  160. {
  161. asUINT n;
  162. // Tell the bytecode which variables are temporary
  163. for( n = 0; n < variableIsTemporary.GetLength(); n++ )
  164. {
  165. if( variableIsTemporary[n] )
  166. byteCode.DefineTemporaryVariable(GetVariableOffset(n));
  167. }
  168. // Finalize the bytecode
  169. byteCode.Finalize();
  170. byteCode.ExtractObjectVariableInfo(outFunc);
  171. // Compile the list of object variables for the exception handler
  172. for( n = 0; n < variableAllocations.GetLength(); n++ )
  173. {
  174. if( variableAllocations[n].IsObject() && !variableAllocations[n].IsReference() )
  175. {
  176. outFunc->objVariableTypes.PushLast(variableAllocations[n].GetObjectType());
  177. outFunc->objVariablePos.PushLast(GetVariableOffset(n));
  178. outFunc->objVariableIsOnHeap.PushLast(variableIsOnHeap[n]);
  179. }
  180. }
  181. // Copy byte code to the function
  182. outFunc->byteCode.SetLength(byteCode.GetSize());
  183. byteCode.Output(outFunc->byteCode.AddressOf());
  184. outFunc->AddReferences();
  185. outFunc->stackNeeded = byteCode.largestStackUsed;
  186. outFunc->lineNumbers = byteCode.lineNumbers;
  187. }
  188. // Entry
  189. int asCCompiler::CompileFunction(asCBuilder *builder, asCScriptCode *script, sExplicitSignature *signature, asCScriptNode *func, asCScriptFunction *outFunc)
  190. {
  191. // TODO: The compiler should take the return type and parameter types from the
  192. // outFunc, instead of interpreting the script nodes again. The builder
  193. // must pass the list of parameter names. Making this change we can
  194. // eliminate large parts of this function and the sExplicitSignature structure
  195. Reset(builder, script, outFunc);
  196. int buildErrors = builder->numErrors;
  197. int stackPos = 0;
  198. if( outFunc->objectType )
  199. stackPos = -AS_PTR_SIZE; // The first parameter is the pointer to the object
  200. // Reserve a label for the cleanup code
  201. nextLabel++;
  202. // Add the first variable scope, which the parameters and
  203. // variables declared in the outermost statement block is
  204. // part of.
  205. AddVariableScope();
  206. asCScriptNode *node;
  207. bool isDestructor = false;
  208. asCDataType returnType;
  209. if( !signature )
  210. {
  211. // Skip the private keyword if it is there
  212. node = func->firstChild;
  213. if( node->nodeType == snUndefined && node->tokenType == ttPrivate )
  214. node = node->next;
  215. //----------------------------------------------
  216. // Examine return type
  217. if( node->nodeType == snDataType )
  218. {
  219. // TODO: namespace: Use correct implicit namespace from function
  220. returnType = builder->CreateDataTypeFromNode(node, script, "");
  221. returnType = builder->ModifyDataTypeFromNode(returnType, node->next, script, 0, 0);
  222. // Make sure the return type is instanciable or is void
  223. if( !returnType.CanBeInstanciated() &&
  224. returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  225. {
  226. asCString str;
  227. str.Format(TXT_DATA_TYPE_CANT_BE_s, returnType.Format().AddressOf());
  228. Error(str.AddressOf(), func->firstChild);
  229. }
  230. }
  231. else
  232. {
  233. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  234. if( node->tokenType == ttBitNot )
  235. isDestructor = true;
  236. else
  237. m_isConstructor = true;
  238. }
  239. }
  240. else
  241. {
  242. node = func;
  243. returnType = signature->returnType;
  244. }
  245. // If the return type is a value type returned by value the address of the
  246. // location where the value will be stored is pushed on the stack before
  247. // the arguments
  248. if( !(isDestructor || m_isConstructor) && outFunc->DoesReturnOnStack() )
  249. stackPos -= AS_PTR_SIZE;
  250. asCVariableScope vs(0);
  251. if( !signature )
  252. {
  253. //----------------------------------------------
  254. // Declare parameters
  255. // Find first parameter
  256. while( node && node->nodeType != snParameterList )
  257. node = node->next;
  258. // Register parameters from last to first, otherwise they will be destroyed in the wrong order
  259. if( node ) node = node->firstChild;
  260. while( node )
  261. {
  262. // Get the parameter type
  263. // TODO: namespace: Use correct implicit namespace from function
  264. asCDataType type = builder->CreateDataTypeFromNode(node, script, "");
  265. asETypeModifiers inoutFlag = asTM_NONE;
  266. type = builder->ModifyDataTypeFromNode(type, node->next, script, &inoutFlag, 0);
  267. // Is the data type allowed?
  268. if( (type.IsReference() && inoutFlag != asTM_INOUTREF && !type.CanBeInstanciated()) ||
  269. (!type.IsReference() && !type.CanBeInstanciated()) )
  270. {
  271. asCString parm = type.Format();
  272. if( inoutFlag == asTM_INREF )
  273. parm += "in";
  274. else if( inoutFlag == asTM_OUTREF )
  275. parm += "out";
  276. asCString str;
  277. str.Format(TXT_PARAMETER_CANT_BE_s, parm.AddressOf());
  278. Error(str.AddressOf(), node);
  279. }
  280. // If the parameter has a name then declare it as variable
  281. node = node->next->next;
  282. if( node && node->nodeType == snIdentifier )
  283. {
  284. asCString name(&script->code[node->tokenPos], node->tokenLength);
  285. if( vs.DeclareVariable(name.AddressOf(), type, stackPos, true) < 0 )
  286. Error(TXT_PARAMETER_ALREADY_DECLARED, node);
  287. // Add marker for variable declaration
  288. byteCode.VarDecl((int)outFunc->variables.GetLength());
  289. outFunc->AddVariable(name, type, stackPos);
  290. node = node->next;
  291. // Skip the default arg
  292. if( node && node->nodeType == snExpression )
  293. node = node->next;
  294. }
  295. else
  296. vs.DeclareVariable("", type, stackPos, true);
  297. // Move to next parameter
  298. stackPos -= type.GetSizeOnStackDWords();
  299. }
  300. }
  301. else
  302. {
  303. asCArray<asCDataType> &args = signature->argTypes;
  304. asCArray<asETypeModifiers> &inoutFlags = signature->argModifiers;
  305. asCArray<asCString> &argNames = signature->argNames;
  306. asASSERT(args.GetLength() == argNames.GetLength());
  307. for( int k = 0; k < (int)args.GetLength(); k++ )
  308. {
  309. asCDataType type = args[k];
  310. asETypeModifiers inoutFlag = inoutFlags[k];
  311. if( (type.IsReference() && inoutFlag != asTM_INOUTREF && !type.CanBeInstanciated()) ||
  312. (!type.IsReference() && !type.CanBeInstanciated()) )
  313. {
  314. asCString str;
  315. str.Format(TXT_PARAMETER_CANT_BE_s, type.Format().AddressOf());
  316. Error(str.AddressOf(), node);
  317. }
  318. if( 0 != argNames[k].Compare("") )
  319. {
  320. if( vs.DeclareVariable(argNames[k].AddressOf(), type, stackPos, true) < 0 )
  321. Error(TXT_PARAMETER_ALREADY_DECLARED, node);
  322. // Add marker for variable declaration
  323. byteCode.VarDecl((int)outFunc->variables.GetLength());
  324. outFunc->AddVariable(argNames[k], type, stackPos);
  325. }
  326. else
  327. vs.DeclareVariable("", type, stackPos, true);
  328. // Move to next parameter
  329. stackPos -= type.GetSizeOnStackDWords();
  330. }
  331. }
  332. int n;
  333. for( n = (int)vs.variables.GetLength() - 1; n >= 0; n-- )
  334. {
  335. variables->DeclareVariable(vs.variables[n]->name.AddressOf(), vs.variables[n]->type, vs.variables[n]->stackOffset, vs.variables[n]->onHeap);
  336. }
  337. // Is the return type allowed?
  338. if( (returnType.GetSizeOnStackDWords() == 0 && returnType != asCDataType::CreatePrimitive(ttVoid, false)) ||
  339. (returnType.IsReference() && !returnType.CanBeInstanciated()) )
  340. {
  341. asCString str;
  342. str.Format(TXT_RETURN_CANT_BE_s, returnType.Format().AddressOf());
  343. Error(str.AddressOf(), func);
  344. }
  345. variables->DeclareVariable("return", returnType, stackPos, true);
  346. //--------------------------------------------
  347. // Compile the statement block
  348. // We need to parse the statement block now
  349. asCScriptNode *blockBegin;
  350. if( !signature )
  351. blockBegin = func->lastChild;
  352. else
  353. blockBegin = func;
  354. // TODO: memory: We can parse the statement block one statement at a time, thus save even more memory
  355. asCParser parser(builder);
  356. int r = parser.ParseStatementBlock(script, blockBegin);
  357. if( r < 0 ) return -1;
  358. asCScriptNode *block = parser.GetScriptNode();
  359. bool hasReturn;
  360. asCByteCode bc(engine);
  361. LineInstr(&bc, blockBegin->tokenPos);
  362. CompileStatementBlock(block, false, &hasReturn, &bc);
  363. LineInstr(&bc, blockBegin->tokenPos + blockBegin->tokenLength);
  364. // Make sure there is a return in all paths (if not return type is void)
  365. if( returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  366. {
  367. if( hasReturn == false )
  368. Error(TXT_NOT_ALL_PATHS_RETURN, blockBegin);
  369. }
  370. //------------------------------------------------
  371. // Concatenate the bytecode
  372. // Insert a JitEntry at the start of the function for JIT compilers
  373. byteCode.InstrPTR(asBC_JitEntry, 0);
  374. // Count total variable size
  375. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  376. byteCode.Push(varSize);
  377. if( outFunc->objectType )
  378. {
  379. // Call the base class' default constructor unless called manually in the code
  380. if( m_isConstructor && !m_isConstructorCalled && outFunc->objectType->derivedFrom )
  381. {
  382. byteCode.InstrSHORT(asBC_PSF, 0);
  383. byteCode.Instr(asBC_RDSPtr);
  384. byteCode.Call(asBC_CALL, outFunc->objectType->derivedFrom->beh.construct, AS_PTR_SIZE);
  385. }
  386. // Increase the reference for the object pointer, so that it is guaranteed to live during the entire call
  387. // TODO: optimize: This is probably not necessary for constructors as no outside reference to the object is created yet
  388. byteCode.InstrSHORT(asBC_PSF, 0);
  389. byteCode.Instr(asBC_RDSPtr);
  390. byteCode.Call(asBC_CALLSYS, outFunc->objectType->beh.addref, AS_PTR_SIZE);
  391. }
  392. // Add the code for the statement block
  393. byteCode.AddCode(&bc);
  394. // Deallocate all local variables
  395. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  396. {
  397. sVariable *v = variables->variables[n];
  398. if( v->stackOffset > 0 )
  399. {
  400. // Call variables destructors
  401. if( v->name != "return" && v->name != "return address" )
  402. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  403. DeallocateVariable(v->stackOffset);
  404. }
  405. }
  406. // This is the label that return statements jump to
  407. // in order to exit the function
  408. byteCode.Label(0);
  409. // Call destructors for function parameters
  410. for( n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  411. {
  412. sVariable *v = variables->variables[n];
  413. if( v->stackOffset <= 0 )
  414. {
  415. // Call variable destructors here, for variables not yet destroyed
  416. if( v->name != "return" && v->name != "return address" )
  417. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  418. }
  419. // Do not deallocate parameters
  420. }
  421. // Release the object pointer again
  422. if( outFunc->objectType )
  423. {
  424. byteCode.InstrW_PTR(asBC_FREE, 0, outFunc->objectType);
  425. }
  426. // If there are compile errors, there is no reason to build the final code
  427. if( hasCompileErrors || builder->numErrors != buildErrors )
  428. return -1;
  429. // At this point there should be no variables allocated
  430. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  431. // Remove the variable scope
  432. RemoveVariableScope();
  433. // This POP is not necessary as the return will clean up the stack frame anyway.
  434. // The bytecode optimizer would remove this POP, however by not including it here
  435. // it is guaranteed it doesn't have to be adjusted by the asCRestore class when
  436. // a types are of a different size than originally compiled for.
  437. // byteCode.Pop(varSize);
  438. byteCode.Ret(-stackPos);
  439. FinalizeFunction();
  440. #ifdef AS_DEBUG
  441. // DEBUG: output byte code
  442. if( outFunc->objectType )
  443. byteCode.DebugOutput(("__" + outFunc->objectType->name + "_" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  444. else
  445. byteCode.DebugOutput(("__" + outFunc->name + ".txt").AddressOf(), engine, outFunc);
  446. #endif
  447. return 0;
  448. }
  449. int asCCompiler::CallCopyConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asSExprContext *arg, asCScriptNode *node, bool isGlobalVar, bool derefDest)
  450. {
  451. if( !type.IsObject() )
  452. return 0;
  453. // CallCopyConstructor should not be called for object handles.
  454. asASSERT( !type.IsObjectHandle() );
  455. asCArray<asSExprContext*> args;
  456. args.PushLast(arg);
  457. // The reference parameter must be pushed on the stack
  458. asASSERT( arg->type.dataType.GetObjectType() == type.GetObjectType() );
  459. // Since we're calling the copy constructor, we have to trust the function to not do
  460. // anything stupid otherwise we will just enter a loop, as we try to make temporary
  461. // copies of the argument in order to guarantee safety.
  462. if( type.GetObjectType()->flags & asOBJ_REF )
  463. {
  464. asSExprContext ctx(engine);
  465. int func = 0;
  466. asSTypeBehaviour *beh = type.GetBehaviour();
  467. if( beh ) func = beh->copyfactory;
  468. if( func > 0 )
  469. {
  470. if( !isGlobalVar )
  471. {
  472. // Call factory and store the handle in the given variable
  473. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType(), true, offset);
  474. // Pop the reference left by the function call
  475. ctx.bc.Pop(AS_PTR_SIZE);
  476. }
  477. else
  478. {
  479. // Call factory
  480. PerformFunctionCall(func, &ctx, false, &args, type.GetObjectType());
  481. // Store the returned handle in the global variable
  482. ctx.bc.Instr(asBC_RDSPtr);
  483. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  484. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  485. ctx.bc.Pop(AS_PTR_SIZE);
  486. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  487. }
  488. bc->AddCode(&ctx.bc);
  489. return 0;
  490. }
  491. }
  492. else
  493. {
  494. asSTypeBehaviour *beh = type.GetBehaviour();
  495. int func = beh ? beh->copyconstruct : 0;
  496. if( func > 0 )
  497. {
  498. // Push the address where the object will be stored on the stack, before the argument
  499. // TODO: When the context is serializable this probably has to be changed, since this
  500. // pointer can remain on the stack while the context is suspended. There is no
  501. // risk the pointer becomes invalid though, there is just no easy way to serialize it.
  502. asCByteCode tmp(engine);
  503. if( isGlobalVar )
  504. tmp.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  505. else if( isObjectOnHeap )
  506. tmp.InstrSHORT(asBC_PSF, (short)offset);
  507. tmp.AddCode(bc);
  508. bc->AddCode(&tmp);
  509. // When the object is allocated on the stack the object pointer
  510. // must be pushed on the stack after the arguments
  511. if( !isObjectOnHeap )
  512. {
  513. asASSERT( !isGlobalVar );
  514. bc->InstrSHORT(asBC_PSF, (short)offset);
  515. if( derefDest )
  516. {
  517. // The variable is a reference to the real location, so we need to dereference it
  518. bc->Instr(asBC_RDSPtr);
  519. }
  520. }
  521. asSExprContext ctx(engine);
  522. PerformFunctionCall(func, &ctx, isObjectOnHeap, &args, type.GetObjectType());
  523. bc->AddCode(&ctx.bc);
  524. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  525. // Mark the object as initialized
  526. if( !isObjectOnHeap )
  527. bc->ObjInfo(offset, asOBJ_INIT);
  528. return 0;
  529. }
  530. }
  531. // Class has no copy constructor/factory.
  532. asCString str;
  533. str.Format(TXT_NO_COPY_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  534. Error(str.AddressOf(), node);
  535. return -1;
  536. }
  537. int asCCompiler::CallDefaultConstructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc, asCScriptNode *node, bool isGlobalVar, bool deferDest)
  538. {
  539. if( !type.IsObject() || type.IsObjectHandle() )
  540. return 0;
  541. if( type.GetObjectType()->flags & asOBJ_REF )
  542. {
  543. asSExprContext ctx(engine);
  544. ctx.exprNode = node;
  545. int func = 0;
  546. asSTypeBehaviour *beh = type.GetBehaviour();
  547. if( beh ) func = beh->factory;
  548. if( func > 0 )
  549. {
  550. if( !isGlobalVar )
  551. {
  552. // Call factory and store the handle in the given variable
  553. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType(), true, offset);
  554. // Pop the reference left by the function call
  555. ctx.bc.Pop(AS_PTR_SIZE);
  556. }
  557. else
  558. {
  559. // Call factory
  560. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  561. // Store the returned handle in the global variable
  562. ctx.bc.Instr(asBC_RDSPtr);
  563. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  564. ctx.bc.InstrPTR(asBC_REFCPY, type.GetObjectType());
  565. ctx.bc.Pop(AS_PTR_SIZE);
  566. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  567. }
  568. bc->AddCode(&ctx.bc);
  569. return 0;
  570. }
  571. }
  572. else
  573. {
  574. asSTypeBehaviour *beh = type.GetBehaviour();
  575. int func = 0;
  576. if( beh ) func = beh->construct;
  577. // Allocate and initialize with the default constructor
  578. if( func != 0 || (type.GetObjectType()->flags & asOBJ_POD) )
  579. {
  580. if( !isObjectOnHeap )
  581. {
  582. asASSERT( !isGlobalVar );
  583. // There is nothing to do if there is no function,
  584. // as the memory is already allocated on the stack
  585. if( func )
  586. {
  587. // Call the constructor as a normal function
  588. bc->InstrSHORT(asBC_PSF, (short)offset);
  589. if( deferDest )
  590. bc->Instr(asBC_RDSPtr);
  591. asSExprContext ctx(engine);
  592. PerformFunctionCall(func, &ctx, false, 0, type.GetObjectType());
  593. bc->AddCode(&ctx.bc);
  594. // TODO: value on stack: This probably needs to be done in PerformFunctionCall
  595. // Mark the object as initialized
  596. bc->ObjInfo(offset, asOBJ_INIT);
  597. }
  598. }
  599. else
  600. {
  601. if( isGlobalVar )
  602. bc->InstrPTR(asBC_PGA, engine->globalProperties[offset]->GetAddressOfValue());
  603. else
  604. bc->InstrSHORT(asBC_PSF, (short)offset);
  605. bc->Alloc(asBC_ALLOC, type.GetObjectType(), func, AS_PTR_SIZE);
  606. }
  607. return 0;
  608. }
  609. }
  610. // Class has no default factory/constructor.
  611. asCString str;
  612. // TODO: funcdef: asCDataType should have a GetTypeName()
  613. if( type.GetFuncDef() )
  614. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetFuncDef()->GetName());
  615. else
  616. str.Format(TXT_NO_DEFAULT_CONSTRUCTOR_FOR_s, type.GetObjectType()->GetName());
  617. Error(str.AddressOf(), node);
  618. return -1;
  619. }
  620. void asCCompiler::CallDestructor(asCDataType &type, int offset, bool isObjectOnHeap, asCByteCode *bc)
  621. {
  622. if( !type.IsReference() )
  623. {
  624. // Call destructor for the data type
  625. if( type.IsObject() )
  626. {
  627. if( isObjectOnHeap || type.IsObjectHandle() )
  628. {
  629. // Free the memory
  630. bc->InstrW_PTR(asBC_FREE, (short)offset, type.GetObjectType());
  631. }
  632. else
  633. {
  634. asASSERT( type.GetObjectType()->GetFlags() & asOBJ_VALUE );
  635. if( type.GetBehaviour()->destruct )
  636. {
  637. // Call the destructor as a regular function
  638. bc->InstrSHORT(asBC_PSF, (short)offset);
  639. asSExprContext ctx(engine);
  640. PerformFunctionCall(type.GetBehaviour()->destruct, &ctx);
  641. bc->AddCode(&ctx.bc);
  642. }
  643. // TODO: Value on stack: This probably needs to be done in PerformFunctionCall
  644. // Mark the object as destroyed
  645. bc->ObjInfo(offset, asOBJ_UNINIT);
  646. }
  647. }
  648. }
  649. }
  650. void asCCompiler::LineInstr(asCByteCode *bc, size_t pos)
  651. {
  652. int r, c;
  653. script->ConvertPosToRowCol(pos, &r, &c);
  654. bc->Line(r, c);
  655. }
  656. void asCCompiler::CompileStatementBlock(asCScriptNode *block, bool ownVariableScope, bool *hasReturn, asCByteCode *bc)
  657. {
  658. *hasReturn = false;
  659. bool isFinished = false;
  660. bool hasWarned = false;
  661. if( ownVariableScope )
  662. {
  663. bc->Block(true);
  664. AddVariableScope();
  665. }
  666. asCScriptNode *node = block->firstChild;
  667. while( node )
  668. {
  669. if( !hasWarned && (*hasReturn || isFinished) )
  670. {
  671. hasWarned = true;
  672. Warning(TXT_UNREACHABLE_CODE, node);
  673. }
  674. if( node->nodeType == snBreak || node->nodeType == snContinue )
  675. isFinished = true;
  676. asCByteCode statement(engine);
  677. if( node->nodeType == snDeclaration )
  678. CompileDeclaration(node, &statement);
  679. else
  680. CompileStatement(node, hasReturn, &statement);
  681. LineInstr(bc, node->tokenPos);
  682. bc->AddCode(&statement);
  683. if( !hasCompileErrors )
  684. {
  685. asASSERT( tempVariables.GetLength() == 0 );
  686. asASSERT( reservedVariables.GetLength() == 0 );
  687. }
  688. node = node->next;
  689. }
  690. if( ownVariableScope )
  691. {
  692. // Deallocate variables in this block, in reverse order
  693. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  694. {
  695. sVariable *v = variables->variables[n];
  696. // Call variable destructors here, for variables not yet destroyed
  697. // If the block is terminated with a break, continue, or
  698. // return the variables are already destroyed
  699. if( !isFinished && !*hasReturn )
  700. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  701. // Don't deallocate function parameters
  702. if( v->stackOffset > 0 )
  703. DeallocateVariable(v->stackOffset);
  704. }
  705. RemoveVariableScope();
  706. bc->Block(false);
  707. }
  708. }
  709. // Entry
  710. int asCCompiler::CompileGlobalVariable(asCBuilder *builder, asCScriptCode *script, asCScriptNode *node, sGlobalVariableDescription *gvar, asCScriptFunction *outFunc)
  711. {
  712. Reset(builder, script, outFunc);
  713. // Add a variable scope (even though variables can't be declared)
  714. AddVariableScope();
  715. asSExprContext ctx(engine);
  716. gvar->isPureConstant = false;
  717. // Parse the initialization nodes
  718. asCParser parser(builder);
  719. if( node )
  720. {
  721. int r = parser.ParseGlobalVarInit(script, node);
  722. if( r < 0 )
  723. return r;
  724. node = parser.GetScriptNode();
  725. }
  726. // Compile the expression
  727. if( node && node->nodeType == snArgList )
  728. {
  729. // Make sure that it is a registered type, and that it isn't a pointer
  730. if( gvar->datatype.GetObjectType() == 0 || gvar->datatype.IsObjectHandle() )
  731. {
  732. Error(TXT_MUST_BE_OBJECT, node);
  733. }
  734. else
  735. {
  736. // Compile the arguments
  737. asCArray<asSExprContext *> args;
  738. if( CompileArgumentList(node, args) >= 0 )
  739. {
  740. // Find all constructors
  741. asCArray<int> funcs;
  742. asSTypeBehaviour *beh = gvar->datatype.GetBehaviour();
  743. if( beh )
  744. {
  745. if( gvar->datatype.GetObjectType()->flags & asOBJ_REF )
  746. funcs = beh->factories;
  747. else
  748. funcs = beh->constructors;
  749. }
  750. asCString str = gvar->datatype.Format();
  751. MatchFunctions(funcs, args, node, str.AddressOf());
  752. if( funcs.GetLength() == 1 )
  753. {
  754. int r = asSUCCESS;
  755. // Add the default values for arguments not explicitly supplied
  756. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  757. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  758. r = CompileDefaultArgs(node, args, func);
  759. if( r == asSUCCESS )
  760. {
  761. if( gvar->datatype.GetObjectType()->flags & asOBJ_REF )
  762. {
  763. MakeFunctionCall(&ctx, funcs[0], 0, args, node);
  764. // Store the returned handle in the global variable
  765. ctx.bc.Instr(asBC_RDSPtr);
  766. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  767. ctx.bc.InstrPTR(asBC_REFCPY, gvar->datatype.GetObjectType());
  768. ctx.bc.Pop(AS_PTR_SIZE);
  769. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  770. }
  771. else
  772. {
  773. // Push the address of the location where the variable will be stored on the stack.
  774. // This reference is safe, because the addresses of the global variables cannot change.
  775. // TODO: When serialization of the context is implemented this will probably have to change,
  776. // because this pointer may be on the stack while the context is suspended, and may
  777. // be difficult to serialize as the context doesn't know that the value represents a
  778. // pointer.
  779. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  780. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  781. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  782. PerformFunctionCall(funcs[0], &ctx, true, &args, gvar->datatype.GetObjectType());
  783. }
  784. }
  785. }
  786. }
  787. // Cleanup
  788. for( asUINT n = 0; n < args.GetLength(); n++ )
  789. if( args[n] )
  790. {
  791. asDELETE(args[n],asSExprContext);
  792. }
  793. }
  794. }
  795. else if( node && node->nodeType == snInitList )
  796. {
  797. asCTypeInfo ti;
  798. ti.Set(gvar->datatype);
  799. ti.isVariable = false;
  800. ti.isTemporary = false;
  801. ti.stackOffset = (short)gvar->index;
  802. ti.isLValue = true;
  803. CompileInitList(&ti, node, &ctx.bc);
  804. node = node->next;
  805. }
  806. else if( node )
  807. {
  808. // Compile the right hand expression
  809. asSExprContext expr(engine);
  810. int r = CompileAssignment(node, &expr); if( r < 0 ) return r;
  811. // Assign the value to the variable
  812. if( gvar->datatype.IsPrimitive() )
  813. {
  814. if( gvar->datatype.IsReadOnly() && expr.type.isConstant )
  815. {
  816. ImplicitConversion(&expr, gvar->datatype, node, asIC_IMPLICIT_CONV);
  817. gvar->isPureConstant = true;
  818. gvar->constantValue = expr.type.qwordValue;
  819. }
  820. asSExprContext lctx(engine);
  821. lctx.type.Set(gvar->datatype);
  822. lctx.type.dataType.MakeReference(true);
  823. lctx.type.dataType.MakeReadOnly(false);
  824. lctx.type.isLValue = true;
  825. // If it is an enum value that is being compiled, then
  826. // we skip this, as the bytecode won't be used anyway
  827. if( !gvar->isEnumValue )
  828. lctx.bc.InstrPTR(asBC_LDG, engine->globalProperties[gvar->index]->GetAddressOfValue());
  829. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  830. }
  831. else
  832. {
  833. // TODO: optimize: Here we should look for the best matching constructor, instead of
  834. // just the copy constructor. Only if no appropriate constructor is
  835. // available should the assignment operator be used.
  836. if( !gvar->datatype.IsObjectHandle() )
  837. {
  838. // Call the default constructor to have a valid object for the assignment
  839. CallDefaultConstructor(gvar->datatype, gvar->index, true, &ctx.bc, gvar->idNode, true);
  840. }
  841. asSExprContext lexpr(engine);
  842. lexpr.type.Set(gvar->datatype);
  843. lexpr.type.dataType.MakeReference(true);
  844. lexpr.type.dataType.MakeReadOnly(false);
  845. lexpr.type.stackOffset = -1;
  846. lexpr.type.isLValue = true;
  847. if( gvar->datatype.IsObjectHandle() )
  848. lexpr.type.isExplicitHandle = true;
  849. lexpr.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  850. // If left expression resolves into a registered type
  851. // check if the assignment operator is overloaded, and check
  852. // the type of the right hand expression. If none is found
  853. // the default action is a direct copy if it is the same type
  854. // and a simple assignment.
  855. bool assigned = false;
  856. // Even though an ASHANDLE can be an explicit handle the assignment needs to be treated by the overloaded operator
  857. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  858. {
  859. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  860. if( assigned )
  861. {
  862. // Pop the resulting value
  863. ctx.bc.Pop(ctx.type.dataType.GetSizeOnStackDWords());
  864. // Release the argument
  865. ProcessDeferredParams(&ctx);
  866. }
  867. }
  868. if( !assigned )
  869. {
  870. PrepareForAssignment(&lexpr.type.dataType, &expr, node, false);
  871. // If the expression is constant and the variable also is constant
  872. // then mark the variable as pure constant. This will allow the compiler
  873. // to optimize expressions with this variable.
  874. if( gvar->datatype.IsReadOnly() && expr.type.isConstant )
  875. {
  876. gvar->isPureConstant = true;
  877. gvar->constantValue = expr.type.qwordValue;
  878. }
  879. // Add expression code to bytecode
  880. MergeExprBytecode(&ctx, &expr);
  881. // Add byte code for storing value of expression in variable
  882. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[gvar->index]->GetAddressOfValue());
  883. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, node);
  884. // Release temporary variables used by expression
  885. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  886. ctx.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  887. }
  888. }
  889. }
  890. else if( gvar->datatype.IsObject() && !gvar->datatype.IsObjectHandle() )
  891. {
  892. // Call the default constructor in case no explicit initialization is given
  893. CallDefaultConstructor(gvar->datatype, gvar->index, true, &ctx.bc, gvar->idNode, true);
  894. }
  895. // Concatenate the bytecode
  896. int varSize = GetVariableOffset((int)variableAllocations.GetLength()) - 1;
  897. // Add information on the line number for the global variable
  898. size_t pos = 0;
  899. if( gvar->idNode )
  900. pos = gvar->idNode->tokenPos;
  901. else if( gvar->nextNode )
  902. pos = gvar->nextNode->tokenPos;
  903. LineInstr(&byteCode, pos);
  904. // We need to push zeroes on the stack to guarantee
  905. // that temporary object handles are clear
  906. // TODO: bytecode: How will this work with platform independent bytecode as the pointer size can vary?
  907. int n;
  908. for( n = 0; n < varSize; n++ )
  909. byteCode.InstrINT(asBC_PshC4, 0);
  910. byteCode.AddCode(&ctx.bc);
  911. // Deallocate variables in this block, in reverse order
  912. for( n = (int)variables->variables.GetLength() - 1; n >= 0; --n )
  913. {
  914. sVariable *v = variables->variables[n];
  915. // Call variable destructors here, for variables not yet destroyed
  916. CallDestructor(v->type, v->stackOffset, v->onHeap, &byteCode);
  917. DeallocateVariable(v->stackOffset);
  918. }
  919. if( hasCompileErrors ) return -1;
  920. // At this point there should be no variables allocated
  921. asASSERT(variableAllocations.GetLength() == freeVariables.GetLength());
  922. // Remove the variable scope again
  923. RemoveVariableScope();
  924. byteCode.Ret(0);
  925. FinalizeFunction();
  926. #ifdef AS_DEBUG
  927. // DEBUG: output byte code
  928. byteCode.DebugOutput(("___init_" + gvar->name + ".txt").AddressOf(), engine, outFunc);
  929. #endif
  930. return 0;
  931. }
  932. void asCCompiler::PrepareArgument(asCDataType *paramType, asSExprContext *ctx, asCScriptNode *node, bool isFunction, int refType, bool isMakingCopy)
  933. {
  934. asCDataType param = *paramType;
  935. if( paramType->GetTokenType() == ttQuestion )
  936. {
  937. // Since the function is expecting a var type ?, then we don't want to convert the argument to anything else
  938. param = ctx->type.dataType;
  939. param.MakeHandle(ctx->type.isExplicitHandle);
  940. param.MakeReference(paramType->IsReference());
  941. param.MakeReadOnly(paramType->IsReadOnly());
  942. }
  943. else
  944. param = *paramType;
  945. asCDataType dt = param;
  946. // Need to protect arguments by reference
  947. if( isFunction && dt.IsReference() )
  948. {
  949. if( paramType->GetTokenType() == ttQuestion )
  950. {
  951. asCByteCode tmpBC(engine);
  952. // Place the type id on the stack as a hidden parameter
  953. tmpBC.InstrDWORD(asBC_TYPEID, engine->GetTypeIdFromDataType(param));
  954. // Insert the code before the expression code
  955. tmpBC.AddCode(&ctx->bc);
  956. ctx->bc.AddCode(&tmpBC);
  957. }
  958. // Allocate a temporary variable of the same type as the argument
  959. dt.MakeReference(false);
  960. dt.MakeReadOnly(false);
  961. int offset;
  962. if( refType == 1 ) // &in
  963. {
  964. ProcessPropertyGetAccessor(ctx, node);
  965. // If the reference is const, then it is not necessary to make a copy if the value already is a variable
  966. // Even if the same variable is passed in another argument as non-const then there is no problem
  967. if( dt.IsPrimitive() || dt.IsNullHandle() )
  968. {
  969. IsVariableInitialized(&ctx->type, node);
  970. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  971. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV, true);
  972. if( !(param.IsReadOnly() && ctx->type.isVariable) )
  973. ConvertToTempVariable(ctx);
  974. PushVariableOnStack(ctx, true);
  975. ctx->type.dataType.MakeReadOnly(param.IsReadOnly());
  976. }
  977. else
  978. {
  979. IsVariableInitialized(&ctx->type, node);
  980. if( !isMakingCopy )
  981. {
  982. ImplicitConversion(ctx, param, node, asIC_IMPLICIT_CONV, true);
  983. if( !ctx->type.dataType.IsEqualExceptRef(param) )
  984. {
  985. asCString str;
  986. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), param.Format().AddressOf());
  987. Error(str.AddressOf(), node);
  988. ctx->type.Set(param);
  989. }
  990. }
  991. // If the argument already is a temporary
  992. // variable we don't need to allocate another
  993. // If the parameter is read-only and the object already is a local
  994. // variable then it is not necessary to make a copy either
  995. if( !ctx->type.isTemporary && !(param.IsReadOnly() && ctx->type.isVariable) && !isMakingCopy )
  996. {
  997. // Make sure the variable is not used in the expression
  998. offset = AllocateVariableNotIn(dt, true, false, ctx);
  999. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  1000. // Allocate and construct the temporary object
  1001. asCByteCode tmpBC(engine);
  1002. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  1003. // Insert the code before the expression code
  1004. tmpBC.AddCode(&ctx->bc);
  1005. ctx->bc.AddCode(&tmpBC);
  1006. // Assign the evaluated expression to the temporary variable
  1007. PrepareForAssignment(&dt, ctx, node, true);
  1008. dt.MakeReference(IsVariableOnHeap(offset));
  1009. asCTypeInfo type;
  1010. type.Set(dt);
  1011. type.isTemporary = true;
  1012. type.stackOffset = (short)offset;
  1013. if( dt.IsObjectHandle() )
  1014. type.isExplicitHandle = true;
  1015. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1016. PerformAssignment(&type, &ctx->type, &ctx->bc, node);
  1017. ctx->bc.Pop(ctx->type.dataType.GetSizeOnStackDWords());
  1018. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  1019. ctx->type = type;
  1020. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1021. if( dt.IsObject() && !dt.IsObjectHandle() )
  1022. ctx->bc.Instr(asBC_RDSPtr);
  1023. if( paramType->IsReadOnly() )
  1024. ctx->type.dataType.MakeReadOnly(true);
  1025. }
  1026. else if( isMakingCopy )
  1027. {
  1028. // We must guarantee that the address to the value is on the stack
  1029. if( ctx->type.dataType.IsObject() &&
  1030. !ctx->type.dataType.IsObjectHandle() &&
  1031. ctx->type.dataType.IsReference() )
  1032. Dereference(ctx, true);
  1033. }
  1034. }
  1035. }
  1036. else if( refType == 2 ) // &out
  1037. {
  1038. // Make sure the variable is not used in the expression
  1039. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1040. if( dt.IsPrimitive() )
  1041. {
  1042. ctx->type.SetVariable(dt, offset, true);
  1043. PushVariableOnStack(ctx, true);
  1044. }
  1045. else
  1046. {
  1047. // Allocate and construct the temporary object
  1048. asCByteCode tmpBC(engine);
  1049. CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &tmpBC, node);
  1050. // Insert the code before the expression code
  1051. tmpBC.AddCode(&ctx->bc);
  1052. ctx->bc.AddCode(&tmpBC);
  1053. dt.MakeReference((!dt.IsObject() || dt.IsObjectHandle()));
  1054. asCTypeInfo type;
  1055. type.Set(dt);
  1056. type.isTemporary = true;
  1057. type.stackOffset = (short)offset;
  1058. ctx->type = type;
  1059. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  1060. if( dt.IsObject() && !dt.IsObjectHandle() )
  1061. ctx->bc.Instr(asBC_RDSPtr);
  1062. }
  1063. // After the function returns the temporary variable will
  1064. // be assigned to the expression, if it is a valid lvalue
  1065. }
  1066. else if( refType == asTM_INOUTREF )
  1067. {
  1068. ProcessPropertyGetAccessor(ctx, node);
  1069. // Literal constants cannot be passed to inout ref arguments
  1070. if( !ctx->type.isVariable && ctx->type.isConstant )
  1071. {
  1072. Error(TXT_NOT_VALID_REFERENCE, node);
  1073. }
  1074. // Only objects that support object handles
  1075. // can be guaranteed to be safe. Local variables are
  1076. // already safe, so there is no need to add an extra
  1077. // references
  1078. if( !engine->ep.allowUnsafeReferences &&
  1079. !ctx->type.isVariable &&
  1080. ctx->type.dataType.IsObject() &&
  1081. !ctx->type.dataType.IsObjectHandle() &&
  1082. ((ctx->type.dataType.GetBehaviour()->addref &&
  1083. ctx->type.dataType.GetBehaviour()->release) ||
  1084. (ctx->type.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) )
  1085. {
  1086. // Store a handle to the object as local variable
  1087. asSExprContext tmp(engine);
  1088. asCDataType dt = ctx->type.dataType;
  1089. dt.MakeHandle(true);
  1090. dt.MakeReference(false);
  1091. offset = AllocateVariableNotIn(dt, true, false, ctx);
  1092. // Copy the handle
  1093. if( !ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReference() )
  1094. ctx->bc.Instr(asBC_RDSPtr);
  1095. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1096. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  1097. ctx->bc.Pop(AS_PTR_SIZE);
  1098. ctx->bc.InstrWORD(asBC_PSF, (asWORD)offset);
  1099. dt.MakeHandle(false);
  1100. dt.MakeReference(true);
  1101. // Release previous temporary variable stored in the context (if any)
  1102. if( ctx->type.isTemporary )
  1103. {
  1104. ReleaseTemporaryVariable(ctx->type.stackOffset, &ctx->bc);
  1105. }
  1106. ctx->type.SetVariable(dt, offset, true);
  1107. }
  1108. // Make sure the reference to the value is on the stack
  1109. // For objects, the reference needs to be dereferenced so the pointer on the stack is to the actual object
  1110. // For handles, the reference shouldn't be changed because the pointer on the stack should be to the handle
  1111. if( ctx->type.dataType.IsObject() && ctx->type.dataType.IsReference() && !paramType->IsObjectHandle() )
  1112. Dereference(ctx, true);
  1113. else if( ctx->type.isVariable && !ctx->type.dataType.IsObject() )
  1114. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  1115. else if( ctx->type.dataType.IsPrimitive() )
  1116. ctx->bc.Instr(asBC_PshRPtr);
  1117. }
  1118. }
  1119. else
  1120. {
  1121. ProcessPropertyGetAccessor(ctx, node);
  1122. if( dt.IsPrimitive() )
  1123. {
  1124. IsVariableInitialized(&ctx->type, node);
  1125. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  1126. // Implicitly convert primitives to the parameter type
  1127. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  1128. if( ctx->type.isVariable )
  1129. {
  1130. PushVariableOnStack(ctx, dt.IsReference());
  1131. }
  1132. else if( ctx->type.isConstant )
  1133. {
  1134. ConvertToVariable(ctx);
  1135. PushVariableOnStack(ctx, dt.IsReference());
  1136. }
  1137. }
  1138. else
  1139. {
  1140. IsVariableInitialized(&ctx->type, node);
  1141. // Implicitly convert primitives to the parameter type
  1142. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  1143. // Was the conversion successful?
  1144. if( !ctx->type.dataType.IsEqualExceptRef(dt) )
  1145. {
  1146. asCString str;
  1147. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), dt.Format().AddressOf());
  1148. Error(str.AddressOf(), node);
  1149. ctx->type.Set(dt);
  1150. }
  1151. if( dt.IsObjectHandle() )
  1152. ctx->type.isExplicitHandle = true;
  1153. if( dt.IsObject() )
  1154. {
  1155. if( !dt.IsReference() )
  1156. {
  1157. // Objects passed by value must be placed in temporary variables
  1158. // so that they are guaranteed to not be referenced anywhere else.
  1159. // The object must also be allocated on the heap, as the memory will
  1160. // be deleted by in as_callfunc_xxx.
  1161. // TODO: value on stack: How can we avoid this unnecessary allocation?
  1162. PrepareTemporaryObject(node, ctx, true);
  1163. // The implicit conversion shouldn't convert the object to
  1164. // non-reference yet. It will be dereferenced just before the call.
  1165. // Otherwise the object might be missed by the exception handler.
  1166. dt.MakeReference(true);
  1167. }
  1168. else
  1169. {
  1170. // An object passed by reference should place the pointer to
  1171. // the object on the stack.
  1172. dt.MakeReference(false);
  1173. }
  1174. }
  1175. }
  1176. }
  1177. // Don't put any pointer on the stack yet
  1178. if( param.IsReference() || param.IsObject() )
  1179. {
  1180. // &inout parameter may leave the reference on the stack already
  1181. if( refType != 3 )
  1182. {
  1183. asASSERT( ctx->type.isVariable || ctx->type.isTemporary || isMakingCopy );
  1184. if( ctx->type.isVariable || ctx->type.isTemporary )
  1185. {
  1186. ctx->bc.Pop(AS_PTR_SIZE);
  1187. ctx->bc.InstrSHORT(asBC_VAR, ctx->type.stackOffset);
  1188. ProcessDeferredParams(ctx);
  1189. }
  1190. }
  1191. }
  1192. }
  1193. void asCCompiler::PrepareFunctionCall(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args)
  1194. {
  1195. // When a match has been found, compile the final byte code using correct parameter types
  1196. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1197. // If the function being called is the opAssign or copy constructor for the same type
  1198. // as the argument, then we should avoid making temporary copy of the argument
  1199. bool makingCopy = false;
  1200. if( descr->parameterTypes.GetLength() == 1 &&
  1201. descr->parameterTypes[0].IsEqualExceptRefAndConst(args[0]->type.dataType) &&
  1202. ((descr->name == "opAssign" && descr->objectType && descr->objectType == args[0]->type.dataType.GetObjectType()) ||
  1203. (args[0]->type.dataType.GetObjectType() && descr->name == args[0]->type.dataType.GetObjectType()->name)) )
  1204. makingCopy = true;
  1205. // Add code for arguments
  1206. asSExprContext e(engine);
  1207. for( int n = (int)args.GetLength()-1; n >= 0; n-- )
  1208. {
  1209. // Make sure PrepareArgument doesn't use any variable that is already
  1210. // being used by any of the following argument expressions
  1211. int l = int(reservedVariables.GetLength());
  1212. for( int m = n-1; m >= 0; m-- )
  1213. args[m]->bc.GetVarsUsed(reservedVariables);
  1214. PrepareArgument2(&e, args[n], &descr->parameterTypes[n], true, descr->inOutFlags[n], makingCopy);
  1215. reservedVariables.SetLength(l);
  1216. }
  1217. bc->AddCode(&e.bc);
  1218. }
  1219. void asCCompiler::MoveArgsToStack(int funcId, asCByteCode *bc, asCArray<asSExprContext *> &args, bool addOneToOffset)
  1220. {
  1221. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  1222. int offset = 0;
  1223. if( addOneToOffset )
  1224. offset += AS_PTR_SIZE;
  1225. // The address of where the return value should be stored is push on top of the arguments
  1226. if( descr->DoesReturnOnStack() )
  1227. offset += AS_PTR_SIZE;
  1228. #ifdef AS_DEBUG
  1229. // If the function being called is the opAssign or copy constructor for the same type
  1230. // as the argument, then we should avoid making temporary copy of the argument
  1231. bool makingCopy = false;
  1232. if( descr->parameterTypes.GetLength() == 1 &&
  1233. descr->parameterTypes[0].IsEqualExceptRefAndConst(args[0]->type.dataType) &&
  1234. ((descr->name == "opAssign" && descr->objectType && descr->objectType == args[0]->type.dataType.GetObjectType()) ||
  1235. (args[0]->type.dataType.GetObjectType() && descr->name == args[0]->type.dataType.GetObjectType()->name)) )
  1236. makingCopy = true;
  1237. #endif
  1238. // Move the objects that are sent by value to the stack just before the call
  1239. for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
  1240. {
  1241. if( descr->parameterTypes[n].IsReference() )
  1242. {
  1243. if( descr->parameterTypes[n].IsObject() && !descr->parameterTypes[n].IsObjectHandle() )
  1244. {
  1245. if( descr->inOutFlags[n] != asTM_INOUTREF )
  1246. {
  1247. #ifdef AS_DEBUG
  1248. asASSERT( args[n]->type.isVariable || args[n]->type.isTemporary || makingCopy );
  1249. #endif
  1250. if( (args[n]->type.isVariable || args[n]->type.isTemporary) )
  1251. {
  1252. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1253. // TODO: optimize: Actually the reference can be pushed on the stack directly
  1254. // as the value allocated on the stack is guaranteed to be safe
  1255. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1256. else
  1257. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1258. }
  1259. }
  1260. if( args[n]->type.dataType.IsObjectHandle() )
  1261. bc->InstrWORD(asBC_ChkNullS, (asWORD)offset);
  1262. }
  1263. else if( descr->inOutFlags[n] != asTM_INOUTREF )
  1264. {
  1265. if( descr->parameterTypes[n].GetTokenType() == ttQuestion &&
  1266. args[n]->type.dataType.IsObject() && !args[n]->type.dataType.IsObjectHandle() )
  1267. {
  1268. // Send the object as a reference to the object,
  1269. // and not to the variable holding the object
  1270. if( !IsVariableOnHeap(args[n]->type.stackOffset) )
  1271. // TODO: optimize: Actually the reference can be pushed on the stack directly
  1272. // as the value allocated on the stack is guaranteed to be safe
  1273. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1274. else
  1275. bc->InstrWORD(asBC_GETOBJREF, (asWORD)offset);
  1276. }
  1277. else
  1278. {
  1279. bc->InstrWORD(asBC_GETREF, (asWORD)offset);
  1280. }
  1281. }
  1282. }
  1283. else if( descr->parameterTypes[n].IsObject() )
  1284. {
  1285. // TODO: value on stack: What can we do to avoid this unnecessary allocation?
  1286. // The object must be allocated on the heap, because this memory will be deleted in as_callfunc_xxx
  1287. asASSERT(IsVariableOnHeap(args[n]->type.stackOffset));
  1288. bc->InstrWORD(asBC_GETOBJ, (asWORD)offset);
  1289. // The temporary variable must not be freed as it will no longer hold an object
  1290. DeallocateVariable(args[n]->type.stackOffset);
  1291. args[n]->type.isTemporary = false;
  1292. }
  1293. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  1294. }
  1295. }
  1296. int asCCompiler::CompileArgumentList(asCScriptNode *node, asCArray<asSExprContext*> &args)
  1297. {
  1298. asASSERT(node->nodeType == snArgList);
  1299. // Count arguments
  1300. asCScriptNode *arg = node->firstChild;
  1301. int argCount = 0;
  1302. while( arg )
  1303. {
  1304. argCount++;
  1305. arg = arg->next;
  1306. }
  1307. // Prepare the arrays
  1308. args.SetLength(argCount);
  1309. int n;
  1310. for( n = 0; n < argCount; n++ )
  1311. args[n] = 0;
  1312. n = argCount-1;
  1313. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1314. bool anyErrors = false;
  1315. arg = node->lastChild;
  1316. while( arg )
  1317. {
  1318. asSExprContext expr(engine);
  1319. int r = CompileAssignment(arg, &expr);
  1320. if( r < 0 ) anyErrors = true;
  1321. args[n] = asNEW(asSExprContext)(engine);
  1322. MergeExprBytecodeAndType(args[n], &expr);
  1323. n--;
  1324. arg = arg->prev;
  1325. }
  1326. return anyErrors ? -1 : 0;
  1327. }
  1328. int asCCompiler::CompileDefaultArgs(asCScriptNode *node, asCArray<asSExprContext*> &args, asCScriptFunction *func)
  1329. {
  1330. bool anyErrors = false;
  1331. asCArray<int> varsUsed;
  1332. int explicitArgs = (int)args.GetLength();
  1333. for( int p = 0; p < explicitArgs; p++ )
  1334. args[p]->bc.GetVarsUsed(varsUsed);
  1335. // Compile the arguments in reverse order (as they will be pushed on the stack)
  1336. args.SetLength(func->parameterTypes.GetLength());
  1337. for( asUINT c = explicitArgs; c < args.GetLength(); c++ )
  1338. args[c] = 0;
  1339. for( int n = (int)func->parameterTypes.GetLength() - 1; n >= explicitArgs; n-- )
  1340. {
  1341. if( func->defaultArgs[n] == 0 ) { anyErrors = true; continue; }
  1342. // Parse the default arg string
  1343. asCParser parser(builder);
  1344. asCScriptCode code;
  1345. code.SetCode("default arg", func->defaultArgs[n]->AddressOf(), false);
  1346. int r = parser.ParseExpression(&code);
  1347. if( r < 0 ) { anyErrors = true; continue; }
  1348. asCScriptNode *arg = parser.GetScriptNode();
  1349. // Temporarily set the script code to the default arg expression
  1350. asCScriptCode *origScript = script;
  1351. script = &code;
  1352. // Don't allow the expression to access local variables
  1353. // TODO: namespace: The default arg should see the symbols declared in the same scope as the function
  1354. isCompilingDefaultArg = true;
  1355. asSExprContext expr(engine);
  1356. r = CompileExpression(arg, &expr);
  1357. isCompilingDefaultArg = false;
  1358. script = origScript;
  1359. if( r < 0 )
  1360. {
  1361. asCString msg;
  1362. msg.Format(TXT_FAILED_TO_COMPILE_DEF_ARG_d_IN_FUNC_s, n, func->GetDeclaration());
  1363. Error(msg.AddressOf(), node);
  1364. anyErrors = true;
  1365. continue;
  1366. }
  1367. args[n] = asNEW(asSExprContext)(engine);
  1368. MergeExprBytecodeAndType(args[n], &expr);
  1369. // Make sure the default arg expression doesn't end up
  1370. // with a variable that is used in a previous expression
  1371. if( args[n]->type.isVariable )
  1372. {
  1373. int offset = args[n]->type.stackOffset;
  1374. if( varsUsed.Exists(offset) )
  1375. {
  1376. // Release the current temporary variable
  1377. ReleaseTemporaryVariable(args[n]->type, 0);
  1378. asCDataType dt = args[n]->type.dataType;
  1379. dt.MakeReference(false);
  1380. int newOffset = AllocateVariable(dt, true, IsVariableOnHeap(offset));
  1381. asASSERT( IsVariableOnHeap(offset) == IsVariableOnHeap(newOffset) );
  1382. args[n]->bc.ExchangeVar(offset, newOffset);
  1383. args[n]->type.stackOffset = (short)newOffset;
  1384. args[n]->type.isTemporary = true;
  1385. args[n]->type.isVariable = true;
  1386. }
  1387. }
  1388. }
  1389. return anyErrors ? -1 : 0;
  1390. }
  1391. asUINT asCCompiler::MatchFunctions(asCArray<int> &funcs, asCArray<asSExprContext*> &args, asCScriptNode *node, const char *name, asCObjectType *objectType, bool isConstMethod, bool silent, bool allowObjectConstruct, const asCString &scope)
  1392. {
  1393. asCArray<int> origFuncs = funcs; // Keep the original list for error message
  1394. asUINT cost = 0;
  1395. asUINT n;
  1396. if( funcs.GetLength() > 0 )
  1397. {
  1398. // Check the number of parameters in the found functions
  1399. for( n = 0; n < funcs.GetLength(); ++n )
  1400. {
  1401. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  1402. if( desc->parameterTypes.GetLength() != args.GetLength() )
  1403. {
  1404. bool noMatch = true;
  1405. if( args.GetLength() < desc->parameterTypes.GetLength() )
  1406. {
  1407. // Count the number of default args
  1408. asUINT defaultArgs = 0;
  1409. for( asUINT d = 0; d < desc->defaultArgs.GetLength(); d++ )
  1410. if( desc->defaultArgs[d] )
  1411. defaultArgs++;
  1412. if( args.GetLength() >= desc->parameterTypes.GetLength() - defaultArgs )
  1413. noMatch = false;
  1414. }
  1415. if( noMatch )
  1416. {
  1417. // remove it from the list
  1418. if( n == funcs.GetLength()-1 )
  1419. funcs.PopLast();
  1420. else
  1421. funcs[n] = funcs.PopLast();
  1422. n--;
  1423. }
  1424. }
  1425. }
  1426. // Match functions with the parameters, and discard those that do not match
  1427. asCArray<int> matchingFuncs = funcs;
  1428. for( n = 0; n < args.GetLength(); ++n )
  1429. {
  1430. asCArray<int> tempFuncs;
  1431. cost += MatchArgument(funcs, tempFuncs, &args[n]->type, n, allowObjectConstruct);
  1432. // Intersect the found functions with the list of matching functions
  1433. for( asUINT f = 0; f < matchingFuncs.GetLength(); f++ )
  1434. {
  1435. asUINT c;
  1436. for( c = 0; c < tempFuncs.GetLength(); c++ )
  1437. {
  1438. if( matchingFuncs[f] == tempFuncs[c] )
  1439. break;
  1440. }
  1441. // Was the function a match?
  1442. if( c == tempFuncs.GetLength() )
  1443. {
  1444. // No, remove it from the list
  1445. if( f == matchingFuncs.GetLength()-1 )
  1446. matchingFuncs.PopLast();
  1447. else
  1448. matchingFuncs[f] = matchingFuncs.PopLast();
  1449. f--;
  1450. }
  1451. }
  1452. }
  1453. funcs = matchingFuncs;
  1454. }
  1455. if( !isConstMethod )
  1456. FilterConst(funcs);
  1457. if( funcs.GetLength() != 1 && !silent )
  1458. {
  1459. // Build a readable string of the function with parameter types
  1460. asCString str;
  1461. if( scope != "" )
  1462. {
  1463. if( scope == "::" )
  1464. str = scope;
  1465. else
  1466. str = scope + "::";
  1467. }
  1468. str += name;
  1469. str += "(";
  1470. if( args.GetLength() )
  1471. str += args[0]->type.dataType.Format();
  1472. for( n = 1; n < args.GetLength(); n++ )
  1473. str += ", " + args[n]->type.dataType.Format();
  1474. str += ")";
  1475. if( isConstMethod )
  1476. str += " const";
  1477. if( objectType && scope == "" )
  1478. str = objectType->name + "::" + str;
  1479. if( funcs.GetLength() == 0 )
  1480. {
  1481. str.Format(TXT_NO_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1482. Error(str.AddressOf(), node);
  1483. // Print the list of candidates
  1484. if( origFuncs.GetLength() > 0 )
  1485. {
  1486. int r = 0, c = 0;
  1487. asASSERT( node );
  1488. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  1489. builder->WriteInfo(script->name.AddressOf(), TXT_CANDIDATES_ARE, r, c, false);
  1490. PrintMatchingFuncs(origFuncs, node);
  1491. }
  1492. }
  1493. else
  1494. {
  1495. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, str.AddressOf());
  1496. Error(str.AddressOf(), node);
  1497. PrintMatchingFuncs(funcs, node);
  1498. }
  1499. }
  1500. return cost;
  1501. }
  1502. void asCCompiler::CompileDeclaration(asCScriptNode *decl, asCByteCode *bc)
  1503. {
  1504. // Get the data type
  1505. // TODO: namespace: Use correct implicit namespace from function
  1506. asCDataType type = builder->CreateDataTypeFromNode(decl->firstChild, script, "");
  1507. // Declare all variables in this declaration
  1508. asCScriptNode *node = decl->firstChild->next;
  1509. while( node )
  1510. {
  1511. // Is the type allowed?
  1512. if( !type.CanBeInstanciated() )
  1513. {
  1514. asCString str;
  1515. // TODO: Change to "'type' cannot be declared as variable"
  1516. str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format().AddressOf());
  1517. Error(str.AddressOf(), node);
  1518. // Use int instead to avoid further problems
  1519. type = asCDataType::CreatePrimitive(ttInt, false);
  1520. }
  1521. // A shared object may not declare variables of non-shared types
  1522. if( outFunc->IsShared() )
  1523. {
  1524. asCObjectType *ot = type.GetObjectType();
  1525. if( ot && !ot->IsShared() )
  1526. {
  1527. asCString msg;
  1528. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  1529. Error(msg.AddressOf(), decl);
  1530. }
  1531. }
  1532. // Get the name of the identifier
  1533. asCString name(&script->code[node->tokenPos], node->tokenLength);
  1534. // Verify that the name isn't used by a dynamic data type
  1535. if( engine->GetObjectType(name.AddressOf()) != 0 )
  1536. {
  1537. asCString str;
  1538. str.Format(TXT_ILLEGAL_VARIABLE_NAME_s, name.AddressOf());
  1539. Error(str.AddressOf(), node);
  1540. }
  1541. int offset = AllocateVariable(type, false);
  1542. if( variables->DeclareVariable(name.AddressOf(), type, offset, IsVariableOnHeap(offset)) < 0 )
  1543. {
  1544. asCString str;
  1545. str.Format(TXT_s_ALREADY_DECLARED, name.AddressOf());
  1546. Error(str.AddressOf(), node);
  1547. // Don't continue after this error, as it will just
  1548. // lead to more errors that are likely false
  1549. return;
  1550. }
  1551. // Add marker that the variable has been declared
  1552. bc->VarDecl((int)outFunc->variables.GetLength());
  1553. outFunc->AddVariable(name, type, offset);
  1554. // Keep the node for the variable decl
  1555. asCScriptNode *varNode = node;
  1556. node = node->next;
  1557. if( node && node->nodeType == snArgList )
  1558. {
  1559. // Make sure that it is a registered type, and that is isn't a pointer
  1560. if( type.GetObjectType() == 0 || type.IsObjectHandle() )
  1561. {
  1562. Error(TXT_MUST_BE_OBJECT, node);
  1563. }
  1564. else
  1565. {
  1566. // Compile the arguments
  1567. asCArray<asSExprContext *> args;
  1568. if( CompileArgumentList(node, args) >= 0 )
  1569. {
  1570. // Find all constructors
  1571. asCArray<int> funcs;
  1572. asSTypeBehaviour *beh = type.GetBehaviour();
  1573. if( beh )
  1574. {
  1575. if( type.GetObjectType()->flags & asOBJ_REF )
  1576. funcs = beh->factories;
  1577. else
  1578. funcs = beh->constructors;
  1579. }
  1580. asCString str = type.Format();
  1581. MatchFunctions(funcs, args, node, str.AddressOf());
  1582. if( funcs.GetLength() == 1 )
  1583. {
  1584. int r = asSUCCESS;
  1585. // Add the default values for arguments not explicitly supplied
  1586. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  1587. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  1588. r = CompileDefaultArgs(node, args, func);
  1589. if( r == asSUCCESS )
  1590. {
  1591. sVariable *v = variables->GetVariable(name.AddressOf());
  1592. asSExprContext ctx(engine);
  1593. if( v->type.GetObjectType() && (v->type.GetObjectType()->flags & asOBJ_REF) )
  1594. {
  1595. MakeFunctionCall(&ctx, funcs[0], 0, args, node, true, v->stackOffset);
  1596. // Pop the reference left by the function call
  1597. ctx.bc.Pop(AS_PTR_SIZE);
  1598. }
  1599. else
  1600. {
  1601. // When the object is allocated on the heap, the address where the
  1602. // reference will be stored must be pushed on the stack before the
  1603. // arguments. This reference on the stack is safe, even if the script
  1604. // is suspended during the evaluation of the arguments.
  1605. if( v->onHeap )
  1606. ctx.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1607. PrepareFunctionCall(funcs[0], &ctx.bc, args);
  1608. MoveArgsToStack(funcs[0], &ctx.bc, args, false);
  1609. // When the object is allocated on the stack, the address to the
  1610. // object is pushed on the stack after the arguments as the object pointer
  1611. if( !v->onHeap )
  1612. ctx.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1613. PerformFunctionCall(funcs[0], &ctx, v->onHeap, &args, type.GetObjectType());
  1614. // TODO: value on stack: This probably has to be done in PerformFunctionCall
  1615. // Mark the object as initialized
  1616. ctx.bc.ObjInfo(v->stackOffset, asOBJ_INIT);
  1617. }
  1618. bc->AddCode(&ctx.bc);
  1619. }
  1620. }
  1621. }
  1622. // Cleanup
  1623. for( asUINT n = 0; n < args.GetLength(); n++ )
  1624. if( args[n] )
  1625. {
  1626. asDELETE(args[n],asSExprContext);
  1627. }
  1628. }
  1629. node = node->next;
  1630. }
  1631. else if( node && node->nodeType == snInitList )
  1632. {
  1633. sVariable *v = variables->GetVariable(name.AddressOf());
  1634. asCTypeInfo ti;
  1635. ti.Set(type);
  1636. ti.isVariable = true;
  1637. ti.isTemporary = false;
  1638. ti.stackOffset = (short)v->stackOffset;
  1639. ti.isLValue = true;
  1640. CompileInitList(&ti, node, bc);
  1641. node = node->next;
  1642. }
  1643. else if( node && node->nodeType == snAssignment )
  1644. {
  1645. asSExprContext ctx(engine);
  1646. // TODO: copy: Here we should look for the best matching constructor, instead of
  1647. // just the copy constructor. Only if no appropriate constructor is
  1648. // available should the assignment operator be used.
  1649. // Call the default constructor here
  1650. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), &ctx.bc, varNode);
  1651. // Compile the expression
  1652. asSExprContext expr(engine);
  1653. int r = CompileAssignment(node, &expr);
  1654. if( r >= 0 )
  1655. {
  1656. if( type.IsPrimitive() )
  1657. {
  1658. if( type.IsReadOnly() && expr.type.isConstant )
  1659. {
  1660. ImplicitConversion(&expr, type, node, asIC_IMPLICIT_CONV);
  1661. sVariable *v = variables->GetVariable(name.AddressOf());
  1662. v->isPureConstant = true;
  1663. v->constantValue = expr.type.qwordValue;
  1664. }
  1665. asSExprContext lctx(engine);
  1666. lctx.type.SetVariable(type, offset, false);
  1667. lctx.type.dataType.MakeReadOnly(false);
  1668. lctx.type.isLValue = true;
  1669. DoAssignment(&ctx, &lctx, &expr, node, node, ttAssignment, node);
  1670. ProcessDeferredParams(&ctx);
  1671. }
  1672. else
  1673. {
  1674. // TODO: optimize: We can use a copy constructor here
  1675. sVariable *v = variables->GetVariable(name.AddressOf());
  1676. asSExprContext lexpr(engine);
  1677. lexpr.type.Set(type);
  1678. lexpr.type.dataType.MakeReference(v->onHeap);
  1679. // Allow initialization of constant variables
  1680. lexpr.type.dataType.MakeReadOnly(false);
  1681. if( type.IsObjectHandle() )
  1682. lexpr.type.isExplicitHandle = true;
  1683. lexpr.bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  1684. lexpr.type.stackOffset = (short)v->stackOffset;
  1685. lexpr.type.isVariable = true;
  1686. lexpr.type.isLValue = true;
  1687. // If left expression resolves into a registered type
  1688. // check if the assignment operator is overloaded, and check
  1689. // the type of the right hand expression. If none is found
  1690. // the default action is a direct copy if it is the same type
  1691. // and a simple assignment.
  1692. bool assigned = false;
  1693. // Even though an ASHANDLE can be an explicit handle the overloaded operator needs to be called
  1694. if( lexpr.type.dataType.IsObject() && (!lexpr.type.isExplicitHandle || (lexpr.type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  1695. {
  1696. assigned = CompileOverloadedDualOperator(node, &lexpr, &expr, &ctx);
  1697. if( assigned )
  1698. {
  1699. // Pop the resulting value
  1700. ctx.bc.Pop(ctx.type.dataType.GetSizeOnStackDWords());
  1701. // Release the argument
  1702. ProcessDeferredParams(&ctx);
  1703. // Release temporary variable that may be allocated by the overloaded operator
  1704. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1705. }
  1706. }
  1707. if( !assigned )
  1708. {
  1709. PrepareForAssignment(&lexpr.type.dataType, &expr, node, false);
  1710. // If the expression is constant and the variable also is constant
  1711. // then mark the variable as pure constant. This will allow the compiler
  1712. // to optimize expressions with this variable.
  1713. if( v->type.IsReadOnly() && expr.type.isConstant )
  1714. {
  1715. v->isPureConstant = true;
  1716. v->constantValue = expr.type.qwordValue;
  1717. }
  1718. // Add expression code to bytecode
  1719. MergeExprBytecode(&ctx, &expr);
  1720. // Add byte code for storing value of expression in variable
  1721. ctx.bc.AddCode(&lexpr.bc);
  1722. lexpr.type.stackOffset = (short)v->stackOffset;
  1723. PerformAssignment(&lexpr.type, &expr.type, &ctx.bc, node->prev);
  1724. // Release temporary variables used by expression
  1725. ReleaseTemporaryVariable(expr.type, &ctx.bc);
  1726. ctx.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  1727. ProcessDeferredParams(&ctx);
  1728. }
  1729. }
  1730. }
  1731. node = node->next;
  1732. bc->AddCode(&ctx.bc);
  1733. }
  1734. else
  1735. {
  1736. // Call the default constructor here if no explicit initialization is done
  1737. CallDefaultConstructor(type, offset, IsVariableOnHeap(offset), bc, varNode);
  1738. }
  1739. }
  1740. }
  1741. void asCCompiler::CompileInitList(asCTypeInfo *var, asCScriptNode *node, asCByteCode *bc)
  1742. {
  1743. // Check if the type supports initialization lists
  1744. if( var->dataType.GetObjectType() == 0 ||
  1745. var->dataType.GetBehaviour()->listFactory == 0 ||
  1746. var->dataType.IsObjectHandle() )
  1747. {
  1748. asCString str;
  1749. str.Format(TXT_INIT_LIST_CANNOT_BE_USED_WITH_s, var->dataType.Format().AddressOf());
  1750. Error(str.AddressOf(), node);
  1751. return;
  1752. }
  1753. // Count the number of elements and initialize the array with the correct size
  1754. int countElements = 0;
  1755. asCScriptNode *el = node->firstChild;
  1756. while( el )
  1757. {
  1758. countElements++;
  1759. el = el->next;
  1760. }
  1761. // Construct the array with the size elements
  1762. // TODO: value on stack: This needs to support value types on the stack as well
  1763. // Find the list factory
  1764. // TODO: initlist: Add support for value types as well
  1765. int funcId = var->dataType.GetBehaviour()->listFactory;
  1766. asCArray<asSExprContext *> args;
  1767. asSExprContext arg1(engine);
  1768. arg1.bc.InstrDWORD(asBC_PshC4, countElements);
  1769. arg1.type.Set(asCDataType::CreatePrimitive(ttUInt, false));
  1770. args.PushLast(&arg1);
  1771. asSExprContext ctx(engine);
  1772. PrepareFunctionCall(funcId, &ctx.bc, args);
  1773. MoveArgsToStack(funcId, &ctx.bc, args, false);
  1774. if( var->isVariable )
  1775. {
  1776. // Call factory and store the handle in the given variable
  1777. PerformFunctionCall(funcId, &ctx, false, &args, 0, true, var->stackOffset);
  1778. ctx.bc.Pop(AS_PTR_SIZE);
  1779. }
  1780. else
  1781. {
  1782. PerformFunctionCall(funcId, &ctx, false, &args);
  1783. // Store the returned handle in the global variable
  1784. ctx.bc.Instr(asBC_RDSPtr);
  1785. ctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  1786. ctx.bc.InstrPTR(asBC_REFCPY, var->dataType.GetObjectType());
  1787. ctx.bc.Pop(AS_PTR_SIZE);
  1788. ReleaseTemporaryVariable(ctx.type.stackOffset, &ctx.bc);
  1789. }
  1790. bc->AddCode(&ctx.bc);
  1791. // TODO: initlist: Should we have a special indexing operator for this? How can we support
  1792. // initialization lists with different types for different elements? Maybe
  1793. // by using the variable arguments the initialization can be done with one
  1794. // call, passing all the elements as arguments. The registered function can
  1795. // then traverse them however it wants.
  1796. // Find the indexing operator that is not read-only that will be used for all elements
  1797. asCDataType retType;
  1798. retType = var->dataType.GetSubType();
  1799. retType.MakeReference(true);
  1800. retType.MakeReadOnly(false);
  1801. funcId = 0;
  1802. for( asUINT n = 0; n < var->dataType.GetObjectType()->methods.GetLength(); n++ )
  1803. {
  1804. asCScriptFunction *desc = builder->GetFunctionDescription(var->dataType.GetObjectType()->methods[n]);
  1805. if( !desc->isReadOnly &&
  1806. desc->parameterTypes.GetLength() == 1 &&
  1807. (desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttUInt, false) ||
  1808. desc->parameterTypes[0] == asCDataType::CreatePrimitive(ttInt, false)) &&
  1809. desc->returnType == retType &&
  1810. desc->name == "opIndex" )
  1811. {
  1812. funcId = var->dataType.GetObjectType()->methods[n];
  1813. break;
  1814. }
  1815. }
  1816. if( funcId == 0 )
  1817. {
  1818. Error(TXT_NO_APPROPRIATE_INDEX_OPERATOR, node);
  1819. return;
  1820. }
  1821. asUINT index = 0;
  1822. el = node->firstChild;
  1823. while( el )
  1824. {
  1825. if( el->nodeType == snAssignment || el->nodeType == snInitList )
  1826. {
  1827. asSExprContext lctx(engine);
  1828. asSExprContext rctx(engine);
  1829. if( el->nodeType == snAssignment )
  1830. {
  1831. // Compile the assignment expression
  1832. CompileAssignment(el, &rctx);
  1833. }
  1834. else if( el->nodeType == snInitList )
  1835. {
  1836. int offset = AllocateVariable(var->dataType.GetSubType(), true);
  1837. rctx.type.Set(var->dataType.GetSubType());
  1838. rctx.type.isVariable = true;
  1839. rctx.type.isTemporary = true;
  1840. rctx.type.stackOffset = (short)offset;
  1841. CompileInitList(&rctx.type, el, &rctx.bc);
  1842. // Put the object on the stack
  1843. rctx.bc.InstrSHORT(asBC_PSF, rctx.type.stackOffset);
  1844. // It is a reference that we place on the stack
  1845. rctx.type.dataType.MakeReference(true);
  1846. }
  1847. // Compile the lvalue
  1848. lctx.bc.InstrDWORD(asBC_PshC4, index);
  1849. if( var->isVariable )
  1850. lctx.bc.InstrSHORT(asBC_PSF, var->stackOffset);
  1851. else
  1852. lctx.bc.InstrPTR(asBC_PGA, engine->globalProperties[var->stackOffset]->GetAddressOfValue());
  1853. lctx.bc.Instr(asBC_RDSPtr);
  1854. lctx.bc.Call(asBC_CALLSYS, funcId, 1+AS_PTR_SIZE);
  1855. if( !var->dataType.GetSubType().IsPrimitive() )
  1856. lctx.bc.Instr(asBC_PshRPtr);
  1857. lctx.type.Set(var->dataType.GetSubType());
  1858. if( !lctx.type.dataType.IsObject() || lctx.type.dataType.IsObjectHandle() )
  1859. lctx.type.dataType.MakeReference(true);
  1860. // If the element type is handles, then we're expected to do handle assignments
  1861. if( lctx.type.dataType.IsObjectHandle() )
  1862. lctx.type.isExplicitHandle = true;
  1863. lctx.type.isLValue = true;
  1864. asSExprContext ctx(engine);
  1865. DoAssignment(&ctx, &lctx, &rctx, el, el, ttAssignment, el);
  1866. if( !lctx.type.dataType.IsPrimitive() )
  1867. ctx.bc.Pop(AS_PTR_SIZE);
  1868. // Release temporary variables used by expression
  1869. ReleaseTemporaryVariable(ctx.type, &ctx.bc);
  1870. ProcessDeferredParams(&ctx);
  1871. bc->AddCode(&ctx.bc);
  1872. }
  1873. el = el->next;
  1874. index++;
  1875. }
  1876. }
  1877. void asCCompiler::CompileStatement(asCScriptNode *statement, bool *hasReturn, asCByteCode *bc)
  1878. {
  1879. *hasReturn = false;
  1880. if( statement->nodeType == snStatementBlock )
  1881. CompileStatementBlock(statement, true, hasReturn, bc);
  1882. else if( statement->nodeType == snIf )
  1883. CompileIfStatement(statement, hasReturn, bc);
  1884. else if( statement->nodeType == snFor )
  1885. CompileForStatement(statement, bc);
  1886. else if( statement->nodeType == snWhile )
  1887. CompileWhileStatement(statement, bc);
  1888. else if( statement->nodeType == snDoWhile )
  1889. CompileDoWhileStatement(statement, bc);
  1890. else if( statement->nodeType == snExpressionStatement )
  1891. CompileExpressionStatement(statement, bc);
  1892. else if( statement->nodeType == snBreak )
  1893. CompileBreakStatement(statement, bc);
  1894. else if( statement->nodeType == snContinue )
  1895. CompileContinueStatement(statement, bc);
  1896. else if( statement->nodeType == snSwitch )
  1897. CompileSwitchStatement(statement, hasReturn, bc);
  1898. else if( statement->nodeType == snReturn )
  1899. {
  1900. CompileReturnStatement(statement, bc);
  1901. *hasReturn = true;
  1902. }
  1903. }
  1904. void asCCompiler::CompileSwitchStatement(asCScriptNode *snode, bool *, asCByteCode *bc)
  1905. {
  1906. // TODO: inheritance: Must guarantee that all options in the switch case call a constructor, or that none call it.
  1907. // Reserve label for break statements
  1908. int breakLabel = nextLabel++;
  1909. breakLabels.PushLast(breakLabel);
  1910. // Add a variable scope that will be used by CompileBreak
  1911. // to know where to stop deallocating variables
  1912. AddVariableScope(true, false);
  1913. //---------------------------
  1914. // Compile the switch expression
  1915. //-------------------------------
  1916. // Compile the switch expression
  1917. asSExprContext expr(engine);
  1918. CompileAssignment(snode->firstChild, &expr);
  1919. // Verify that the expression is a primitive type
  1920. if( !expr.type.dataType.IsIntegerType() && !expr.type.dataType.IsUnsignedType() && !expr.type.dataType.IsEnumType() )
  1921. {
  1922. Error(TXT_SWITCH_MUST_BE_INTEGRAL, snode->firstChild);
  1923. return;
  1924. }
  1925. ProcessPropertyGetAccessor(&expr, snode);
  1926. // TODO: Need to support 64bit integers
  1927. // Convert the expression to a 32bit variable
  1928. asCDataType to;
  1929. if( expr.type.dataType.IsIntegerType() || expr.type.dataType.IsEnumType() )
  1930. to.SetTokenType(ttInt);
  1931. else if( expr.type.dataType.IsUnsignedType() )
  1932. to.SetTokenType(ttUInt);
  1933. // Make sure the value is in a variable
  1934. if( expr.type.dataType.IsReference() )
  1935. ConvertToVariable(&expr);
  1936. ImplicitConversion(&expr, to, snode->firstChild, asIC_IMPLICIT_CONV, true);
  1937. ConvertToVariable(&expr);
  1938. int offset = expr.type.stackOffset;
  1939. ProcessDeferredParams(&expr);
  1940. //-------------------------------
  1941. // Determine case values and labels
  1942. //--------------------------------
  1943. // Remember the first label so that we can later pass the
  1944. // correct label to each CompileCase()
  1945. int firstCaseLabel = nextLabel;
  1946. int defaultLabel = 0;
  1947. asCArray<int> caseValues;
  1948. asCArray<int> caseLabels;
  1949. // Compile all case comparisons and make them jump to the right label
  1950. asCScriptNode *cnode = snode->firstChild->next;
  1951. while( cnode )
  1952. {
  1953. // Each case should have a constant expression
  1954. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  1955. {
  1956. // Compile expression
  1957. asSExprContext c(engine);
  1958. CompileExpression(cnode->firstChild, &c);
  1959. // Verify that the result is a constant
  1960. if( !c.type.isConstant )
  1961. Error(TXT_SWITCH_CASE_MUST_BE_CONSTANT, cnode->firstChild);
  1962. // Verify that the result is an integral number
  1963. if( !c.type.dataType.IsIntegerType() && !c.type.dataType.IsUnsignedType() && !c.type.dataType.IsEnumType() )
  1964. Error(TXT_SWITCH_MUST_BE_INTEGRAL, cnode->firstChild);
  1965. ImplicitConversion(&c, to, cnode->firstChild, asIC_IMPLICIT_CONV, true);
  1966. // Has this case been declared already?
  1967. if( caseValues.IndexOf(c.type.intValue) >= 0 )
  1968. {
  1969. Error(TXT_DUPLICATE_SWITCH_CASE, cnode->firstChild);
  1970. }
  1971. // TODO: Optimize: We can insert the numbers sorted already
  1972. // Store constant for later use
  1973. caseValues.PushLast(c.type.intValue);
  1974. // Reserve label for this case
  1975. caseLabels.PushLast(nextLabel++);
  1976. }
  1977. else
  1978. {
  1979. // Is default the last case?
  1980. if( cnode->next )
  1981. {
  1982. Error(TXT_DEFAULT_MUST_BE_LAST, cnode);
  1983. break;
  1984. }
  1985. // Reserve label for this case
  1986. defaultLabel = nextLabel++;
  1987. }
  1988. cnode = cnode->next;
  1989. }
  1990. // check for empty switch
  1991. if (caseValues.GetLength() == 0)
  1992. {
  1993. Error(TXT_EMPTY_SWITCH, snode);
  1994. return;
  1995. }
  1996. if( defaultLabel == 0 )
  1997. defaultLabel = breakLabel;
  1998. //---------------------------------
  1999. // Output the optimized case comparisons
  2000. // with jumps to the case code
  2001. //------------------------------------
  2002. // Sort the case values by increasing value. Do the sort together with the labels
  2003. // A simple bubble sort is sufficient since we don't expect a huge number of values
  2004. for( asUINT fwd = 1; fwd < caseValues.GetLength(); fwd++ )
  2005. {
  2006. for( int bck = fwd - 1; bck >= 0; bck-- )
  2007. {
  2008. int bckp = bck + 1;
  2009. if( caseValues[bck] > caseValues[bckp] )
  2010. {
  2011. // Swap the values in both arrays
  2012. int swap = caseValues[bckp];
  2013. caseValues[bckp] = caseValues[bck];
  2014. caseValues[bck] = swap;
  2015. swap = caseLabels[bckp];
  2016. caseLabels[bckp] = caseLabels[bck];
  2017. caseLabels[bck] = swap;
  2018. }
  2019. else
  2020. break;
  2021. }
  2022. }
  2023. // Find ranges of consecutive numbers
  2024. asCArray<int> ranges;
  2025. ranges.PushLast(0);
  2026. asUINT n;
  2027. for( n = 1; n < caseValues.GetLength(); ++n )
  2028. {
  2029. // We can join numbers that are less than 5 numbers
  2030. // apart since the output code will still be smaller
  2031. if( caseValues[n] > caseValues[n-1] + 5 )
  2032. ranges.PushLast(n);
  2033. }
  2034. // If the value is larger than the largest case value, jump to default
  2035. int tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2036. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[caseValues.GetLength()-1]);
  2037. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2038. expr.bc.InstrDWORD(asBC_JP, defaultLabel);
  2039. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2040. // TODO: optimize: We could possibly optimize this even more by doing a
  2041. // binary search instead of a linear search through the ranges
  2042. // For each range
  2043. int range;
  2044. for( range = 0; range < (int)ranges.GetLength(); range++ )
  2045. {
  2046. // Find the largest value in this range
  2047. int maxRange = caseValues[ranges[range]];
  2048. int index = ranges[range];
  2049. for( ; (index < (int)caseValues.GetLength()) && (caseValues[index] <= maxRange + 5); index++ )
  2050. maxRange = caseValues[index];
  2051. // If there are only 2 numbers then it is better to compare them directly
  2052. if( index - ranges[range] > 2 )
  2053. {
  2054. // If the value is smaller than the smallest case value in the range, jump to default
  2055. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2056. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  2057. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2058. expr.bc.InstrDWORD(asBC_JS, defaultLabel);
  2059. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2060. int nextRangeLabel = nextLabel++;
  2061. // If this is the last range we don't have to make this test
  2062. if( range < (int)ranges.GetLength() - 1 )
  2063. {
  2064. // If the value is larger than the largest case value in the range, jump to the next range
  2065. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2066. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, maxRange);
  2067. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2068. expr.bc.InstrDWORD(asBC_JP, nextRangeLabel);
  2069. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2070. }
  2071. // Jump forward according to the value
  2072. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2073. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[ranges[range]]);
  2074. expr.bc.InstrW_W_W(asBC_SUBi, tmpOffset, offset, tmpOffset);
  2075. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2076. expr.bc.JmpP(tmpOffset, maxRange - caseValues[ranges[range]]);
  2077. // Add the list of jumps to the correct labels (any holes, jump to default)
  2078. index = ranges[range];
  2079. for( int n = caseValues[index]; n <= maxRange; n++ )
  2080. {
  2081. if( caseValues[index] == n )
  2082. expr.bc.InstrINT(asBC_JMP, caseLabels[index++]);
  2083. else
  2084. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  2085. }
  2086. expr.bc.Label((short)nextRangeLabel);
  2087. }
  2088. else
  2089. {
  2090. // Simply make a comparison with each value
  2091. int n;
  2092. for( n = ranges[range]; n < index; ++n )
  2093. {
  2094. tmpOffset = AllocateVariable(asCDataType::CreatePrimitive(ttInt, false), true);
  2095. expr.bc.InstrSHORT_DW(asBC_SetV4, (short)tmpOffset, caseValues[n]);
  2096. expr.bc.InstrW_W(asBC_CMPi, offset, tmpOffset);
  2097. expr.bc.InstrDWORD(asBC_JZ, caseLabels[n]);
  2098. ReleaseTemporaryVariable(tmpOffset, &expr.bc);
  2099. }
  2100. }
  2101. }
  2102. // Catch any value that falls trough
  2103. expr.bc.InstrINT(asBC_JMP, defaultLabel);
  2104. // Release the temporary variable previously stored
  2105. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2106. //----------------------------------
  2107. // Output case implementations
  2108. //----------------------------------
  2109. // Compile case implementations, each one with the label before it
  2110. cnode = snode->firstChild->next;
  2111. while( cnode )
  2112. {
  2113. // Each case should have a constant expression
  2114. if( cnode->firstChild && cnode->firstChild->nodeType == snExpression )
  2115. {
  2116. expr.bc.Label((short)firstCaseLabel++);
  2117. CompileCase(cnode->firstChild->next, &expr.bc);
  2118. }
  2119. else
  2120. {
  2121. expr.bc.Label((short)defaultLabel);
  2122. // Is default the last case?
  2123. if( cnode->next )
  2124. {
  2125. // We've already reported this error
  2126. break;
  2127. }
  2128. CompileCase(cnode->firstChild, &expr.bc);
  2129. }
  2130. cnode = cnode->next;
  2131. }
  2132. //--------------------------------
  2133. bc->AddCode(&expr.bc);
  2134. // Add break label
  2135. bc->Label((short)breakLabel);
  2136. breakLabels.PopLast();
  2137. RemoveVariableScope();
  2138. }
  2139. void asCCompiler::CompileCase(asCScriptNode *node, asCByteCode *bc)
  2140. {
  2141. bool isFinished = false;
  2142. bool hasReturn = false;
  2143. while( node )
  2144. {
  2145. if( hasReturn || isFinished )
  2146. {
  2147. Warning(TXT_UNREACHABLE_CODE, node);
  2148. break;
  2149. }
  2150. if( node->nodeType == snBreak || node->nodeType == snContinue )
  2151. isFinished = true;
  2152. asCByteCode statement(engine);
  2153. if( node->nodeType == snDeclaration )
  2154. {
  2155. Error(TXT_DECL_IN_SWITCH, node);
  2156. // Compile it anyway to avoid further compiler errors
  2157. CompileDeclaration(node, &statement);
  2158. }
  2159. else
  2160. CompileStatement(node, &hasReturn, &statement);
  2161. LineInstr(bc, node->tokenPos);
  2162. bc->AddCode(&statement);
  2163. if( !hasCompileErrors )
  2164. asASSERT( tempVariables.GetLength() == 0 );
  2165. node = node->next;
  2166. }
  2167. }
  2168. void asCCompiler::CompileIfStatement(asCScriptNode *inode, bool *hasReturn, asCByteCode *bc)
  2169. {
  2170. // We will use one label for the if statement
  2171. // and possibly another for the else statement
  2172. int afterLabel = nextLabel++;
  2173. // Compile the expression
  2174. asSExprContext expr(engine);
  2175. CompileAssignment(inode->firstChild, &expr);
  2176. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2177. {
  2178. Error(TXT_EXPR_MUST_BE_BOOL, inode->firstChild);
  2179. expr.type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 1);
  2180. }
  2181. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2182. ProcessDeferredParams(&expr);
  2183. if( !expr.type.isConstant )
  2184. {
  2185. ProcessPropertyGetAccessor(&expr, inode);
  2186. ConvertToVariable(&expr);
  2187. // Add byte code from the expression
  2188. bc->AddCode(&expr.bc);
  2189. // Add a test
  2190. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2191. bc->Instr(asBC_ClrHi);
  2192. bc->InstrDWORD(asBC_JZ, afterLabel);
  2193. ReleaseTemporaryVariable(expr.type, bc);
  2194. }
  2195. else if( expr.type.dwordValue == 0 )
  2196. {
  2197. // Jump to the else case
  2198. bc->InstrINT(asBC_JMP, afterLabel);
  2199. // TODO: Should we warn that the expression will always go to the else?
  2200. }
  2201. // Compile the if statement
  2202. bool origIsConstructorCalled = m_isConstructorCalled;
  2203. bool hasReturn1;
  2204. asCByteCode ifBC(engine);
  2205. CompileStatement(inode->firstChild->next, &hasReturn1, &ifBC);
  2206. // Add the byte code
  2207. LineInstr(bc, inode->firstChild->next->tokenPos);
  2208. bc->AddCode(&ifBC);
  2209. if( inode->firstChild->next->nodeType == snExpressionStatement && inode->firstChild->next->firstChild == 0 )
  2210. {
  2211. // Don't allow if( expr );
  2212. Error(TXT_IF_WITH_EMPTY_STATEMENT, inode->firstChild->next);
  2213. }
  2214. // If one of the statements call the constructor, the other must as well
  2215. // otherwise it is possible the constructor is never called
  2216. bool constructorCall1 = false;
  2217. bool constructorCall2 = false;
  2218. if( !origIsConstructorCalled && m_isConstructorCalled )
  2219. constructorCall1 = true;
  2220. // Do we have an else statement?
  2221. if( inode->firstChild->next != inode->lastChild )
  2222. {
  2223. // Reset the constructor called flag so the else statement can call the constructor too
  2224. m_isConstructorCalled = origIsConstructorCalled;
  2225. int afterElse = 0;
  2226. if( !hasReturn1 )
  2227. {
  2228. afterElse = nextLabel++;
  2229. // Add jump to after the else statement
  2230. bc->InstrINT(asBC_JMP, afterElse);
  2231. }
  2232. // Add label for the else statement
  2233. bc->Label((short)afterLabel);
  2234. bool hasReturn2;
  2235. asCByteCode elseBC(engine);
  2236. CompileStatement(inode->lastChild, &hasReturn2, &elseBC);
  2237. // Add byte code for the else statement
  2238. LineInstr(bc, inode->lastChild->tokenPos);
  2239. bc->AddCode(&elseBC);
  2240. if( inode->lastChild->nodeType == snExpressionStatement && inode->lastChild->firstChild == 0 )
  2241. {
  2242. // Don't allow if( expr ) {} else;
  2243. Error(TXT_ELSE_WITH_EMPTY_STATEMENT, inode->lastChild);
  2244. }
  2245. if( !hasReturn1 )
  2246. {
  2247. // Add label for the end of else statement
  2248. bc->Label((short)afterElse);
  2249. }
  2250. // The if statement only has return if both alternatives have
  2251. *hasReturn = hasReturn1 && hasReturn2;
  2252. if( !origIsConstructorCalled && m_isConstructorCalled )
  2253. constructorCall2 = true;
  2254. }
  2255. else
  2256. {
  2257. // Add label for the end of if statement
  2258. bc->Label((short)afterLabel);
  2259. *hasReturn = false;
  2260. }
  2261. // Make sure both or neither conditions call a constructor
  2262. if( (constructorCall1 && !constructorCall2) ||
  2263. (constructorCall2 && !constructorCall1) )
  2264. {
  2265. Error(TXT_BOTH_CONDITIONS_MUST_CALL_CONSTRUCTOR, inode);
  2266. }
  2267. m_isConstructorCalled = origIsConstructorCalled || constructorCall1 || constructorCall2;
  2268. }
  2269. void asCCompiler::CompileForStatement(asCScriptNode *fnode, asCByteCode *bc)
  2270. {
  2271. // TODO: optimize: We should be able to remove the static JMP to the beginning of the loop by rearranging the
  2272. // byte code a bit.
  2273. //
  2274. // init
  2275. // jump to before
  2276. // begin:
  2277. // statements
  2278. // continue:
  2279. // next
  2280. // before:
  2281. // condition
  2282. // if loop jump to begin
  2283. // break:
  2284. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2285. AddVariableScope(true, true);
  2286. // We will use three labels for the for loop
  2287. int beforeLabel = nextLabel++;
  2288. int afterLabel = nextLabel++;
  2289. int continueLabel = nextLabel++;
  2290. continueLabels.PushLast(continueLabel);
  2291. breakLabels.PushLast(afterLabel);
  2292. //---------------------------------------
  2293. // Compile the initialization statement
  2294. asCByteCode initBC(engine);
  2295. if( fnode->firstChild->nodeType == snDeclaration )
  2296. CompileDeclaration(fnode->firstChild, &initBC);
  2297. else
  2298. CompileExpressionStatement(fnode->firstChild, &initBC);
  2299. //-----------------------------------
  2300. // Compile the condition statement
  2301. asSExprContext expr(engine);
  2302. asCScriptNode *second = fnode->firstChild->next;
  2303. if( second->firstChild )
  2304. {
  2305. int r = CompileAssignment(second->firstChild, &expr);
  2306. if( r >= 0 )
  2307. {
  2308. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2309. Error(TXT_EXPR_MUST_BE_BOOL, second);
  2310. else
  2311. {
  2312. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2313. ProcessDeferredParams(&expr);
  2314. ProcessPropertyGetAccessor(&expr, second);
  2315. // If expression is false exit the loop
  2316. ConvertToVariable(&expr);
  2317. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2318. expr.bc.Instr(asBC_ClrHi);
  2319. expr.bc.InstrDWORD(asBC_JZ, afterLabel);
  2320. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2321. }
  2322. }
  2323. }
  2324. //---------------------------
  2325. // Compile the increment statement
  2326. asCByteCode nextBC(engine);
  2327. asCScriptNode *third = second->next;
  2328. if( third->nodeType == snExpressionStatement )
  2329. CompileExpressionStatement(third, &nextBC);
  2330. //------------------------------
  2331. // Compile loop statement
  2332. bool hasReturn;
  2333. asCByteCode forBC(engine);
  2334. CompileStatement(fnode->lastChild, &hasReturn, &forBC);
  2335. //-------------------------------
  2336. // Join the code pieces
  2337. bc->AddCode(&initBC);
  2338. bc->Label((short)beforeLabel);
  2339. // Add a suspend bytecode inside the loop to guarantee
  2340. // that the application can suspend the execution
  2341. bc->Instr(asBC_SUSPEND);
  2342. bc->InstrPTR(asBC_JitEntry, 0);
  2343. bc->AddCode(&expr.bc);
  2344. LineInstr(bc, fnode->lastChild->tokenPos);
  2345. bc->AddCode(&forBC);
  2346. bc->Label((short)continueLabel);
  2347. bc->AddCode(&nextBC);
  2348. bc->InstrINT(asBC_JMP, beforeLabel);
  2349. bc->Label((short)afterLabel);
  2350. continueLabels.PopLast();
  2351. breakLabels.PopLast();
  2352. // Deallocate variables in this block, in reverse order
  2353. for( int n = (int)variables->variables.GetLength() - 1; n >= 0; n-- )
  2354. {
  2355. sVariable *v = variables->variables[n];
  2356. // Call variable destructors here, for variables not yet destroyed
  2357. CallDestructor(v->type, v->stackOffset, v->onHeap, bc);
  2358. // Don't deallocate function parameters
  2359. if( v->stackOffset > 0 )
  2360. DeallocateVariable(v->stackOffset);
  2361. }
  2362. RemoveVariableScope();
  2363. }
  2364. void asCCompiler::CompileWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2365. {
  2366. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2367. AddVariableScope(true, true);
  2368. // We will use two labels for the while loop
  2369. int beforeLabel = nextLabel++;
  2370. int afterLabel = nextLabel++;
  2371. continueLabels.PushLast(beforeLabel);
  2372. breakLabels.PushLast(afterLabel);
  2373. // Add label before the expression
  2374. bc->Label((short)beforeLabel);
  2375. // Compile expression
  2376. asSExprContext expr(engine);
  2377. CompileAssignment(wnode->firstChild, &expr);
  2378. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2379. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2380. else
  2381. {
  2382. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2383. ProcessDeferredParams(&expr);
  2384. ProcessPropertyGetAccessor(&expr, wnode);
  2385. // Add byte code for the expression
  2386. ConvertToVariable(&expr);
  2387. bc->AddCode(&expr.bc);
  2388. // Jump to end of statement if expression is false
  2389. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2390. bc->Instr(asBC_ClrHi);
  2391. bc->InstrDWORD(asBC_JZ, afterLabel);
  2392. ReleaseTemporaryVariable(expr.type, bc);
  2393. }
  2394. // Add a suspend bytecode inside the loop to guarantee
  2395. // that the application can suspend the execution
  2396. bc->Instr(asBC_SUSPEND);
  2397. bc->InstrPTR(asBC_JitEntry, 0);
  2398. // Compile statement
  2399. bool hasReturn;
  2400. asCByteCode whileBC(engine);
  2401. CompileStatement(wnode->lastChild, &hasReturn, &whileBC);
  2402. // Add byte code for the statement
  2403. LineInstr(bc, wnode->lastChild->tokenPos);
  2404. bc->AddCode(&whileBC);
  2405. // Jump to the expression
  2406. bc->InstrINT(asBC_JMP, beforeLabel);
  2407. // Add label after the statement
  2408. bc->Label((short)afterLabel);
  2409. continueLabels.PopLast();
  2410. breakLabels.PopLast();
  2411. RemoveVariableScope();
  2412. }
  2413. void asCCompiler::CompileDoWhileStatement(asCScriptNode *wnode, asCByteCode *bc)
  2414. {
  2415. // Add a variable scope that will be used by CompileBreak/Continue to know where to stop deallocating variables
  2416. AddVariableScope(true, true);
  2417. // We will use two labels for the while loop
  2418. int beforeLabel = nextLabel++;
  2419. int beforeTest = nextLabel++;
  2420. int afterLabel = nextLabel++;
  2421. continueLabels.PushLast(beforeTest);
  2422. breakLabels.PushLast(afterLabel);
  2423. // Add label before the statement
  2424. bc->Label((short)beforeLabel);
  2425. // Compile statement
  2426. bool hasReturn;
  2427. asCByteCode whileBC(engine);
  2428. CompileStatement(wnode->firstChild, &hasReturn, &whileBC);
  2429. // Add byte code for the statement
  2430. LineInstr(bc, wnode->firstChild->tokenPos);
  2431. bc->AddCode(&whileBC);
  2432. // Add label before the expression
  2433. bc->Label((short)beforeTest);
  2434. // Add a suspend bytecode inside the loop to guarantee
  2435. // that the application can suspend the execution
  2436. bc->Instr(asBC_SUSPEND);
  2437. bc->InstrPTR(asBC_JitEntry, 0);
  2438. // Add a line instruction
  2439. LineInstr(bc, wnode->lastChild->tokenPos);
  2440. // Compile expression
  2441. asSExprContext expr(engine);
  2442. CompileAssignment(wnode->lastChild, &expr);
  2443. if( !expr.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  2444. Error(TXT_EXPR_MUST_BE_BOOL, wnode->firstChild);
  2445. else
  2446. {
  2447. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2448. ProcessDeferredParams(&expr);
  2449. ProcessPropertyGetAccessor(&expr, wnode);
  2450. // Add byte code for the expression
  2451. ConvertToVariable(&expr);
  2452. bc->AddCode(&expr.bc);
  2453. // Jump to next iteration if expression is true
  2454. bc->InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2455. bc->Instr(asBC_ClrHi);
  2456. bc->InstrDWORD(asBC_JNZ, beforeLabel);
  2457. ReleaseTemporaryVariable(expr.type, bc);
  2458. }
  2459. // Add label after the statement
  2460. bc->Label((short)afterLabel);
  2461. continueLabels.PopLast();
  2462. breakLabels.PopLast();
  2463. RemoveVariableScope();
  2464. }
  2465. void asCCompiler::CompileBreakStatement(asCScriptNode *node, asCByteCode *bc)
  2466. {
  2467. if( breakLabels.GetLength() == 0 )
  2468. {
  2469. Error(TXT_INVALID_BREAK, node);
  2470. return;
  2471. }
  2472. // Add destructor calls for all variables that will go out of scope
  2473. // Put this clean up in a block to allow exception handler to understand them
  2474. bc->Block(true);
  2475. asCVariableScope *vs = variables;
  2476. while( !vs->isBreakScope )
  2477. {
  2478. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2479. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2480. vs = vs->parent;
  2481. }
  2482. bc->Block(false);
  2483. bc->InstrINT(asBC_JMP, breakLabels[breakLabels.GetLength()-1]);
  2484. }
  2485. void asCCompiler::CompileContinueStatement(asCScriptNode *node, asCByteCode *bc)
  2486. {
  2487. if( continueLabels.GetLength() == 0 )
  2488. {
  2489. Error(TXT_INVALID_CONTINUE, node);
  2490. return;
  2491. }
  2492. // Add destructor calls for all variables that will go out of scope
  2493. // Put this clean up in a block to allow exception handler to understand them
  2494. bc->Block(true);
  2495. asCVariableScope *vs = variables;
  2496. while( !vs->isContinueScope )
  2497. {
  2498. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2499. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2500. vs = vs->parent;
  2501. }
  2502. bc->Block(false);
  2503. bc->InstrINT(asBC_JMP, continueLabels[continueLabels.GetLength()-1]);
  2504. }
  2505. void asCCompiler::CompileExpressionStatement(asCScriptNode *enode, asCByteCode *bc)
  2506. {
  2507. if( enode->firstChild )
  2508. {
  2509. // Compile the expression
  2510. asSExprContext expr(engine);
  2511. CompileAssignment(enode->firstChild, &expr);
  2512. // Pop the value from the stack
  2513. if( !expr.type.dataType.IsPrimitive() )
  2514. expr.bc.Pop(expr.type.dataType.GetSizeOnStackDWords());
  2515. // Release temporary variables used by expression
  2516. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2517. ProcessDeferredParams(&expr);
  2518. bc->AddCode(&expr.bc);
  2519. }
  2520. }
  2521. void asCCompiler::PrepareTemporaryObject(asCScriptNode *node, asSExprContext *ctx, bool forceOnHeap)
  2522. {
  2523. // If the object already is stored in temporary variable then nothing needs to be done
  2524. // Note, a type can be temporary without being a variable, in which case it is holding off
  2525. // on releasing a previously used object.
  2526. if( ctx->type.isTemporary && ctx->type.isVariable &&
  2527. !(forceOnHeap && !IsVariableOnHeap(ctx->type.stackOffset)) )
  2528. {
  2529. // If the temporary object is currently not a reference
  2530. // the expression needs to be reevaluated to a reference
  2531. if( !ctx->type.dataType.IsReference() )
  2532. {
  2533. ctx->bc.Pop(AS_PTR_SIZE);
  2534. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  2535. ctx->type.dataType.MakeReference(true);
  2536. }
  2537. return;
  2538. }
  2539. // Allocate temporary variable
  2540. asCDataType dt = ctx->type.dataType;
  2541. dt.MakeReference(false);
  2542. dt.MakeReadOnly(false);
  2543. int offset = AllocateVariable(dt, true, forceOnHeap);
  2544. // Objects stored on the stack are not considered references
  2545. dt.MakeReference(IsVariableOnHeap(offset));
  2546. asCTypeInfo lvalue;
  2547. lvalue.Set(dt);
  2548. lvalue.isTemporary = true;
  2549. lvalue.stackOffset = (short)offset;
  2550. lvalue.isVariable = true;
  2551. lvalue.isExplicitHandle = ctx->type.isExplicitHandle;
  2552. if( !dt.IsObjectHandle() &&
  2553. dt.GetObjectType() && (dt.GetBehaviour()->copyconstruct || dt.GetBehaviour()->copyfactory) )
  2554. {
  2555. PrepareForAssignment(&lvalue.dataType, ctx, node, true);
  2556. // Use the copy constructor/factory when available
  2557. CallCopyConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, ctx, node);
  2558. }
  2559. else
  2560. {
  2561. // Allocate and construct the temporary object
  2562. int r = CallDefaultConstructor(dt, offset, IsVariableOnHeap(offset), &ctx->bc, node);
  2563. if( r < 0 )
  2564. {
  2565. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  2566. }
  2567. else
  2568. {
  2569. // Assign the object to the temporary variable
  2570. PrepareForAssignment(&lvalue.dataType, ctx, node, true);
  2571. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2572. r = PerformAssignment(&lvalue, &ctx->type, &ctx->bc, node);
  2573. if( r < 0 )
  2574. {
  2575. Error(TXT_FAILED_TO_CREATE_TEMP_OBJ, node);
  2576. }
  2577. // Pop the original reference
  2578. ctx->bc.Pop(AS_PTR_SIZE);
  2579. }
  2580. }
  2581. // If the expression was holding off on releasing a
  2582. // previously used object, we need to release it now
  2583. if( ctx->type.isTemporary )
  2584. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  2585. // Push the reference to the temporary variable on the stack
  2586. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  2587. lvalue.dataType.MakeReference(IsVariableOnHeap(offset));
  2588. ctx->type = lvalue;
  2589. }
  2590. void asCCompiler::CompileReturnStatement(asCScriptNode *rnode, asCByteCode *bc)
  2591. {
  2592. // Get return type and location
  2593. sVariable *v = variables->GetVariable("return");
  2594. // Basic validations
  2595. if( v->type.GetSizeOnStackDWords() > 0 && !rnode->firstChild )
  2596. {
  2597. Error(TXT_MUST_RETURN_VALUE, rnode);
  2598. return;
  2599. }
  2600. else if( v->type.GetSizeOnStackDWords() == 0 && rnode->firstChild )
  2601. {
  2602. Error(TXT_CANT_RETURN_VALUE, rnode);
  2603. return;
  2604. }
  2605. // Compile the expression
  2606. if( rnode->firstChild )
  2607. {
  2608. // Compile the expression
  2609. asSExprContext expr(engine);
  2610. int r = CompileAssignment(rnode->firstChild, &expr);
  2611. if( r < 0 ) return;
  2612. if( v->type.IsReference() )
  2613. {
  2614. // The expression that gives the reference must not use any of the
  2615. // variables that must be destroyed upon exit, because then it means
  2616. // reference will stay alive while the clean-up is done, which could
  2617. // potentially mean that the reference is invalidated by the clean-up.
  2618. //
  2619. // When the function is returning a reference, the clean-up of the
  2620. // variables must be done before the evaluation of the expression.
  2621. //
  2622. // A reference to a global variable, or a class member for class methods
  2623. // should be allowed to be returned.
  2624. if( !(expr.type.dataType.IsReference() ||
  2625. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle())) )
  2626. {
  2627. // Clean up the potential deferred parameters
  2628. ProcessDeferredParams(&expr);
  2629. Error(TXT_NOT_VALID_REFERENCE, rnode);
  2630. return;
  2631. }
  2632. // No references to local variables, temporary variables, or parameters
  2633. // are allowed to be returned, since they go out of scope when the function
  2634. // returns. Even reference parameters are disallowed, since it is not possible
  2635. // to know the scope of them. The exception is the 'this' pointer, which
  2636. // is treated by the compiler as a local variable, but isn't really so.
  2637. if( (expr.type.isVariable && !(expr.type.stackOffset == 0 && outFunc->objectType)) || expr.type.isTemporary )
  2638. {
  2639. // Clean up the potential deferred parameters
  2640. ProcessDeferredParams(&expr);
  2641. Error(TXT_CANNOT_RETURN_REF_TO_LOCAL, rnode);
  2642. return;
  2643. }
  2644. // The type must match exactly as we cannot convert
  2645. // the reference without loosing the original value
  2646. if( !(v->type == expr.type.dataType ||
  2647. (expr.type.dataType.IsObject() && !expr.type.dataType.IsObjectHandle() && v->type.IsEqualExceptRef(expr.type.dataType))) )
  2648. {
  2649. // Clean up the potential deferred parameters
  2650. ProcessDeferredParams(&expr);
  2651. asCString str;
  2652. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2653. Error(str.AddressOf(), rnode);
  2654. return;
  2655. }
  2656. // The expression must not have any deferred expressions, because the evaluation
  2657. // of these cannot be done without keeping the reference which is not safe
  2658. if( expr.deferredParams.GetLength() )
  2659. {
  2660. // Clean up the potential deferred parameters
  2661. ProcessDeferredParams(&expr);
  2662. Error(TXT_REF_CANT_BE_RETURNED_DEFERRED_PARAM, rnode);
  2663. return;
  2664. }
  2665. // Make sure the expression isn't using any local variables that
  2666. // will need to be cleaned up before the function completes
  2667. asCArray<int> usedVars;
  2668. expr.bc.GetVarsUsed(usedVars);
  2669. for( asUINT n = 0; n < usedVars.GetLength(); n++ )
  2670. {
  2671. int var = GetVariableSlot(usedVars[n]);
  2672. if( var != -1 )
  2673. {
  2674. asCDataType dt = variableAllocations[var];
  2675. if( dt.IsObject() )
  2676. {
  2677. ProcessDeferredParams(&expr);
  2678. Error(TXT_REF_CANT_BE_RETURNED_LOCAL_VARS, rnode);
  2679. return;
  2680. }
  2681. }
  2682. }
  2683. // All objects in the function must be cleaned up before the expression
  2684. // is evaluated, otherwise there is a possibility that the cleanup will
  2685. // invalidate the reference.
  2686. // Destroy the local variables before loading
  2687. // the reference into the register. This will
  2688. // be done before the expression is evaluated.
  2689. DestroyVariables(bc);
  2690. // For primitives the reference is already in the register,
  2691. // but for non-primitives the reference is on the stack so we
  2692. // need to load it into the register
  2693. if( !expr.type.dataType.IsPrimitive() )
  2694. {
  2695. if( !expr.type.dataType.IsObjectHandle() &&
  2696. expr.type.dataType.IsReference() )
  2697. expr.bc.Instr(asBC_RDSPtr);
  2698. expr.bc.Instr(asBC_PopRPtr);
  2699. }
  2700. // There are no temporaries to release so we're done
  2701. }
  2702. else // if( !v->type.IsReference() )
  2703. {
  2704. ProcessPropertyGetAccessor(&expr, rnode);
  2705. // Prepare the value for assignment
  2706. IsVariableInitialized(&expr.type, rnode->firstChild);
  2707. if( v->type.IsPrimitive() )
  2708. {
  2709. if( expr.type.dataType.IsReference() ) ConvertToVariable(&expr);
  2710. // Implicitly convert the value to the return type
  2711. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  2712. // Verify that the conversion was successful
  2713. if( expr.type.dataType != v->type )
  2714. {
  2715. asCString str;
  2716. str.Format(TXT_NO_CONVERSION_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2717. Error(str.AddressOf(), rnode);
  2718. return;
  2719. }
  2720. else
  2721. {
  2722. ConvertToVariable(&expr);
  2723. // Clean up the local variables and process deferred parameters
  2724. DestroyVariables(&expr.bc);
  2725. ProcessDeferredParams(&expr);
  2726. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2727. // Load the variable in the register
  2728. if( v->type.GetSizeOnStackDWords() == 1 )
  2729. expr.bc.InstrSHORT(asBC_CpyVtoR4, expr.type.stackOffset);
  2730. else
  2731. expr.bc.InstrSHORT(asBC_CpyVtoR8, expr.type.stackOffset);
  2732. }
  2733. }
  2734. else if( v->type.IsObject() )
  2735. {
  2736. // Value types are returned on the stack, in a location
  2737. // that has been reserved by the calling function.
  2738. if( outFunc->DoesReturnOnStack() )
  2739. {
  2740. // TODO: optimize: If the return type has a constructor that takes the type of the expression,
  2741. // it should be called directly instead of first converting the expression and
  2742. // then copy the value.
  2743. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  2744. {
  2745. ImplicitConversion(&expr, v->type, rnode->firstChild, asIC_IMPLICIT_CONV);
  2746. if( !v->type.IsEqualExceptRefAndConst(expr.type.dataType) )
  2747. {
  2748. asCString str;
  2749. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, expr.type.dataType.Format().AddressOf(), v->type.Format().AddressOf());
  2750. Error(str.AddressOf(), rnode->firstChild);
  2751. return;
  2752. }
  2753. }
  2754. int offset = outFunc->objectType ? -AS_PTR_SIZE : 0;
  2755. if( v->type.GetObjectType()->beh.copyconstruct )
  2756. {
  2757. PrepareForAssignment(&v->type, &expr, rnode->firstChild, false);
  2758. CallCopyConstructor(v->type, offset, false, &expr.bc, &expr, rnode->firstChild, false, true);
  2759. }
  2760. else
  2761. {
  2762. // If the copy constructor doesn't exist, then a manual assignment needs to be done instead.
  2763. CallDefaultConstructor(v->type, offset, false, &expr.bc, rnode->firstChild, false, true);
  2764. PrepareForAssignment(&v->type, &expr, rnode->firstChild, false);
  2765. expr.bc.InstrSHORT(asBC_PSF, (short)offset);
  2766. expr.bc.Instr(asBC_RDSPtr);
  2767. asSExprContext lexpr(engine);
  2768. lexpr.type.Set(v->type);
  2769. lexpr.type.isLValue = true;
  2770. PerformAssignment(&lexpr.type, &expr.type, &expr.bc, rnode->firstChild);
  2771. expr.bc.Pop(AS_PTR_SIZE);
  2772. // Release any temporary variable
  2773. ReleaseTemporaryVariable(expr.type, &expr.bc);
  2774. }
  2775. // Clean up the local variables and process deferred parameters
  2776. DestroyVariables(&expr.bc);
  2777. ProcessDeferredParams(&expr);
  2778. }
  2779. else
  2780. {
  2781. asASSERT( v->type.GetObjectType()->flags & asOBJ_REF );
  2782. // Prepare the expression to be loaded into the object
  2783. // register. This will place the reference in local variable
  2784. PrepareArgument(&v->type, &expr, rnode->firstChild, false, 0);
  2785. // Pop the reference to the temporary variable
  2786. expr.bc.Pop(AS_PTR_SIZE);
  2787. // Clean up the local variables and process deferred parameters
  2788. DestroyVariables(&expr.bc);
  2789. ProcessDeferredParams(&expr);
  2790. // Load the object pointer into the object register
  2791. // LOADOBJ also clears the address in the variable
  2792. expr.bc.InstrSHORT(asBC_LOADOBJ, expr.type.stackOffset);
  2793. // LOADOBJ cleared the address in the variable so the object will not be freed
  2794. // here, but the temporary variable must still be freed so the slot can be reused
  2795. // By releasing without the bytecode we do just that.
  2796. ReleaseTemporaryVariable(expr.type, 0);
  2797. }
  2798. }
  2799. }
  2800. bc->AddCode(&expr.bc);
  2801. }
  2802. else
  2803. {
  2804. // For functions that don't return anything
  2805. // we just detroy the local variables
  2806. DestroyVariables(bc);
  2807. }
  2808. // Jump to the end of the function
  2809. bc->InstrINT(asBC_JMP, 0);
  2810. }
  2811. void asCCompiler::DestroyVariables(asCByteCode *bc)
  2812. {
  2813. // Call destructor on all variables except for the function parameters
  2814. // Put the clean-up in a block to allow exception handler to understand this
  2815. bc->Block(true);
  2816. asCVariableScope *vs = variables;
  2817. while( vs )
  2818. {
  2819. for( int n = (int)vs->variables.GetLength() - 1; n >= 0; n-- )
  2820. if( vs->variables[n]->stackOffset > 0 )
  2821. CallDestructor(vs->variables[n]->type, vs->variables[n]->stackOffset, vs->variables[n]->onHeap, bc);
  2822. vs = vs->parent;
  2823. }
  2824. bc->Block(false);
  2825. }
  2826. void asCCompiler::AddVariableScope(bool isBreakScope, bool isContinueScope)
  2827. {
  2828. variables = asNEW(asCVariableScope)(variables);
  2829. variables->isBreakScope = isBreakScope;
  2830. variables->isContinueScope = isContinueScope;
  2831. }
  2832. void asCCompiler::RemoveVariableScope()
  2833. {
  2834. if( variables )
  2835. {
  2836. asCVariableScope *var = variables;
  2837. variables = variables->parent;
  2838. asDELETE(var,asCVariableScope);
  2839. }
  2840. }
  2841. void asCCompiler::Error(const char *msg, asCScriptNode *node)
  2842. {
  2843. asCString str;
  2844. int r = 0, c = 0;
  2845. asASSERT( node );
  2846. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2847. builder->WriteError(script->name.AddressOf(), msg, r, c);
  2848. hasCompileErrors = true;
  2849. }
  2850. void asCCompiler::Warning(const char *msg, asCScriptNode *node)
  2851. {
  2852. asCString str;
  2853. int r = 0, c = 0;
  2854. asASSERT( node );
  2855. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2856. builder->WriteWarning(script->name.AddressOf(), msg, r, c);
  2857. }
  2858. void asCCompiler::Information(const char *msg, asCScriptNode *node)
  2859. {
  2860. asCString str;
  2861. int r = 0, c = 0;
  2862. asASSERT( node );
  2863. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2864. builder->WriteInfo(script->name.AddressOf(), msg, r, c, false);
  2865. }
  2866. void asCCompiler::PrintMatchingFuncs(asCArray<int> &funcs, asCScriptNode *node)
  2867. {
  2868. int r = 0, c = 0;
  2869. asASSERT( node );
  2870. if( node ) script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  2871. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  2872. {
  2873. asIScriptFunction *func = builder->GetFunctionDescription(funcs[n]);
  2874. builder->WriteInfo(script->name.AddressOf(), func->GetDeclaration(true), r, c, false);
  2875. }
  2876. }
  2877. int asCCompiler::AllocateVariableNotIn(const asCDataType &type, bool isTemporary, bool forceOnHeap, asSExprContext *ctx)
  2878. {
  2879. int l = int(reservedVariables.GetLength());
  2880. ctx->bc.GetVarsUsed(reservedVariables);
  2881. int var = AllocateVariable(type, isTemporary, forceOnHeap);
  2882. reservedVariables.SetLength(l);
  2883. return var;
  2884. }
  2885. int asCCompiler::AllocateVariable(const asCDataType &type, bool isTemporary, bool forceOnHeap)
  2886. {
  2887. asCDataType t(type);
  2888. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 1 )
  2889. t.SetTokenType(ttInt);
  2890. if( t.IsPrimitive() && t.GetSizeOnStackDWords() == 2 )
  2891. t.SetTokenType(ttDouble);
  2892. // Only null handles have the token type unrecognized token
  2893. asASSERT( t.IsObjectHandle() || t.GetTokenType() != ttUnrecognizedToken );
  2894. bool isOnHeap = true;
  2895. if( t.IsPrimitive() ||
  2896. (t.GetObjectType() && (t.GetObjectType()->GetFlags() & asOBJ_VALUE) && !forceOnHeap) )
  2897. {
  2898. // Primitives and value types (unless overridden) are allocated on the stack
  2899. isOnHeap = false;
  2900. }
  2901. // Find a free location with the same type
  2902. for( asUINT n = 0; n < freeVariables.GetLength(); n++ )
  2903. {
  2904. int slot = freeVariables[n];
  2905. if( variableAllocations[slot].IsEqualExceptConst(t) &&
  2906. variableIsTemporary[slot] == isTemporary &&
  2907. variableIsOnHeap[slot] == isOnHeap )
  2908. {
  2909. // We can't return by slot, must count variable sizes
  2910. int offset = GetVariableOffset(slot);
  2911. // Verify that it is not in the list of reserved variables
  2912. bool isUsed = false;
  2913. if( reservedVariables.GetLength() )
  2914. isUsed = reservedVariables.Exists(offset);
  2915. if( !isUsed )
  2916. {
  2917. if( n != freeVariables.GetLength() - 1 )
  2918. freeVariables[n] = freeVariables.PopLast();
  2919. else
  2920. freeVariables.PopLast();
  2921. if( isTemporary )
  2922. tempVariables.PushLast(offset);
  2923. return offset;
  2924. }
  2925. }
  2926. }
  2927. variableAllocations.PushLast(t);
  2928. variableIsTemporary.PushLast(isTemporary);
  2929. variableIsOnHeap.PushLast(isOnHeap);
  2930. int offset = GetVariableOffset((int)variableAllocations.GetLength()-1);
  2931. if( isTemporary )
  2932. tempVariables.PushLast(offset);
  2933. return offset;
  2934. }
  2935. int asCCompiler::GetVariableOffset(int varIndex)
  2936. {
  2937. // Return offset to the last dword on the stack
  2938. int varOffset = 1;
  2939. for( int n = 0; n < varIndex; n++ )
  2940. {
  2941. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  2942. varOffset += variableAllocations[n].GetSizeInMemoryDWords();
  2943. else
  2944. varOffset += variableAllocations[n].GetSizeOnStackDWords();
  2945. }
  2946. if( varIndex < (int)variableAllocations.GetLength() )
  2947. {
  2948. int size;
  2949. if( !variableIsOnHeap[varIndex] && variableAllocations[varIndex].IsObject() )
  2950. size = variableAllocations[varIndex].GetSizeInMemoryDWords();
  2951. else
  2952. size = variableAllocations[varIndex].GetSizeOnStackDWords();
  2953. if( size > 1 )
  2954. varOffset += size-1;
  2955. }
  2956. return varOffset;
  2957. }
  2958. int asCCompiler::GetVariableSlot(int offset)
  2959. {
  2960. int varOffset = 1;
  2961. for( asUINT n = 0; n < variableAllocations.GetLength(); n++ )
  2962. {
  2963. if( !variableIsOnHeap[n] && variableAllocations[n].IsObject() )
  2964. varOffset += -1 + variableAllocations[n].GetSizeInMemoryDWords();
  2965. else
  2966. varOffset += -1 + variableAllocations[n].GetSizeOnStackDWords();
  2967. if( varOffset == offset )
  2968. return n;
  2969. varOffset++;
  2970. }
  2971. return -1;
  2972. }
  2973. bool asCCompiler::IsVariableOnHeap(int offset)
  2974. {
  2975. int varSlot = GetVariableSlot(offset);
  2976. if( varSlot < 0 )
  2977. {
  2978. // This happens for function arguments that are considered as on the heap
  2979. return true;
  2980. }
  2981. return variableIsOnHeap[varSlot];
  2982. }
  2983. void asCCompiler::DeallocateVariable(int offset)
  2984. {
  2985. // Remove temporary variable
  2986. int n;
  2987. for( n = 0; n < (int)tempVariables.GetLength(); n++ )
  2988. {
  2989. if( offset == tempVariables[n] )
  2990. {
  2991. if( n == (int)tempVariables.GetLength()-1 )
  2992. tempVariables.PopLast();
  2993. else
  2994. tempVariables[n] = tempVariables.PopLast();
  2995. break;
  2996. }
  2997. }
  2998. n = GetVariableSlot(offset);
  2999. if( n != -1 )
  3000. {
  3001. freeVariables.PushLast(n);
  3002. return;
  3003. }
  3004. // We might get here if the variable was implicitly declared
  3005. // because it was use before a formal declaration, in this case
  3006. // the offset is 0x7FFF
  3007. asASSERT(offset == 0x7FFF);
  3008. }
  3009. void asCCompiler::ReleaseTemporaryVariable(asCTypeInfo &t, asCByteCode *bc)
  3010. {
  3011. if( t.isTemporary )
  3012. {
  3013. ReleaseTemporaryVariable(t.stackOffset, bc);
  3014. t.isTemporary = false;
  3015. }
  3016. }
  3017. void asCCompiler::ReleaseTemporaryVariable(int offset, asCByteCode *bc)
  3018. {
  3019. if( bc )
  3020. {
  3021. // We need to call the destructor on the true variable type
  3022. int n = GetVariableSlot(offset);
  3023. asASSERT( n >= 0 );
  3024. if( n >= 0 )
  3025. {
  3026. asCDataType dt = variableAllocations[n];
  3027. bool isOnHeap = variableIsOnHeap[n];
  3028. // Call destructor
  3029. CallDestructor(dt, offset, isOnHeap, bc);
  3030. }
  3031. }
  3032. DeallocateVariable(offset);
  3033. }
  3034. void asCCompiler::Dereference(asSExprContext *ctx, bool generateCode)
  3035. {
  3036. if( ctx->type.dataType.IsReference() )
  3037. {
  3038. if( ctx->type.dataType.IsObject() )
  3039. {
  3040. ctx->type.dataType.MakeReference(false);
  3041. if( generateCode )
  3042. {
  3043. ctx->bc.Instr(asBC_CHKREF);
  3044. ctx->bc.Instr(asBC_RDSPtr);
  3045. }
  3046. }
  3047. else
  3048. {
  3049. // This should never happen as primitives are treated differently
  3050. asASSERT(false);
  3051. }
  3052. }
  3053. }
  3054. bool asCCompiler::IsVariableInitialized(asCTypeInfo *type, asCScriptNode *node)
  3055. {
  3056. // Temporary variables are assumed to be initialized
  3057. if( type->isTemporary ) return true;
  3058. // Verify that it is a variable
  3059. if( !type->isVariable ) return true;
  3060. // Find the variable
  3061. sVariable *v = variables->GetVariableByOffset(type->stackOffset);
  3062. // The variable isn't found if it is a constant, in which case it is guaranteed to be initialized
  3063. if( v == 0 ) return true;
  3064. if( v->isInitialized ) return true;
  3065. // Complex types don't need this test
  3066. if( v->type.IsObject() ) return true;
  3067. // Mark as initialized so that the user will not be bothered again
  3068. v->isInitialized = true;
  3069. // Write warning
  3070. asCString str;
  3071. str.Format(TXT_s_NOT_INITIALIZED, (const char *)v->name.AddressOf());
  3072. Warning(str.AddressOf(), node);
  3073. return false;
  3074. }
  3075. void asCCompiler::PrepareOperand(asSExprContext *ctx, asCScriptNode *node)
  3076. {
  3077. // Check if the variable is initialized (if it indeed is a variable)
  3078. IsVariableInitialized(&ctx->type, node);
  3079. asCDataType to = ctx->type.dataType;
  3080. to.MakeReference(false);
  3081. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  3082. ProcessDeferredParams(ctx);
  3083. }
  3084. void asCCompiler::PrepareForAssignment(asCDataType *lvalue, asSExprContext *rctx, asCScriptNode *node, bool toTemporary, asSExprContext *lvalueExpr)
  3085. {
  3086. ProcessPropertyGetAccessor(rctx, node);
  3087. // Make sure the rvalue is initialized if it is a variable
  3088. IsVariableInitialized(&rctx->type, node);
  3089. if( lvalue->IsPrimitive() )
  3090. {
  3091. if( rctx->type.dataType.IsPrimitive() )
  3092. {
  3093. if( rctx->type.dataType.IsReference() )
  3094. {
  3095. // Cannot do implicit conversion of references so we first convert the reference to a variable
  3096. ConvertToVariableNotIn(rctx, lvalueExpr);
  3097. }
  3098. }
  3099. // Implicitly convert the value to the right type
  3100. int l = int(reservedVariables.GetLength());
  3101. if( lvalueExpr ) lvalueExpr->bc.GetVarsUsed(reservedVariables);
  3102. ImplicitConversion(rctx, *lvalue, node, asIC_IMPLICIT_CONV);
  3103. reservedVariables.SetLength(l);
  3104. // Check data type
  3105. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  3106. {
  3107. asCString str;
  3108. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  3109. Error(str.AddressOf(), node);
  3110. rctx->type.SetDummy();
  3111. }
  3112. // Make sure the rvalue is a variable
  3113. if( !rctx->type.isVariable )
  3114. ConvertToVariableNotIn(rctx, lvalueExpr);
  3115. }
  3116. else
  3117. {
  3118. asCDataType to = *lvalue;
  3119. to.MakeReference(false);
  3120. // TODO: ImplicitConversion should know to do this by itself
  3121. // First convert to a handle which will do a reference cast
  3122. if( !lvalue->IsObjectHandle() &&
  3123. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  3124. to.MakeHandle(true);
  3125. // Don't allow the implicit conversion to create an object
  3126. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, !toTemporary);
  3127. if( !lvalue->IsObjectHandle() &&
  3128. (lvalue->GetObjectType()->flags & asOBJ_SCRIPT_OBJECT) )
  3129. {
  3130. // Then convert to a reference, which will validate the handle
  3131. to.MakeHandle(false);
  3132. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true, !toTemporary);
  3133. }
  3134. // Check data type
  3135. if( !lvalue->IsEqualExceptRefAndConst(rctx->type.dataType) )
  3136. {
  3137. asCString str;
  3138. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lvalue->Format().AddressOf());
  3139. Error(str.AddressOf(), node);
  3140. }
  3141. else
  3142. {
  3143. // If the assignment will be made with the copy behaviour then the rvalue must not be a reference
  3144. if( lvalue->IsObject() )
  3145. asASSERT(!rctx->type.dataType.IsReference());
  3146. }
  3147. }
  3148. }
  3149. bool asCCompiler::IsLValue(asCTypeInfo &type)
  3150. {
  3151. if( !type.isLValue ) return false;
  3152. if( type.dataType.IsReadOnly() ) return false;
  3153. if( !type.dataType.IsObject() && !type.isVariable && !type.dataType.IsReference() ) return false;
  3154. return true;
  3155. }
  3156. int asCCompiler::PerformAssignment(asCTypeInfo *lvalue, asCTypeInfo *rvalue, asCByteCode *bc, asCScriptNode *node)
  3157. {
  3158. if( lvalue->dataType.IsReadOnly() )
  3159. {
  3160. Error(TXT_REF_IS_READ_ONLY, node);
  3161. return -1;
  3162. }
  3163. if( lvalue->dataType.IsPrimitive() )
  3164. {
  3165. if( lvalue->isVariable )
  3166. {
  3167. // Copy the value between the variables directly
  3168. if( lvalue->dataType.GetSizeInMemoryDWords() == 1 )
  3169. bc->InstrW_W(asBC_CpyVtoV4, lvalue->stackOffset, rvalue->stackOffset);
  3170. else
  3171. bc->InstrW_W(asBC_CpyVtoV8, lvalue->stackOffset, rvalue->stackOffset);
  3172. // Mark variable as initialized
  3173. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3174. if( v ) v->isInitialized = true;
  3175. }
  3176. else if( lvalue->dataType.IsReference() )
  3177. {
  3178. // Copy the value of the variable to the reference in the register
  3179. int s = lvalue->dataType.GetSizeInMemoryBytes();
  3180. if( s == 1 )
  3181. bc->InstrSHORT(asBC_WRTV1, rvalue->stackOffset);
  3182. else if( s == 2 )
  3183. bc->InstrSHORT(asBC_WRTV2, rvalue->stackOffset);
  3184. else if( s == 4 )
  3185. bc->InstrSHORT(asBC_WRTV4, rvalue->stackOffset);
  3186. else if( s == 8 )
  3187. bc->InstrSHORT(asBC_WRTV8, rvalue->stackOffset);
  3188. }
  3189. else
  3190. {
  3191. Error(TXT_NOT_VALID_LVALUE, node);
  3192. return -1;
  3193. }
  3194. }
  3195. else if( !lvalue->isExplicitHandle )
  3196. {
  3197. asSExprContext ctx(engine);
  3198. ctx.type = *lvalue;
  3199. Dereference(&ctx, true);
  3200. *lvalue = ctx.type;
  3201. bc->AddCode(&ctx.bc);
  3202. // TODO: Should find the opAssign method that implements the default copy behaviour.
  3203. // The beh->copy member will be removed.
  3204. asSTypeBehaviour *beh = lvalue->dataType.GetBehaviour();
  3205. if( beh->copy )
  3206. {
  3207. // Call the copy operator
  3208. bc->Call(asBC_CALLSYS, (asDWORD)beh->copy, 2*AS_PTR_SIZE);
  3209. bc->Instr(asBC_PshRPtr);
  3210. }
  3211. else
  3212. {
  3213. // Default copy operator
  3214. if( lvalue->dataType.GetSizeInMemoryDWords() == 0 ||
  3215. !(lvalue->dataType.GetObjectType()->flags & asOBJ_POD) )
  3216. {
  3217. asCString msg;
  3218. msg.Format(TXT_NO_DEFAULT_COPY_OP_FOR_s, lvalue->dataType.GetObjectType()->name.AddressOf());
  3219. Error(msg.AddressOf(), node);
  3220. return -1;
  3221. }
  3222. // Copy larger data types from a reference
  3223. bc->InstrSHORT_DW(asBC_COPY, (short)lvalue->dataType.GetSizeInMemoryDWords(), engine->GetTypeIdFromDataType(lvalue->dataType));
  3224. }
  3225. }
  3226. else
  3227. {
  3228. // TODO: The object handle can be stored in a variable as well
  3229. if( !lvalue->dataType.IsReference() )
  3230. {
  3231. Error(TXT_NOT_VALID_REFERENCE, node);
  3232. return -1;
  3233. }
  3234. // TODO: optimize: Convert to register based
  3235. bc->InstrPTR(asBC_REFCPY, lvalue->dataType.GetObjectType());
  3236. // Mark variable as initialized
  3237. if( variables )
  3238. {
  3239. sVariable *v = variables->GetVariableByOffset(lvalue->stackOffset);
  3240. if( v ) v->isInitialized = true;
  3241. }
  3242. }
  3243. return 0;
  3244. }
  3245. bool asCCompiler::CompileRefCast(asSExprContext *ctx, const asCDataType &to, bool isExplicit, asCScriptNode *node, bool generateCode)
  3246. {
  3247. bool conversionDone = false;
  3248. asCArray<int> ops;
  3249. asUINT n;
  3250. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT )
  3251. {
  3252. // We need it to be a reference
  3253. if( !ctx->type.dataType.IsReference() )
  3254. {
  3255. asCDataType to = ctx->type.dataType;
  3256. to.MakeReference(true);
  3257. ImplicitConversion(ctx, to, 0, isExplicit ? asIC_EXPLICIT_REF_CAST : asIC_IMPLICIT_CONV, generateCode);
  3258. }
  3259. if( isExplicit )
  3260. {
  3261. // Allow dynamic cast between object handles (only for script objects).
  3262. // At run time this may result in a null handle,
  3263. // which when used will throw an exception
  3264. conversionDone = true;
  3265. if( generateCode )
  3266. {
  3267. ctx->bc.InstrDWORD(asBC_Cast, engine->GetTypeIdFromDataType(to));
  3268. // Allocate a temporary variable for the returned object
  3269. int returnOffset = AllocateVariable(to, true);
  3270. // Move the pointer from the object register to the temporary variable
  3271. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  3272. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  3273. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3274. ctx->type.SetVariable(to, returnOffset, true);
  3275. ctx->type.dataType.MakeReference(true);
  3276. }
  3277. else
  3278. {
  3279. ctx->type.dataType = to;
  3280. ctx->type.dataType.MakeReference(true);
  3281. }
  3282. }
  3283. else
  3284. {
  3285. if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3286. {
  3287. conversionDone = true;
  3288. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3289. }
  3290. }
  3291. }
  3292. else
  3293. {
  3294. // Find a suitable registered behaviour
  3295. asSTypeBehaviour *beh = &ctx->type.dataType.GetObjectType()->beh;
  3296. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3297. {
  3298. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3299. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3300. {
  3301. int funcId = beh->operators[n+1];
  3302. // Is the operator for the output type?
  3303. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3304. if( func->returnType.GetObjectType() != to.GetObjectType() )
  3305. continue;
  3306. ops.PushLast(funcId);
  3307. }
  3308. }
  3309. // It shouldn't be possible to have more than one
  3310. asASSERT( ops.GetLength() <= 1 );
  3311. // Should only have one behaviour for each output type
  3312. if( ops.GetLength() == 1 )
  3313. {
  3314. if( generateCode )
  3315. {
  3316. // TODO: optimize: Instead of producing bytecode for checking if the handle is
  3317. // null, we can create a special CALLSYS instruction that checks
  3318. // if the object pointer is null and if so sets the object register
  3319. // to null directly without executing the function.
  3320. //
  3321. // Alternatively I could force the ref cast behaviours be global
  3322. // functions with 1 parameter, even though they should still be
  3323. // registered with RegisterObjectBehaviour()
  3324. // Add code to avoid calling the cast behaviour if the handle is already null,
  3325. // because that will raise a null pointer exception due to the cast behaviour
  3326. // being a class method, and the this pointer cannot be null.
  3327. if( ctx->type.isVariable )
  3328. ctx->bc.Pop(AS_PTR_SIZE);
  3329. else
  3330. {
  3331. Dereference(ctx, true);
  3332. ConvertToVariable(ctx);
  3333. }
  3334. // TODO: optimize: should have immediate comparison for null pointer
  3335. int offset = AllocateVariable(asCDataType::CreateNullHandle(), true);
  3336. // TODO: optimize: ClrVPtr is not necessary, because the VM will initialize the variable to null anyway
  3337. ctx->bc.InstrSHORT(asBC_ClrVPtr, (asWORD)offset);
  3338. ctx->bc.InstrW_W(asBC_CmpPtr, ctx->type.stackOffset, offset);
  3339. DeallocateVariable(offset);
  3340. int afterLabel = nextLabel++;
  3341. ctx->bc.InstrDWORD(asBC_JZ, afterLabel);
  3342. // Call the cast operator
  3343. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3344. ctx->bc.Instr(asBC_RDSPtr);
  3345. ctx->type.dataType.MakeReference(false);
  3346. asCTypeInfo objType = ctx->type;
  3347. asCArray<asSExprContext *> args;
  3348. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  3349. ctx->bc.Pop(AS_PTR_SIZE);
  3350. int endLabel = nextLabel++;
  3351. ctx->bc.InstrINT(asBC_JMP, endLabel);
  3352. ctx->bc.Label((short)afterLabel);
  3353. // Make a NULL pointer
  3354. ctx->bc.InstrSHORT(asBC_ClrVPtr, ctx->type.stackOffset);
  3355. ctx->bc.Label((short)endLabel);
  3356. // Since we're receiving a handle, we can release the original variable
  3357. ReleaseTemporaryVariable(objType, &ctx->bc);
  3358. // Push the reference to the handle on the stack
  3359. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  3360. }
  3361. else
  3362. {
  3363. asCScriptFunction *func = engine->scriptFunctions[ops[0]];
  3364. ctx->type.Set(func->returnType);
  3365. }
  3366. }
  3367. else if( ops.GetLength() == 0 )
  3368. {
  3369. // Check for the generic ref cast behaviour
  3370. for( n = 0; n < beh->operators.GetLength(); n+= 2 )
  3371. {
  3372. if( (isExplicit && asBEHAVE_REF_CAST == beh->operators[n]) ||
  3373. asBEHAVE_IMPLICIT_REF_CAST == beh->operators[n] )
  3374. {
  3375. int funcId = beh->operators[n+1];
  3376. // Does the operator take the ?&out parameter?
  3377. asCScriptFunction *func = engine->scriptFunctions[funcId];
  3378. if( func->parameterTypes.GetLength() != 1 ||
  3379. func->parameterTypes[0].GetTokenType() != ttQuestion ||
  3380. func->inOutFlags[0] != asTM_OUTREF )
  3381. continue;
  3382. ops.PushLast(funcId);
  3383. }
  3384. }
  3385. // It shouldn't be possible to have more than one
  3386. asASSERT( ops.GetLength() <= 1 );
  3387. if( ops.GetLength() == 1 )
  3388. {
  3389. if( generateCode )
  3390. {
  3391. asASSERT(to.IsObjectHandle());
  3392. // Allocate a temporary variable of the requested handle type
  3393. int stackOffset = AllocateVariableNotIn(to, true, false, ctx);
  3394. // Pass the reference of that variable to the function as output parameter
  3395. asCDataType toRef(to);
  3396. toRef.MakeReference(true);
  3397. asCArray<asSExprContext *> args;
  3398. asSExprContext arg(engine);
  3399. arg.bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3400. // Don't mark the variable as temporary, so it won't be freed too early
  3401. arg.type.SetVariable(toRef, stackOffset, false);
  3402. arg.type.isLValue = true;
  3403. arg.type.isExplicitHandle = true;
  3404. args.PushLast(&arg);
  3405. // Call the behaviour method
  3406. MakeFunctionCall(ctx, ops[0], ctx->type.dataType.GetObjectType(), args, node);
  3407. // Use the reference to the variable as the result of the expression
  3408. // Now we can mark the variable as temporary
  3409. ctx->type.SetVariable(toRef, stackOffset, true);
  3410. ctx->bc.InstrSHORT(asBC_PSF, (short)stackOffset);
  3411. }
  3412. else
  3413. {
  3414. // All casts are legal
  3415. ctx->type.Set(to);
  3416. }
  3417. }
  3418. }
  3419. }
  3420. return conversionDone;
  3421. }
  3422. asUINT asCCompiler::ImplicitConvPrimitiveToPrimitive(asSExprContext *ctx, const asCDataType &toOrig, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  3423. {
  3424. asCDataType to = toOrig;
  3425. to.MakeReference(false);
  3426. asASSERT( !ctx->type.dataType.IsReference() );
  3427. // Maybe no conversion is needed
  3428. if( to.IsEqualExceptConst(ctx->type.dataType) )
  3429. {
  3430. // A primitive is const or not
  3431. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3432. return asCC_NO_CONV;
  3433. }
  3434. // Determine the cost of this conversion
  3435. asUINT cost = asCC_NO_CONV;
  3436. if( (to.IsIntegerType() || to.IsUnsignedType()) && (ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType()) )
  3437. cost = asCC_INT_FLOAT_CONV;
  3438. else if( (to.IsFloatType() || to.IsDoubleType()) && (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() || ctx->type.dataType.IsEnumType()) )
  3439. cost = asCC_INT_FLOAT_CONV;
  3440. else if( to.IsUnsignedType() && ctx->type.dataType.IsIntegerType() )
  3441. cost = asCC_SIGNED_CONV;
  3442. else if( to.IsIntegerType() && (ctx->type.dataType.IsUnsignedType() || ctx->type.dataType.IsEnumType()) )
  3443. cost = asCC_SIGNED_CONV;
  3444. else if( to.GetSizeInMemoryBytes() || ctx->type.dataType.GetSizeInMemoryBytes() )
  3445. cost = asCC_PRIMITIVE_SIZE_CONV;
  3446. // Start by implicitly converting constant values
  3447. if( ctx->type.isConstant )
  3448. {
  3449. ImplicitConversionConstant(ctx, to, node, convType);
  3450. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3451. return cost;
  3452. }
  3453. // Allow implicit conversion between numbers
  3454. if( generateCode )
  3455. {
  3456. // When generating the code the decision has already been made, so we don't bother determining the cost
  3457. // Convert smaller types to 32bit first
  3458. int s = ctx->type.dataType.GetSizeInMemoryBytes();
  3459. if( s < 4 )
  3460. {
  3461. ConvertToTempVariable(ctx);
  3462. if( ctx->type.dataType.IsIntegerType() )
  3463. {
  3464. if( s == 1 )
  3465. ctx->bc.InstrSHORT(asBC_sbTOi, ctx->type.stackOffset);
  3466. else if( s == 2 )
  3467. ctx->bc.InstrSHORT(asBC_swTOi, ctx->type.stackOffset);
  3468. ctx->type.dataType.SetTokenType(ttInt);
  3469. }
  3470. else if( ctx->type.dataType.IsUnsignedType() )
  3471. {
  3472. if( s == 1 )
  3473. ctx->bc.InstrSHORT(asBC_ubTOi, ctx->type.stackOffset);
  3474. else if( s == 2 )
  3475. ctx->bc.InstrSHORT(asBC_uwTOi, ctx->type.stackOffset);
  3476. ctx->type.dataType.SetTokenType(ttUInt);
  3477. }
  3478. }
  3479. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1) ||
  3480. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  3481. {
  3482. if( ctx->type.dataType.IsIntegerType() ||
  3483. ctx->type.dataType.IsUnsignedType() ||
  3484. ctx->type.dataType.IsEnumType() )
  3485. {
  3486. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3487. {
  3488. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3489. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3490. }
  3491. else
  3492. {
  3493. ConvertToTempVariable(ctx);
  3494. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3495. int offset = AllocateVariable(to, true);
  3496. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3497. ctx->type.SetVariable(to, offset, true);
  3498. }
  3499. }
  3500. else if( ctx->type.dataType.IsFloatType() )
  3501. {
  3502. ConvertToTempVariable(ctx);
  3503. ctx->bc.InstrSHORT(asBC_fTOi, ctx->type.stackOffset);
  3504. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3505. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3506. }
  3507. else if( ctx->type.dataType.IsDoubleType() )
  3508. {
  3509. ConvertToTempVariable(ctx);
  3510. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3511. int offset = AllocateVariable(to, true);
  3512. ctx->bc.InstrW_W(asBC_dTOi, offset, ctx->type.stackOffset);
  3513. ctx->type.SetVariable(to, offset, true);
  3514. }
  3515. // Convert to smaller integer if necessary
  3516. int s = to.GetSizeInMemoryBytes();
  3517. if( s < 4 )
  3518. {
  3519. ConvertToTempVariable(ctx);
  3520. if( s == 1 )
  3521. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3522. else if( s == 2 )
  3523. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3524. }
  3525. }
  3526. if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  3527. {
  3528. if( ctx->type.dataType.IsIntegerType() ||
  3529. ctx->type.dataType.IsUnsignedType() ||
  3530. ctx->type.dataType.IsEnumType() )
  3531. {
  3532. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3533. {
  3534. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3535. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3536. }
  3537. else
  3538. {
  3539. ConvertToTempVariable(ctx);
  3540. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3541. int offset = AllocateVariable(to, true);
  3542. if( ctx->type.dataType.IsUnsignedType() )
  3543. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3544. else
  3545. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3546. ctx->type.SetVariable(to, offset, true);
  3547. }
  3548. }
  3549. else if( ctx->type.dataType.IsFloatType() )
  3550. {
  3551. ConvertToTempVariable(ctx);
  3552. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3553. int offset = AllocateVariable(to, true);
  3554. ctx->bc.InstrW_W(asBC_fTOi64, offset, ctx->type.stackOffset);
  3555. ctx->type.SetVariable(to, offset, true);
  3556. }
  3557. else if( ctx->type.dataType.IsDoubleType() )
  3558. {
  3559. ConvertToTempVariable(ctx);
  3560. ctx->bc.InstrSHORT(asBC_dTOi64, ctx->type.stackOffset);
  3561. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3562. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3563. }
  3564. }
  3565. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  3566. {
  3567. if( ctx->type.dataType.IsIntegerType() ||
  3568. ctx->type.dataType.IsUnsignedType() ||
  3569. ctx->type.dataType.IsEnumType() )
  3570. {
  3571. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3572. {
  3573. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3574. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3575. }
  3576. else
  3577. {
  3578. ConvertToTempVariable(ctx);
  3579. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3580. int offset = AllocateVariable(to, true);
  3581. ctx->bc.InstrW_W(asBC_i64TOi, offset, ctx->type.stackOffset);
  3582. ctx->type.SetVariable(to, offset, true);
  3583. }
  3584. }
  3585. else if( ctx->type.dataType.IsFloatType() )
  3586. {
  3587. ConvertToTempVariable(ctx);
  3588. ctx->bc.InstrSHORT(asBC_fTOu, ctx->type.stackOffset);
  3589. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3590. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3591. }
  3592. else if( ctx->type.dataType.IsDoubleType() )
  3593. {
  3594. ConvertToTempVariable(ctx);
  3595. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3596. int offset = AllocateVariable(to, true);
  3597. ctx->bc.InstrW_W(asBC_dTOu, offset, ctx->type.stackOffset);
  3598. ctx->type.SetVariable(to, offset, true);
  3599. }
  3600. // Convert to smaller integer if necessary
  3601. int s = to.GetSizeInMemoryBytes();
  3602. if( s < 4 )
  3603. {
  3604. ConvertToTempVariable(ctx);
  3605. if( s == 1 )
  3606. ctx->bc.InstrSHORT(asBC_iTOb, ctx->type.stackOffset);
  3607. else if( s == 2 )
  3608. ctx->bc.InstrSHORT(asBC_iTOw, ctx->type.stackOffset);
  3609. }
  3610. }
  3611. if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  3612. {
  3613. if( ctx->type.dataType.IsIntegerType() ||
  3614. ctx->type.dataType.IsUnsignedType() ||
  3615. ctx->type.dataType.IsEnumType() )
  3616. {
  3617. if( ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3618. {
  3619. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3620. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3621. }
  3622. else
  3623. {
  3624. ConvertToTempVariable(ctx);
  3625. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3626. int offset = AllocateVariable(to, true);
  3627. if( ctx->type.dataType.IsUnsignedType() )
  3628. ctx->bc.InstrW_W(asBC_uTOi64, offset, ctx->type.stackOffset);
  3629. else
  3630. ctx->bc.InstrW_W(asBC_iTOi64, offset, ctx->type.stackOffset);
  3631. ctx->type.SetVariable(to, offset, true);
  3632. }
  3633. }
  3634. else if( ctx->type.dataType.IsFloatType() )
  3635. {
  3636. ConvertToTempVariable(ctx);
  3637. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3638. int offset = AllocateVariable(to, true);
  3639. ctx->bc.InstrW_W(asBC_fTOu64, offset, ctx->type.stackOffset);
  3640. ctx->type.SetVariable(to, offset, true);
  3641. }
  3642. else if( ctx->type.dataType.IsDoubleType() )
  3643. {
  3644. ConvertToTempVariable(ctx);
  3645. ctx->bc.InstrSHORT(asBC_dTOu64, ctx->type.stackOffset);
  3646. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3647. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3648. }
  3649. }
  3650. else if( to.IsFloatType() )
  3651. {
  3652. if( (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType()) && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3653. {
  3654. ConvertToTempVariable(ctx);
  3655. ctx->bc.InstrSHORT(asBC_iTOf, ctx->type.stackOffset);
  3656. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3657. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3658. }
  3659. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3660. {
  3661. ConvertToTempVariable(ctx);
  3662. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3663. int offset = AllocateVariable(to, true);
  3664. ctx->bc.InstrW_W(asBC_i64TOf, offset, ctx->type.stackOffset);
  3665. ctx->type.SetVariable(to, offset, true);
  3666. }
  3667. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3668. {
  3669. ConvertToTempVariable(ctx);
  3670. ctx->bc.InstrSHORT(asBC_uTOf, ctx->type.stackOffset);
  3671. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3672. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3673. }
  3674. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3675. {
  3676. ConvertToTempVariable(ctx);
  3677. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3678. int offset = AllocateVariable(to, true);
  3679. ctx->bc.InstrW_W(asBC_u64TOf, offset, ctx->type.stackOffset);
  3680. ctx->type.SetVariable(to, offset, true);
  3681. }
  3682. else if( ctx->type.dataType.IsDoubleType() )
  3683. {
  3684. ConvertToTempVariable(ctx);
  3685. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3686. int offset = AllocateVariable(to, true);
  3687. ctx->bc.InstrW_W(asBC_dTOf, offset, ctx->type.stackOffset);
  3688. ctx->type.SetVariable(to, offset, true);
  3689. }
  3690. }
  3691. else if( to.IsDoubleType() )
  3692. {
  3693. if( (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType()) && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3694. {
  3695. ConvertToTempVariable(ctx);
  3696. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3697. int offset = AllocateVariable(to, true);
  3698. ctx->bc.InstrW_W(asBC_iTOd, offset, ctx->type.stackOffset);
  3699. ctx->type.SetVariable(to, offset, true);
  3700. }
  3701. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3702. {
  3703. ConvertToTempVariable(ctx);
  3704. ctx->bc.InstrSHORT(asBC_i64TOd, ctx->type.stackOffset);
  3705. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3706. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3707. }
  3708. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  3709. {
  3710. ConvertToTempVariable(ctx);
  3711. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3712. int offset = AllocateVariable(to, true);
  3713. ctx->bc.InstrW_W(asBC_uTOd, offset, ctx->type.stackOffset);
  3714. ctx->type.SetVariable(to, offset, true);
  3715. }
  3716. else if( ctx->type.dataType.IsUnsignedType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  3717. {
  3718. ConvertToTempVariable(ctx);
  3719. ctx->bc.InstrSHORT(asBC_u64TOd, ctx->type.stackOffset);
  3720. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3721. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3722. }
  3723. else if( ctx->type.dataType.IsFloatType() )
  3724. {
  3725. ConvertToTempVariable(ctx);
  3726. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  3727. int offset = AllocateVariable(to, true);
  3728. ctx->bc.InstrW_W(asBC_fTOd, offset, ctx->type.stackOffset);
  3729. ctx->type.SetVariable(to, offset, true);
  3730. }
  3731. }
  3732. }
  3733. else
  3734. {
  3735. if( (to.IsIntegerType() || to.IsUnsignedType() ||
  3736. to.IsFloatType() || to.IsDoubleType() ||
  3737. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST)) &&
  3738. (ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() ||
  3739. ctx->type.dataType.IsFloatType() || ctx->type.dataType.IsDoubleType() ||
  3740. ctx->type.dataType.IsEnumType()) )
  3741. {
  3742. ctx->type.dataType.SetTokenType(to.GetTokenType());
  3743. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3744. }
  3745. }
  3746. // Primitive types on the stack, can be const or non-const
  3747. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  3748. return cost;
  3749. }
  3750. asUINT asCCompiler::ImplicitConversion(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, bool allowObjectConstruct)
  3751. {
  3752. asASSERT( ctx->type.dataType.GetTokenType() != ttUnrecognizedToken ||
  3753. ctx->type.dataType.IsNullHandle() );
  3754. // No conversion from void to any other type
  3755. if( ctx->type.dataType.GetTokenType() == ttVoid )
  3756. return asCC_NO_CONV;
  3757. // Do we want a var type?
  3758. if( to.GetTokenType() == ttQuestion )
  3759. {
  3760. // Any type can be converted to a var type, but only when not generating code
  3761. asASSERT( !generateCode );
  3762. ctx->type.dataType = to;
  3763. return asCC_VARIABLE_CONV;
  3764. }
  3765. // Do we want a primitive?
  3766. else if( to.IsPrimitive() )
  3767. {
  3768. if( !ctx->type.dataType.IsPrimitive() )
  3769. return ImplicitConvObjectToPrimitive(ctx, to, node, convType, generateCode);
  3770. else
  3771. return ImplicitConvPrimitiveToPrimitive(ctx, to, node, convType, generateCode);
  3772. }
  3773. else // The target is a complex type
  3774. {
  3775. if( ctx->type.dataType.IsPrimitive() )
  3776. return ImplicitConvPrimitiveToObject(ctx, to, node, convType, generateCode, allowObjectConstruct);
  3777. else if( ctx->type.IsNullConstant() || ctx->type.dataType.GetObjectType() )
  3778. return ImplicitConvObjectToObject(ctx, to, node, convType, generateCode, allowObjectConstruct);
  3779. }
  3780. return asCC_NO_CONV;
  3781. }
  3782. asUINT asCCompiler::ImplicitConvObjectToPrimitive(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  3783. {
  3784. if( ctx->type.isExplicitHandle )
  3785. {
  3786. // An explicit handle cannot be converted to a primitive
  3787. if( convType != asIC_IMPLICIT_CONV && node )
  3788. {
  3789. asCString str;
  3790. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3791. Error(str.AddressOf(), node);
  3792. }
  3793. return asCC_NO_CONV;
  3794. }
  3795. // TODO: Must use the const cast behaviour if the object is read-only
  3796. // Find matching value cast behaviours
  3797. // Here we're only interested in those that convert the type to a primitive type
  3798. asCArray<int> funcs;
  3799. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  3800. if( beh )
  3801. {
  3802. if( convType == asIC_EXPLICIT_VAL_CAST )
  3803. {
  3804. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3805. {
  3806. // accept both implicit and explicit cast
  3807. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  3808. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  3809. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  3810. funcs.PushLast(beh->operators[n+1]);
  3811. }
  3812. }
  3813. else
  3814. {
  3815. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3816. {
  3817. // accept only implicit cast
  3818. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  3819. builder->GetFunctionDescription(beh->operators[n+1])->returnType.IsPrimitive() )
  3820. funcs.PushLast(beh->operators[n+1]);
  3821. }
  3822. }
  3823. }
  3824. // This matrix describes the priorities of the types to search for, for each target type
  3825. // The first column is the target type, the priorities goes from left to right
  3826. eTokenType matchMtx[10][10] =
  3827. {
  3828. {ttDouble, ttFloat, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  3829. {ttFloat, ttDouble, ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8},
  3830. {ttInt64, ttUInt64, ttInt, ttUInt, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  3831. {ttUInt64, ttInt64, ttUInt, ttInt, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  3832. {ttInt, ttUInt, ttInt64, ttUInt64, ttInt16, ttUInt16, ttInt8, ttUInt8, ttDouble, ttFloat},
  3833. {ttUInt, ttInt, ttUInt64, ttInt64, ttUInt16, ttInt16, ttUInt8, ttInt8, ttDouble, ttFloat},
  3834. {ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttInt8, ttUInt8, ttDouble, ttFloat},
  3835. {ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttUInt8, ttInt8, ttDouble, ttFloat},
  3836. {ttInt8, ttUInt8, ttInt16, ttUInt16, ttInt, ttUInt, ttInt64, ttUInt64, ttDouble, ttFloat},
  3837. {ttUInt8, ttInt8, ttUInt16, ttInt16, ttUInt, ttInt, ttUInt64, ttInt64, ttDouble, ttFloat},
  3838. };
  3839. // Which row to use?
  3840. eTokenType *row = 0;
  3841. for( unsigned int type = 0; type < 10; type++ )
  3842. {
  3843. if( to.GetTokenType() == matchMtx[type][0] )
  3844. {
  3845. row = &matchMtx[type][0];
  3846. break;
  3847. }
  3848. }
  3849. // Find the best matching cast operator
  3850. int funcId = 0;
  3851. if( row )
  3852. {
  3853. asCDataType target(to);
  3854. // Priority goes from left to right in the matrix
  3855. for( unsigned int attempt = 0; attempt < 10 && funcId == 0; attempt++ )
  3856. {
  3857. target.SetTokenType(row[attempt]);
  3858. for( unsigned int n = 0; n < funcs.GetLength(); n++ )
  3859. {
  3860. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[n]);
  3861. if( descr->returnType.IsEqualExceptConst(target) )
  3862. {
  3863. funcId = funcs[n];
  3864. break;
  3865. }
  3866. }
  3867. }
  3868. }
  3869. // Did we find a suitable function?
  3870. if( funcId != 0 )
  3871. {
  3872. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  3873. if( generateCode )
  3874. {
  3875. asCTypeInfo objType = ctx->type;
  3876. Dereference(ctx, true);
  3877. PerformFunctionCall(funcId, ctx);
  3878. ReleaseTemporaryVariable(objType, &ctx->bc);
  3879. }
  3880. else
  3881. ctx->type.Set(descr->returnType);
  3882. // Allow one more implicit conversion to another primitive type
  3883. return asCC_OBJ_TO_PRIMITIVE_CONV + ImplicitConversion(ctx, to, node, convType, generateCode, false);
  3884. }
  3885. else
  3886. {
  3887. if( convType != asIC_IMPLICIT_CONV && node )
  3888. {
  3889. asCString str;
  3890. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  3891. Error(str.AddressOf(), node);
  3892. }
  3893. }
  3894. return asCC_NO_CONV;
  3895. }
  3896. asUINT asCCompiler::ImplicitConvObjectRef(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode)
  3897. {
  3898. // Convert null to any object type handle, but not to a non-handle type
  3899. if( ctx->type.IsNullConstant() )
  3900. {
  3901. if( to.IsObjectHandle() )
  3902. {
  3903. ctx->type.dataType = to;
  3904. return asCC_REF_CONV;
  3905. }
  3906. return asCC_NO_CONV;
  3907. }
  3908. asASSERT(ctx->type.dataType.GetObjectType());
  3909. // First attempt to convert the base type without instanciating another instance
  3910. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  3911. {
  3912. // If the to type is an interface and the from type implements it, then we can convert it immediately
  3913. if( ctx->type.dataType.GetObjectType()->Implements(to.GetObjectType()) )
  3914. {
  3915. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3916. return asCC_REF_CONV;
  3917. }
  3918. // If the to type is a class and the from type derives from it, then we can convert it immediately
  3919. else if( ctx->type.dataType.GetObjectType()->DerivesFrom(to.GetObjectType()) )
  3920. {
  3921. ctx->type.dataType.SetObjectType(to.GetObjectType());
  3922. return asCC_REF_CONV;
  3923. }
  3924. // If the types are not equal yet, then we may still be able to find a reference cast
  3925. else if( ctx->type.dataType.GetObjectType() != to.GetObjectType() )
  3926. {
  3927. // A ref cast must not remove the constness
  3928. bool isConst = false;
  3929. if( (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) ||
  3930. (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) )
  3931. isConst = true;
  3932. // We may still be able to find an implicit ref cast behaviour
  3933. CompileRefCast(ctx, to, convType == asIC_EXPLICIT_REF_CAST, node, generateCode);
  3934. ctx->type.dataType.MakeHandleToConst(isConst);
  3935. // Was the conversion done?
  3936. if( ctx->type.dataType.GetObjectType() == to.GetObjectType() )
  3937. return asCC_REF_CONV;
  3938. }
  3939. }
  3940. // Convert matching function types
  3941. if( to.GetFuncDef() && ctx->type.dataType.GetFuncDef() &&
  3942. to.GetFuncDef() != ctx->type.dataType.GetFuncDef() )
  3943. {
  3944. asCScriptFunction *toFunc = to.GetFuncDef();
  3945. asCScriptFunction *fromFunc = ctx->type.dataType.GetFuncDef();
  3946. if( toFunc->IsSignatureExceptNameEqual(fromFunc) )
  3947. {
  3948. ctx->type.dataType.SetFuncDef(toFunc);
  3949. return asCC_REF_CONV;
  3950. }
  3951. }
  3952. return asCC_NO_CONV;
  3953. }
  3954. asUINT asCCompiler::ImplicitConvObjectValue(asSExprContext *ctx, const asCDataType &to, asCScriptNode * /*node*/, EImplicitConv convType, bool generateCode)
  3955. {
  3956. asUINT cost = asCC_NO_CONV;
  3957. // If the base type is still different, and we are allowed to instance
  3958. // another object then we can try an implicit value cast
  3959. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  3960. {
  3961. // TODO: Implement support for implicit constructor/factory
  3962. asCArray<int> funcs;
  3963. asSTypeBehaviour *beh = ctx->type.dataType.GetBehaviour();
  3964. if( beh )
  3965. {
  3966. if( convType == asIC_EXPLICIT_VAL_CAST )
  3967. {
  3968. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3969. {
  3970. // accept both implicit and explicit cast
  3971. if( (beh->operators[n] == asBEHAVE_VALUE_CAST ||
  3972. beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST) &&
  3973. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  3974. funcs.PushLast(beh->operators[n+1]);
  3975. }
  3976. }
  3977. else
  3978. {
  3979. for( unsigned int n = 0; n < beh->operators.GetLength(); n += 2 )
  3980. {
  3981. // accept only implicit cast
  3982. if( beh->operators[n] == asBEHAVE_IMPLICIT_VALUE_CAST &&
  3983. builder->GetFunctionDescription(beh->operators[n+1])->returnType.GetObjectType() == to.GetObjectType() )
  3984. funcs.PushLast(beh->operators[n+1]);
  3985. }
  3986. }
  3987. }
  3988. // TODO: If there are multiple valid value casts, then we must choose the most appropriate one
  3989. asASSERT( funcs.GetLength() <= 1 );
  3990. if( funcs.GetLength() == 1 )
  3991. {
  3992. asCScriptFunction *f = builder->GetFunctionDescription(funcs[0]);
  3993. if( generateCode )
  3994. {
  3995. asCTypeInfo objType = ctx->type;
  3996. Dereference(ctx, true);
  3997. bool useVariable = false;
  3998. int stackOffset = 0;
  3999. if( f->DoesReturnOnStack() )
  4000. {
  4001. useVariable = true;
  4002. stackOffset = AllocateVariable(f->returnType, true);
  4003. // Push the pointer to the pre-allocated space for the return value
  4004. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  4005. // The object pointer is already on the stack, but should be the top
  4006. // one, so we need to swap the pointers in order to get the correct
  4007. ctx->bc.Instr(asBC_SwapPtr);
  4008. }
  4009. PerformFunctionCall(funcs[0], ctx, false, 0, 0, useVariable, stackOffset);
  4010. ReleaseTemporaryVariable(objType, &ctx->bc);
  4011. }
  4012. else
  4013. ctx->type.Set(f->returnType);
  4014. cost = asCC_TO_OBJECT_CONV;
  4015. }
  4016. }
  4017. return cost;
  4018. }
  4019. asUINT asCCompiler::ImplicitConvObjectToObject(asSExprContext *ctx, const asCDataType &to, asCScriptNode *node, EImplicitConv convType, bool generateCode, bool allowObjectConstruct)
  4020. {
  4021. // First try a ref cast
  4022. asUINT cost = ImplicitConvObjectRef(ctx, to, node, convType, generateCode);
  4023. // If the desired type is an asOBJ_ASHANDLE then we'll assume it is allowed to implicitly
  4024. // construct the object through any of the available constructors
  4025. if( to.GetObjectType() && (to.GetObjectType()->flags & asOBJ_ASHANDLE) && to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  4026. {
  4027. asCArray<int> funcs;
  4028. funcs = to.GetObjectType()->beh.constructors;
  4029. asCArray<asSExprContext *> args;
  4030. args.PushLast(ctx);
  4031. cost = asCC_TO_OBJECT_CONV + MatchFunctions(funcs, args, node, 0, 0, false, true, false);
  4032. // Did we find a matching constructor?
  4033. if( funcs.GetLength() == 1 )
  4034. {
  4035. if( generateCode )
  4036. {
  4037. // TODO: This should really reuse the code from CompileConstructCall
  4038. // Allocate the new object
  4039. asCTypeInfo tempObj;
  4040. tempObj.dataType = to;
  4041. tempObj.dataType.MakeReference(false);
  4042. tempObj.stackOffset = (short)AllocateVariable(tempObj.dataType, true);
  4043. tempObj.dataType.MakeReference(true);
  4044. tempObj.isTemporary = true;
  4045. tempObj.isVariable = true;
  4046. bool onHeap = IsVariableOnHeap(tempObj.stackOffset);
  4047. // Push the address of the object on the stack
  4048. asSExprContext e(engine);
  4049. if( onHeap )
  4050. e.bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  4051. PrepareFunctionCall(funcs[0], &e.bc, args);
  4052. MoveArgsToStack(funcs[0], &e.bc, args, false);
  4053. // If the object is allocated on the stack, then call the constructor as a normal function
  4054. if( onHeap )
  4055. {
  4056. int offset = 0;
  4057. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  4058. offset = descr->parameterTypes[0].GetSizeOnStackDWords();
  4059. e.bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  4060. }
  4061. else
  4062. e.bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  4063. PerformFunctionCall(funcs[0], &e, onHeap, &args, tempObj.dataType.GetObjectType());
  4064. // Add tag that the object has been initialized
  4065. e.bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  4066. // The constructor doesn't return anything,
  4067. // so we have to manually inform the type of
  4068. // the return value
  4069. e.type = tempObj;
  4070. if( !onHeap )
  4071. e.type.dataType.MakeReference(false);
  4072. // Push the address of the object on the stack again
  4073. e.bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  4074. MergeExprBytecodeAndType(ctx, &e);
  4075. }
  4076. else
  4077. {
  4078. ctx->type.Set(asCDataType::CreateObject(to.GetObjectType(), false));
  4079. }
  4080. }
  4081. }
  4082. // If the base type is still different, and we are allowed to instance
  4083. // another object then we can try an implicit value cast
  4084. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() && allowObjectConstruct )
  4085. {
  4086. // Attempt implicit value cast
  4087. cost = ImplicitConvObjectValue(ctx, to, node, convType, generateCode);
  4088. }
  4089. // If we still haven't converted the base type to the correct type, then there is
  4090. // no need to continue as it is not possible to do the conversion
  4091. if( to.GetObjectType() != ctx->type.dataType.GetObjectType() )
  4092. return asCC_NO_CONV;
  4093. if( to.IsObjectHandle() )
  4094. {
  4095. // There is no extra cost in converting to a handle
  4096. // reference to handle -> handle
  4097. // reference -> handle
  4098. // object -> handle
  4099. // handle -> reference to handle
  4100. // reference -> reference to handle
  4101. // object -> reference to handle
  4102. // TODO: If the type is handle, then we can't use IsReadOnly to determine the constness of the basetype
  4103. // If the rvalue is a handle to a const object, then
  4104. // the lvalue must also be a handle to a const object
  4105. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() )
  4106. {
  4107. if( convType != asIC_IMPLICIT_CONV )
  4108. {
  4109. asASSERT(node);
  4110. asCString str;
  4111. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, ctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  4112. Error(str.AddressOf(), node);
  4113. }
  4114. }
  4115. if( !ctx->type.dataType.IsObjectHandle() )
  4116. {
  4117. // An object type can be directly converted to a handle of the same type
  4118. if( ctx->type.dataType.SupportHandles() )
  4119. {
  4120. ctx->type.dataType.MakeHandle(true);
  4121. }
  4122. if( ctx->type.dataType.IsObjectHandle() )
  4123. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4124. if( to.IsHandleToConst() && ctx->type.dataType.IsObjectHandle() )
  4125. ctx->type.dataType.MakeHandleToConst(true);
  4126. }
  4127. else
  4128. {
  4129. // A handle to non-const can be converted to a
  4130. // handle to const, but not the other way
  4131. if( to.IsHandleToConst() )
  4132. ctx->type.dataType.MakeHandleToConst(true);
  4133. // A const handle can be converted to a non-const
  4134. // handle and vice versa as the handle is just a value
  4135. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4136. }
  4137. if( to.IsReference() && !ctx->type.dataType.IsReference() )
  4138. {
  4139. if( generateCode )
  4140. {
  4141. asASSERT( ctx->type.dataType.IsObjectHandle() );
  4142. // If the input type is a handle, then a simple ref copy is enough
  4143. bool isExplicitHandle = ctx->type.isExplicitHandle;
  4144. ctx->type.isExplicitHandle = ctx->type.dataType.IsObjectHandle();
  4145. // If the input type is read-only we'll need to temporarily
  4146. // remove this constness, otherwise the assignment will fail
  4147. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  4148. ctx->type.dataType.MakeReadOnly(false);
  4149. // If the object already is a temporary variable, then the copy
  4150. // doesn't have to be made as it is already a unique object
  4151. PrepareTemporaryObject(node, ctx);
  4152. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  4153. ctx->type.isExplicitHandle = isExplicitHandle;
  4154. }
  4155. // A non-reference can be converted to a reference,
  4156. // by putting the value in a temporary variable
  4157. ctx->type.dataType.MakeReference(true);
  4158. // Since it is a new temporary variable it doesn't have to be const
  4159. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4160. }
  4161. else if( !to.IsReference() && ctx->type.dataType.IsReference() )
  4162. {
  4163. Dereference(ctx, generateCode);
  4164. }
  4165. }
  4166. else
  4167. {
  4168. if( !to.IsReference() )
  4169. {
  4170. // reference to handle -> object
  4171. // handle -> object
  4172. // reference -> object
  4173. // An implicit handle can be converted to an object by adding a check for null pointer
  4174. if( ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  4175. {
  4176. if( generateCode )
  4177. ctx->bc.Instr(asBC_CHKREF);
  4178. ctx->type.dataType.MakeHandle(false);
  4179. }
  4180. // A const object can be converted to a non-const object through a copy
  4181. if( ctx->type.dataType.IsReadOnly() && !to.IsReadOnly() &&
  4182. allowObjectConstruct )
  4183. {
  4184. // Does the object type allow a copy to be made?
  4185. if( ctx->type.dataType.CanBeCopied() )
  4186. {
  4187. if( generateCode )
  4188. {
  4189. // Make a temporary object with the copy
  4190. PrepareTemporaryObject(node, ctx);
  4191. }
  4192. // In case the object was already in a temporary variable, then the function
  4193. // didn't really do anything so we need to remove the constness here
  4194. ctx->type.dataType.MakeReadOnly(false);
  4195. // Add the cost for the copy
  4196. cost += asCC_TO_OBJECT_CONV;
  4197. }
  4198. }
  4199. if( ctx->type.dataType.IsReference() )
  4200. {
  4201. // This may look strange, but a value type allocated on the stack is already
  4202. // correct, so nothing should be done other than remove the mark as reference.
  4203. // For types allocated on the heap, it is necessary to dereference the pointer
  4204. // that is currently on the stack
  4205. if( IsVariableOnHeap(ctx->type.stackOffset) )
  4206. Dereference(ctx, generateCode);
  4207. else
  4208. ctx->type.dataType.MakeReference(false);
  4209. }
  4210. // A non-const object can be converted to a const object directly
  4211. if( !ctx->type.dataType.IsReadOnly() && to.IsReadOnly() )
  4212. {
  4213. ctx->type.dataType.MakeReadOnly(true);
  4214. }
  4215. }
  4216. else
  4217. {
  4218. // reference to handle -> reference
  4219. // handle -> reference
  4220. // object -> reference
  4221. if( ctx->type.dataType.IsReference() )
  4222. {
  4223. if( ctx->type.isExplicitHandle && ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  4224. {
  4225. // ASHANDLE objects are really value types, so explicit handle can be removed
  4226. ctx->type.isExplicitHandle = false;
  4227. ctx->type.dataType.MakeHandle(false);
  4228. }
  4229. // A reference to a handle can be converted to a reference to an object
  4230. // by first reading the address, then verifying that it is not null
  4231. if( !to.IsObjectHandle() && ctx->type.dataType.IsObjectHandle() && !ctx->type.isExplicitHandle )
  4232. {
  4233. ctx->type.dataType.MakeHandle(false);
  4234. if( generateCode )
  4235. ctx->bc.Instr(asBC_ChkRefS);
  4236. }
  4237. // A reference to a non-const can be converted to a reference to a const
  4238. if( to.IsReadOnly() )
  4239. ctx->type.dataType.MakeReadOnly(true);
  4240. else if( ctx->type.dataType.IsReadOnly() )
  4241. {
  4242. // A reference to a const can be converted to a reference to a
  4243. // non-const by copying the object to a temporary variable
  4244. ctx->type.dataType.MakeReadOnly(false);
  4245. if( generateCode )
  4246. {
  4247. // If the object already is a temporary variable, then the copy
  4248. // doesn't have to be made as it is already a unique object
  4249. PrepareTemporaryObject(node, ctx);
  4250. }
  4251. // Add the cost for the copy
  4252. cost += asCC_TO_OBJECT_CONV;
  4253. }
  4254. }
  4255. else
  4256. {
  4257. // A value type allocated on the stack is differentiated
  4258. // by it not being a reference. But it can be handled as
  4259. // reference by pushing the pointer on the stack
  4260. if( (ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) &&
  4261. (ctx->type.isVariable || ctx->type.isTemporary) &&
  4262. !IsVariableOnHeap(ctx->type.stackOffset) )
  4263. {
  4264. // Actually the pointer is already pushed on the stack in
  4265. // CompileVariableAccess, so we don't need to do anything else
  4266. }
  4267. else if( generateCode )
  4268. {
  4269. // A non-reference can be converted to a reference,
  4270. // by putting the value in a temporary variable
  4271. // If the input type is read-only we'll need to temporarily
  4272. // remove this constness, otherwise the assignment will fail
  4273. bool typeIsReadOnly = ctx->type.dataType.IsReadOnly();
  4274. ctx->type.dataType.MakeReadOnly(false);
  4275. // If the object already is a temporary variable, then the copy
  4276. // doesn't have to be made as it is already a unique object
  4277. PrepareTemporaryObject(node, ctx);
  4278. ctx->type.dataType.MakeReadOnly(typeIsReadOnly);
  4279. // Add the cost for the copy
  4280. cost += asCC_TO_OBJECT_CONV;
  4281. }
  4282. // A handle can be converted to a reference, by checking for a null pointer
  4283. if( ctx->type.dataType.IsObjectHandle() )
  4284. {
  4285. if( generateCode )
  4286. ctx->bc.InstrSHORT(asBC_ChkNullV, ctx->type.stackOffset);
  4287. ctx->type.dataType.MakeHandle(false);
  4288. ctx->type.dataType.MakeReference(true);
  4289. // TODO: Make sure a handle to const isn't converted to non-const reference
  4290. }
  4291. else
  4292. {
  4293. // This may look strange as the conversion was to make the expression a reference
  4294. // but a value type allocated on the stack is a reference even without the type
  4295. // being marked as such.
  4296. ctx->type.dataType.MakeReference(IsVariableOnHeap(ctx->type.stackOffset));
  4297. }
  4298. // TODO: If the variable is an object allocated on the stack the following is not true as the copy may not have been made
  4299. // Since it is a new temporary variable it doesn't have to be const
  4300. ctx->type.dataType.MakeReadOnly(to.IsReadOnly());
  4301. }
  4302. }
  4303. }
  4304. return cost;
  4305. }
  4306. asUINT asCCompiler::ImplicitConvPrimitiveToObject(asSExprContext * /*ctx*/, const asCDataType & /*to*/, asCScriptNode * /*node*/, EImplicitConv /*isExplicit*/, bool /*generateCode*/, bool /*allowObjectConstruct*/)
  4307. {
  4308. // TODO: This function should call the constructor/factory that has been marked as available
  4309. // for implicit conversions. The code will likely be similar to CallCopyConstructor()
  4310. return asCC_NO_CONV;
  4311. }
  4312. void asCCompiler::ImplicitConversionConstant(asSExprContext *from, const asCDataType &to, asCScriptNode *node, EImplicitConv convType)
  4313. {
  4314. asASSERT(from->type.isConstant);
  4315. // TODO: node should be the node of the value that is
  4316. // converted (not the operator that provokes the implicit
  4317. // conversion)
  4318. // If the base type is correct there is no more to do
  4319. if( to.IsEqualExceptRefAndConst(from->type.dataType) ) return;
  4320. // References cannot be constants
  4321. if( from->type.dataType.IsReference() ) return;
  4322. if( (to.IsIntegerType() && to.GetSizeInMemoryDWords() == 1) ||
  4323. (to.IsEnumType() && convType == asIC_EXPLICIT_VAL_CAST) )
  4324. {
  4325. if( from->type.dataType.IsFloatType() ||
  4326. from->type.dataType.IsDoubleType() ||
  4327. from->type.dataType.IsUnsignedType() ||
  4328. from->type.dataType.IsIntegerType() ||
  4329. from->type.dataType.IsEnumType() )
  4330. {
  4331. // Transform the value
  4332. // Float constants can be implicitly converted to int
  4333. if( from->type.dataType.IsFloatType() )
  4334. {
  4335. float fc = from->type.floatValue;
  4336. int ic = int(fc);
  4337. if( float(ic) != fc )
  4338. {
  4339. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4340. }
  4341. from->type.intValue = ic;
  4342. }
  4343. // Double constants can be implicitly converted to int
  4344. else if( from->type.dataType.IsDoubleType() )
  4345. {
  4346. double fc = from->type.doubleValue;
  4347. int ic = int(fc);
  4348. if( double(ic) != fc )
  4349. {
  4350. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4351. }
  4352. from->type.intValue = ic;
  4353. }
  4354. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4355. {
  4356. // Verify that it is possible to convert to signed without getting negative
  4357. if( from->type.intValue < 0 )
  4358. {
  4359. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4360. }
  4361. // Convert to 32bit
  4362. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4363. from->type.intValue = from->type.byteValue;
  4364. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4365. from->type.intValue = from->type.wordValue;
  4366. }
  4367. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4368. {
  4369. // Convert to 32bit
  4370. from->type.intValue = int(from->type.qwordValue);
  4371. }
  4372. else if( from->type.dataType.IsIntegerType() &&
  4373. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4374. {
  4375. // Convert to 32bit
  4376. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4377. from->type.intValue = (signed char)from->type.byteValue;
  4378. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4379. from->type.intValue = (short)from->type.wordValue;
  4380. }
  4381. else if( from->type.dataType.IsEnumType() )
  4382. {
  4383. // Enum type is already an integer type
  4384. }
  4385. // Set the resulting type
  4386. if( to.IsEnumType() )
  4387. from->type.dataType = to;
  4388. else
  4389. from->type.dataType = asCDataType::CreatePrimitive(ttInt, true);
  4390. }
  4391. // Check if a downsize is necessary
  4392. if( to.IsIntegerType() &&
  4393. from->type.dataType.IsIntegerType() &&
  4394. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4395. {
  4396. // Verify if it is possible
  4397. if( to.GetSizeInMemoryBytes() == 1 )
  4398. {
  4399. if( char(from->type.intValue) != from->type.intValue )
  4400. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4401. from->type.byteValue = char(from->type.intValue);
  4402. }
  4403. else if( to.GetSizeInMemoryBytes() == 2 )
  4404. {
  4405. if( short(from->type.intValue) != from->type.intValue )
  4406. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4407. from->type.wordValue = short(from->type.intValue);
  4408. }
  4409. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4410. }
  4411. }
  4412. else if( to.IsIntegerType() && to.GetSizeInMemoryDWords() == 2 )
  4413. {
  4414. // Float constants can be implicitly converted to int
  4415. if( from->type.dataType.IsFloatType() )
  4416. {
  4417. float fc = from->type.floatValue;
  4418. asINT64 ic = asINT64(fc);
  4419. if( float(ic) != fc )
  4420. {
  4421. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4422. }
  4423. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4424. from->type.qwordValue = ic;
  4425. }
  4426. // Double constants can be implicitly converted to int
  4427. else if( from->type.dataType.IsDoubleType() )
  4428. {
  4429. double fc = from->type.doubleValue;
  4430. asINT64 ic = asINT64(fc);
  4431. if( double(ic) != fc )
  4432. {
  4433. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4434. }
  4435. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4436. from->type.qwordValue = ic;
  4437. }
  4438. else if( from->type.dataType.IsUnsignedType() )
  4439. {
  4440. // Convert to 64bit
  4441. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4442. from->type.qwordValue = from->type.byteValue;
  4443. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4444. from->type.qwordValue = from->type.wordValue;
  4445. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4446. from->type.qwordValue = from->type.dwordValue;
  4447. else if( from->type.dataType.GetSizeInMemoryBytes() == 8 )
  4448. {
  4449. if( asINT64(from->type.qwordValue) < 0 )
  4450. {
  4451. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4452. }
  4453. }
  4454. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4455. }
  4456. else if( from->type.dataType.IsEnumType() )
  4457. {
  4458. from->type.qwordValue = from->type.intValue;
  4459. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4460. }
  4461. else if( from->type.dataType.IsIntegerType() )
  4462. {
  4463. // Convert to 64bit
  4464. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4465. from->type.qwordValue = (signed char)from->type.byteValue;
  4466. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4467. from->type.qwordValue = (short)from->type.wordValue;
  4468. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4469. from->type.qwordValue = from->type.intValue;
  4470. from->type.dataType = asCDataType::CreatePrimitive(ttInt64, true);
  4471. }
  4472. }
  4473. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 1 )
  4474. {
  4475. if( from->type.dataType.IsFloatType() )
  4476. {
  4477. float fc = from->type.floatValue;
  4478. // Some compilers set the value to 0 when converting a negative float to unsigned int.
  4479. // To maintain a consistent behaviour across compilers we convert to int first.
  4480. asUINT uic = asUINT(int(fc));
  4481. if( float(uic) != fc )
  4482. {
  4483. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4484. }
  4485. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4486. from->type.intValue = uic;
  4487. // Try once more, in case of a smaller type
  4488. ImplicitConversionConstant(from, to, node, convType);
  4489. }
  4490. else if( from->type.dataType.IsDoubleType() )
  4491. {
  4492. double fc = from->type.doubleValue;
  4493. // Some compilers set the value to 0 when converting a negative double to unsigned int.
  4494. // To maintain a consistent behaviour across compilers we convert to int first.
  4495. asUINT uic = asUINT(int(fc));
  4496. if( double(uic) != fc )
  4497. {
  4498. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4499. }
  4500. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4501. from->type.intValue = uic;
  4502. // Try once more, in case of a smaller type
  4503. ImplicitConversionConstant(from, to, node, convType);
  4504. }
  4505. else if( from->type.dataType.IsEnumType() )
  4506. {
  4507. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4508. // Try once more, in case of a smaller type
  4509. ImplicitConversionConstant(from, to, node, convType);
  4510. }
  4511. else if( from->type.dataType.IsIntegerType() )
  4512. {
  4513. // Verify that it is possible to convert to unsigned without loosing negative
  4514. if( from->type.intValue < 0 )
  4515. {
  4516. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4517. }
  4518. // Convert to 32bit
  4519. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4520. from->type.intValue = (signed char)from->type.byteValue;
  4521. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4522. from->type.intValue = (short)from->type.wordValue;
  4523. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4524. // Try once more, in case of a smaller type
  4525. ImplicitConversionConstant(from, to, node, convType);
  4526. }
  4527. else if( from->type.dataType.IsUnsignedType() &&
  4528. from->type.dataType.GetSizeInMemoryBytes() < 4 )
  4529. {
  4530. // Convert to 32bit
  4531. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4532. from->type.dwordValue = from->type.byteValue;
  4533. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4534. from->type.dwordValue = from->type.wordValue;
  4535. from->type.dataType = asCDataType::CreatePrimitive(ttUInt, true);
  4536. // Try once more, in case of a smaller type
  4537. ImplicitConversionConstant(from, to, node, convType);
  4538. }
  4539. else if( from->type.dataType.IsUnsignedType() &&
  4540. from->type.dataType.GetSizeInMemoryBytes() > to.GetSizeInMemoryBytes() )
  4541. {
  4542. // Verify if it is possible
  4543. if( to.GetSizeInMemoryBytes() == 1 )
  4544. {
  4545. if( asBYTE(from->type.dwordValue) != from->type.dwordValue )
  4546. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4547. from->type.byteValue = asBYTE(from->type.dwordValue);
  4548. }
  4549. else if( to.GetSizeInMemoryBytes() == 2 )
  4550. {
  4551. if( asWORD(from->type.dwordValue) != from->type.dwordValue )
  4552. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_VALUE_TOO_LARGE_FOR_TYPE, node);
  4553. from->type.wordValue = asWORD(from->type.dwordValue);
  4554. }
  4555. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4556. }
  4557. }
  4558. else if( to.IsUnsignedType() && to.GetSizeInMemoryDWords() == 2 )
  4559. {
  4560. if( from->type.dataType.IsFloatType() )
  4561. {
  4562. float fc = from->type.floatValue;
  4563. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  4564. asQWORD uic = asQWORD(asINT64(fc));
  4565. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  4566. // MSVC6 doesn't support this conversion
  4567. if( float(uic) != fc )
  4568. {
  4569. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4570. }
  4571. #endif
  4572. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4573. from->type.qwordValue = uic;
  4574. }
  4575. else if( from->type.dataType.IsDoubleType() )
  4576. {
  4577. double fc = from->type.doubleValue;
  4578. // Convert first to int64 then to uint64 to avoid negative float becoming 0 on gnuc base compilers
  4579. asQWORD uic = asQWORD(asINT64(fc));
  4580. #if !defined(_MSC_VER) || _MSC_VER > 1200 // MSVC++ 6
  4581. // MSVC6 doesn't support this conversion
  4582. if( double(uic) != fc )
  4583. {
  4584. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4585. }
  4586. #endif
  4587. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4588. from->type.qwordValue = uic;
  4589. }
  4590. else if( from->type.dataType.IsEnumType() )
  4591. {
  4592. from->type.qwordValue = (asINT64)from->type.intValue;
  4593. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4594. }
  4595. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4596. {
  4597. // Convert to 64bit
  4598. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4599. from->type.qwordValue = (asINT64)(signed char)from->type.byteValue;
  4600. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4601. from->type.qwordValue = (asINT64)(short)from->type.wordValue;
  4602. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4603. from->type.qwordValue = (asINT64)from->type.intValue;
  4604. // Verify that it is possible to convert to unsigned without loosing negative
  4605. if( asINT64(from->type.qwordValue) < 0 )
  4606. {
  4607. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4608. }
  4609. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4610. }
  4611. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4612. {
  4613. // Verify that it is possible to convert to unsigned without loosing negative
  4614. if( asINT64(from->type.qwordValue) < 0 )
  4615. {
  4616. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_CHANGE_SIGN, node);
  4617. }
  4618. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4619. }
  4620. else if( from->type.dataType.IsUnsignedType() )
  4621. {
  4622. // Convert to 64bit
  4623. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4624. from->type.qwordValue = from->type.byteValue;
  4625. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4626. from->type.qwordValue = from->type.wordValue;
  4627. else if( from->type.dataType.GetSizeInMemoryBytes() == 4 )
  4628. from->type.qwordValue = from->type.dwordValue;
  4629. from->type.dataType = asCDataType::CreatePrimitive(ttUInt64, true);
  4630. }
  4631. }
  4632. else if( to.IsFloatType() )
  4633. {
  4634. if( from->type.dataType.IsDoubleType() )
  4635. {
  4636. double ic = from->type.doubleValue;
  4637. float fc = float(ic);
  4638. // Don't bother warning about this
  4639. // if( double(fc) != ic )
  4640. // {
  4641. // asCString str;
  4642. // str.Format(TXT_POSSIBLE_LOSS_OF_PRECISION);
  4643. // if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(str.AddressOf(), node);
  4644. // }
  4645. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4646. from->type.floatValue = fc;
  4647. }
  4648. else if( from->type.dataType.IsEnumType() )
  4649. {
  4650. float fc = float(from->type.intValue);
  4651. if( int(fc) != from->type.intValue )
  4652. {
  4653. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4654. }
  4655. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4656. from->type.floatValue = fc;
  4657. }
  4658. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4659. {
  4660. // Must properly convert value in case the from value is smaller
  4661. int ic;
  4662. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4663. ic = (signed char)from->type.byteValue;
  4664. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4665. ic = (short)from->type.wordValue;
  4666. else
  4667. ic = from->type.intValue;
  4668. float fc = float(ic);
  4669. if( int(fc) != ic )
  4670. {
  4671. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4672. }
  4673. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4674. from->type.floatValue = fc;
  4675. }
  4676. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4677. {
  4678. float fc = float(asINT64(from->type.qwordValue));
  4679. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  4680. {
  4681. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4682. }
  4683. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4684. from->type.floatValue = fc;
  4685. }
  4686. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4687. {
  4688. // Must properly convert value in case the from value is smaller
  4689. unsigned int uic;
  4690. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4691. uic = from->type.byteValue;
  4692. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4693. uic = from->type.wordValue;
  4694. else
  4695. uic = from->type.dwordValue;
  4696. float fc = float(uic);
  4697. if( (unsigned int)(fc) != uic )
  4698. {
  4699. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4700. }
  4701. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4702. from->type.floatValue = fc;
  4703. }
  4704. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4705. {
  4706. float fc = float((asINT64)from->type.qwordValue);
  4707. if( asQWORD(fc) != from->type.qwordValue )
  4708. {
  4709. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4710. }
  4711. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4712. from->type.floatValue = fc;
  4713. }
  4714. }
  4715. else if( to.IsDoubleType() )
  4716. {
  4717. if( from->type.dataType.IsFloatType() )
  4718. {
  4719. float ic = from->type.floatValue;
  4720. double fc = double(ic);
  4721. // Don't check for float->double
  4722. // if( float(fc) != ic )
  4723. // {
  4724. // acCString str;
  4725. // str.Format(TXT_NOT_EXACT_g_g_g, ic, fc, float(fc));
  4726. // if( !isExplicit ) Warning(str, node);
  4727. // }
  4728. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4729. from->type.doubleValue = fc;
  4730. }
  4731. else if( from->type.dataType.IsEnumType() )
  4732. {
  4733. double fc = double(from->type.intValue);
  4734. if( int(fc) != from->type.intValue )
  4735. {
  4736. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4737. }
  4738. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4739. from->type.doubleValue = fc;
  4740. }
  4741. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4742. {
  4743. // Must properly convert value in case the from value is smaller
  4744. int ic;
  4745. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4746. ic = (signed char)from->type.byteValue;
  4747. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4748. ic = (short)from->type.wordValue;
  4749. else
  4750. ic = from->type.intValue;
  4751. double fc = double(ic);
  4752. if( int(fc) != ic )
  4753. {
  4754. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4755. }
  4756. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4757. from->type.doubleValue = fc;
  4758. }
  4759. else if( from->type.dataType.IsIntegerType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4760. {
  4761. double fc = double(asINT64(from->type.qwordValue));
  4762. if( asINT64(fc) != asINT64(from->type.qwordValue) )
  4763. {
  4764. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4765. }
  4766. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4767. from->type.doubleValue = fc;
  4768. }
  4769. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 1 )
  4770. {
  4771. // Must properly convert value in case the from value is smaller
  4772. unsigned int uic;
  4773. if( from->type.dataType.GetSizeInMemoryBytes() == 1 )
  4774. uic = from->type.byteValue;
  4775. else if( from->type.dataType.GetSizeInMemoryBytes() == 2 )
  4776. uic = from->type.wordValue;
  4777. else
  4778. uic = from->type.dwordValue;
  4779. double fc = double(uic);
  4780. if( (unsigned int)(fc) != uic )
  4781. {
  4782. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4783. }
  4784. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4785. from->type.doubleValue = fc;
  4786. }
  4787. else if( from->type.dataType.IsUnsignedType() && from->type.dataType.GetSizeInMemoryDWords() == 2 )
  4788. {
  4789. double fc = double((asINT64)from->type.qwordValue);
  4790. if( asQWORD(fc) != from->type.qwordValue )
  4791. {
  4792. if( convType != asIC_EXPLICIT_VAL_CAST && node ) Warning(TXT_NOT_EXACT, node);
  4793. }
  4794. from->type.dataType = asCDataType::CreatePrimitive(to.GetTokenType(), true);
  4795. from->type.doubleValue = fc;
  4796. }
  4797. }
  4798. }
  4799. int asCCompiler::DoAssignment(asSExprContext *ctx, asSExprContext *lctx, asSExprContext *rctx, asCScriptNode *lexpr, asCScriptNode *rexpr, int op, asCScriptNode *opNode)
  4800. {
  4801. // Implicit handle types should always be treated as handles in assignments
  4802. if (lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  4803. {
  4804. lctx->type.dataType.MakeHandle(true);
  4805. lctx->type.isExplicitHandle = true;
  4806. }
  4807. // Urho3D: if there is a handle type, and it does not have an overloaded assignment operator, convert to an explicit handle
  4808. // for scripting convenience. (For the Urho3D handle types, value assignment is not supported)
  4809. if (lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle && !lctx->type.dataType.GetBehaviour()->copy)
  4810. lctx->type.isExplicitHandle = true;
  4811. // If the left hand expression is a property accessor, then that should be used
  4812. // to do the assignment instead of the ordinary operator. The exception is when
  4813. // the property accessor is for a handle property, and the operation is a value
  4814. // assignment.
  4815. if( (lctx->property_get || lctx->property_set) &&
  4816. !(lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle) )
  4817. {
  4818. if( op != ttAssignment )
  4819. {
  4820. // TODO: getset: We may actually be able to support this, if we can
  4821. // guarantee that the object reference will stay valid
  4822. // between the calls to the get and set accessors.
  4823. // Process the property to free the memory
  4824. ProcessPropertySetAccessor(lctx, rctx, opNode);
  4825. // Compound assignments are not allowed for properties
  4826. Error(TXT_COMPOUND_ASGN_WITH_PROP, opNode);
  4827. return -1;
  4828. }
  4829. // It is not allowed to do a handle assignment on a property
  4830. // accessor that doesn't take a handle in the set accessor.
  4831. if( lctx->property_set && lctx->type.isExplicitHandle )
  4832. {
  4833. // set_opIndex has 2 arguments, where as normal setters have only 1
  4834. asCArray<asCDataType>& parameterTypes =
  4835. builder->GetFunctionDescription(lctx->property_set)->parameterTypes;
  4836. if( !parameterTypes[parameterTypes.GetLength() - 1].IsObjectHandle() )
  4837. {
  4838. // Process the property to free the memory
  4839. ProcessPropertySetAccessor(lctx, rctx, opNode);
  4840. Error(TXT_HANDLE_ASSIGN_ON_NON_HANDLE_PROP, opNode);
  4841. return -1;
  4842. }
  4843. }
  4844. MergeExprBytecodeAndType(ctx, lctx);
  4845. return ProcessPropertySetAccessor(ctx, rctx, opNode);
  4846. }
  4847. else if( lctx->property_get && lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  4848. {
  4849. // Get the handle to the object that will be used for the value assignment
  4850. ProcessPropertyGetAccessor(lctx, opNode);
  4851. }
  4852. if( lctx->type.dataType.IsPrimitive() )
  4853. {
  4854. if( !lctx->type.isLValue )
  4855. {
  4856. Error(TXT_NOT_LVALUE, lexpr);
  4857. return -1;
  4858. }
  4859. if( op != ttAssignment )
  4860. {
  4861. // Compute the operator before the assignment
  4862. asCTypeInfo lvalue = lctx->type;
  4863. if( lctx->type.isTemporary && !lctx->type.isVariable )
  4864. {
  4865. // The temporary variable must not be freed until the
  4866. // assignment has been performed. lvalue still holds
  4867. // the information about the temporary variable
  4868. lctx->type.isTemporary = false;
  4869. }
  4870. asSExprContext o(engine);
  4871. CompileOperator(opNode, lctx, rctx, &o);
  4872. MergeExprBytecode(rctx, &o);
  4873. rctx->type = o.type;
  4874. // Convert the rvalue to the right type and validate it
  4875. PrepareForAssignment(&lvalue.dataType, rctx, rexpr, false);
  4876. MergeExprBytecode(ctx, rctx);
  4877. lctx->type = lvalue;
  4878. // The lvalue continues the same, either it was a variable, or a reference in the register
  4879. }
  4880. else
  4881. {
  4882. // Convert the rvalue to the right type and validate it
  4883. PrepareForAssignment(&lctx->type.dataType, rctx, rexpr, false, lctx);
  4884. MergeExprBytecode(ctx, rctx);
  4885. MergeExprBytecode(ctx, lctx);
  4886. }
  4887. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4888. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4889. ctx->type = lctx->type;
  4890. }
  4891. else if( lctx->type.isExplicitHandle )
  4892. {
  4893. if( !lctx->type.isLValue )
  4894. {
  4895. Error(TXT_NOT_LVALUE, lexpr);
  4896. return -1;
  4897. }
  4898. // Object handles don't have any compound assignment operators
  4899. if( op != ttAssignment )
  4900. {
  4901. asCString str;
  4902. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4903. Error(str.AddressOf(), lexpr);
  4904. return -1;
  4905. }
  4906. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  4907. {
  4908. // The object is a value type but that should be treated as a handle
  4909. // TODO: handle: Make sure the right hand value is a handle
  4910. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  4911. {
  4912. // An overloaded assignment operator was found (or a compilation error occured)
  4913. return 0;
  4914. }
  4915. // The object must implement the opAssign method
  4916. Error(TXT_NO_APPROPRIATE_OPASSIGN, opNode);
  4917. return -1;
  4918. }
  4919. else
  4920. {
  4921. asCDataType dt = lctx->type.dataType;
  4922. dt.MakeReference(false);
  4923. PrepareArgument(&dt, rctx, rexpr, true, 1);
  4924. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4925. {
  4926. asCString str;
  4927. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  4928. Error(str.AddressOf(), rexpr);
  4929. return -1;
  4930. }
  4931. MergeExprBytecode(ctx, rctx);
  4932. MergeExprBytecode(ctx, lctx);
  4933. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  4934. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  4935. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  4936. ctx->type = rctx->type;
  4937. }
  4938. }
  4939. else // if( lctx->type.dataType.IsObject() )
  4940. {
  4941. // An ASHANDLE type must not allow a value assignment, as
  4942. // the opAssign operator is used for the handle assignment
  4943. if( lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE )
  4944. {
  4945. asCString str;
  4946. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4947. Error(str.AddressOf(), lexpr);
  4948. return -1;
  4949. }
  4950. // The lvalue reference may be marked as a temporary, if for example
  4951. // it was originated as a handle returned from a function. In such
  4952. // cases it must be possible to assign values to it anyway.
  4953. if( lctx->type.dataType.IsObjectHandle() && !lctx->type.isExplicitHandle )
  4954. {
  4955. // Convert the handle to a object reference
  4956. asCDataType to;
  4957. to = lctx->type.dataType;
  4958. to.MakeHandle(false);
  4959. ImplicitConversion(lctx, to, lexpr, asIC_IMPLICIT_CONV);
  4960. lctx->type.isLValue = true; // Handle may not have been an lvalue, but the dereferenced object is
  4961. }
  4962. // Check for overloaded assignment operator
  4963. if( CompileOverloadedDualOperator(opNode, lctx, rctx, ctx) )
  4964. {
  4965. // An overloaded assignment operator was found (or a compilation error occured)
  4966. return 0;
  4967. }
  4968. // No registered operator was found. In case the operation is a direct
  4969. // assignment and the rvalue is the same type as the lvalue, then we can
  4970. // still use the byte-for-byte copy to do the assignment
  4971. if( op != ttAssignment )
  4972. {
  4973. asCString str;
  4974. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  4975. Error(str.AddressOf(), lexpr);
  4976. return -1;
  4977. }
  4978. // If the left hand expression is simple, i.e. without any
  4979. // function calls or allocations of memory, then we can avoid
  4980. // doing a copy of the right hand expression (done by PrepareArgument).
  4981. // Instead the reference to the value can be placed directly on the
  4982. // stack.
  4983. //
  4984. // This optimization should only be done for value types, where
  4985. // the application developer is responsible for making the
  4986. // implementation safe against unwanted destruction of the input
  4987. // reference before the time.
  4988. bool simpleExpr = (lctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_VALUE) && lctx->bc.IsSimpleExpression();
  4989. // Implicitly convert the rvalue to the type of the lvalue
  4990. if( !lctx->type.dataType.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4991. simpleExpr = false;
  4992. if( !simpleExpr )
  4993. {
  4994. asCDataType dt = lctx->type.dataType;
  4995. dt.MakeReference(true);
  4996. dt.MakeReadOnly(true);
  4997. PrepareArgument(&dt, rctx, rexpr, true, 1);
  4998. if( !dt.IsEqualExceptRefAndConst(rctx->type.dataType) )
  4999. {
  5000. asCString str;
  5001. str.Format(TXT_CANT_IMPLICITLY_CONVERT_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  5002. Error(str.AddressOf(), rexpr);
  5003. return -1;
  5004. }
  5005. }
  5006. else if( rctx->type.dataType.IsReference() && (!(rctx->type.isVariable || rctx->type.isTemporary) || IsVariableOnHeap(rctx->type.stackOffset)) )
  5007. rctx->bc.Instr(asBC_RDSPtr);
  5008. MergeExprBytecode(ctx, rctx);
  5009. MergeExprBytecode(ctx, lctx);
  5010. if( !simpleExpr )
  5011. {
  5012. if( (rctx->type.isVariable || rctx->type.isTemporary) && !IsVariableOnHeap(rctx->type.stackOffset) )
  5013. // TODO: optimize: Actually the reference can be pushed on the stack directly
  5014. // as the value allocated on the stack is guaranteed to be safe.
  5015. // The bytecode optimizer should be able to determine this and optimize away the VAR + GETREF
  5016. ctx->bc.InstrWORD(asBC_GETREF, AS_PTR_SIZE);
  5017. else
  5018. ctx->bc.InstrWORD(asBC_GETOBJREF, AS_PTR_SIZE);
  5019. }
  5020. PerformAssignment(&lctx->type, &rctx->type, &ctx->bc, opNode);
  5021. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  5022. ctx->type = lctx->type;
  5023. }
  5024. return 0;
  5025. }
  5026. int asCCompiler::CompileAssignment(asCScriptNode *expr, asSExprContext *ctx)
  5027. {
  5028. asCScriptNode *lexpr = expr->firstChild;
  5029. if( lexpr->next )
  5030. {
  5031. // Compile the two expression terms
  5032. asSExprContext lctx(engine), rctx(engine);
  5033. int rr = CompileAssignment(lexpr->next->next, &rctx);
  5034. int lr = CompileCondition(lexpr, &lctx);
  5035. if( lr >= 0 && rr >= 0 )
  5036. return DoAssignment(ctx, &lctx, &rctx, lexpr, lexpr->next->next, lexpr->next->tokenType, lexpr->next);
  5037. // Since the operands failed, the assignment was not computed
  5038. ctx->type.SetDummy();
  5039. return -1;
  5040. }
  5041. return CompileCondition(lexpr, ctx);
  5042. }
  5043. int asCCompiler::CompileCondition(asCScriptNode *expr, asSExprContext *ctx)
  5044. {
  5045. asCTypeInfo ctype;
  5046. // Compile the conditional expression
  5047. asCScriptNode *cexpr = expr->firstChild;
  5048. if( cexpr->next )
  5049. {
  5050. //-------------------------------
  5051. // Compile the condition
  5052. asSExprContext e(engine);
  5053. int r = CompileExpression(cexpr, &e);
  5054. if( r < 0 )
  5055. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  5056. if( r >= 0 && !e.type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  5057. {
  5058. Error(TXT_EXPR_MUST_BE_BOOL, cexpr);
  5059. e.type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  5060. }
  5061. ctype = e.type;
  5062. ProcessPropertyGetAccessor(&e, cexpr);
  5063. if( e.type.dataType.IsReference() ) ConvertToVariable(&e);
  5064. ProcessDeferredParams(&e);
  5065. //-------------------------------
  5066. // Compile the left expression
  5067. asSExprContext le(engine);
  5068. int lr = CompileAssignment(cexpr->next, &le);
  5069. //-------------------------------
  5070. // Compile the right expression
  5071. asSExprContext re(engine);
  5072. int rr = CompileAssignment(cexpr->next->next, &re);
  5073. if( lr >= 0 && rr >= 0 )
  5074. {
  5075. ProcessPropertyGetAccessor(&le, cexpr->next);
  5076. ProcessPropertyGetAccessor(&re, cexpr->next->next);
  5077. bool isExplicitHandle = le.type.isExplicitHandle || re.type.isExplicitHandle;
  5078. // Allow a 0 or null in the first case to be implicitly converted to the second type
  5079. if( le.type.isConstant && le.type.intValue == 0 && le.type.dataType.IsUnsignedType() )
  5080. {
  5081. asCDataType to = re.type.dataType;
  5082. to.MakeReference(false);
  5083. to.MakeReadOnly(true);
  5084. ImplicitConversionConstant(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  5085. }
  5086. else if( le.type.IsNullConstant() )
  5087. {
  5088. asCDataType to = re.type.dataType;
  5089. to.MakeHandle(true);
  5090. ImplicitConversion(&le, to, cexpr->next, asIC_IMPLICIT_CONV);
  5091. }
  5092. //---------------------------------
  5093. // Output the byte code
  5094. int afterLabel = nextLabel++;
  5095. int elseLabel = nextLabel++;
  5096. // If left expression is void, then we don't need to store the result
  5097. if( le.type.dataType.IsEqualExceptConst(asCDataType::CreatePrimitive(ttVoid, false)) )
  5098. {
  5099. // Put the code for the condition expression on the output
  5100. MergeExprBytecode(ctx, &e);
  5101. // Added the branch decision
  5102. ctx->type = e.type;
  5103. ConvertToVariable(ctx);
  5104. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  5105. ctx->bc.Instr(asBC_ClrHi);
  5106. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  5107. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  5108. // Add the left expression
  5109. MergeExprBytecode(ctx, &le);
  5110. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  5111. // Add the right expression
  5112. ctx->bc.Label((short)elseLabel);
  5113. MergeExprBytecode(ctx, &re);
  5114. ctx->bc.Label((short)afterLabel);
  5115. // Make sure both expressions have the same type
  5116. if( le.type.dataType != re.type.dataType )
  5117. Error(TXT_BOTH_MUST_BE_SAME, expr);
  5118. // Set the type of the result
  5119. ctx->type = le.type;
  5120. }
  5121. else
  5122. {
  5123. // Allocate temporary variable and copy the result to that one
  5124. asCTypeInfo temp;
  5125. temp = le.type;
  5126. temp.dataType.MakeReference(false);
  5127. temp.dataType.MakeReadOnly(false);
  5128. // Make sure the variable isn't used in the initial expression
  5129. int offset = AllocateVariableNotIn(temp.dataType, true, false, &e);
  5130. temp.SetVariable(temp.dataType, offset, true);
  5131. // TODO: copy: Use copy constructor if available. See PrepareTemporaryObject()
  5132. CallDefaultConstructor(temp.dataType, offset, IsVariableOnHeap(offset), &ctx->bc, expr);
  5133. // Put the code for the condition expression on the output
  5134. MergeExprBytecode(ctx, &e);
  5135. // Add the branch decision
  5136. ctx->type = e.type;
  5137. ConvertToVariable(ctx);
  5138. ctx->bc.InstrSHORT(asBC_CpyVtoR4, ctx->type.stackOffset);
  5139. ctx->bc.Instr(asBC_ClrHi);
  5140. ctx->bc.InstrDWORD(asBC_JZ, elseLabel);
  5141. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  5142. // Assign the result of the left expression to the temporary variable
  5143. asCTypeInfo rtemp;
  5144. rtemp = temp;
  5145. if( rtemp.dataType.IsObjectHandle() )
  5146. rtemp.isExplicitHandle = true;
  5147. PrepareForAssignment(&rtemp.dataType, &le, cexpr->next, true);
  5148. MergeExprBytecode(ctx, &le);
  5149. if( !rtemp.dataType.IsPrimitive() )
  5150. {
  5151. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5152. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  5153. }
  5154. PerformAssignment(&rtemp, &le.type, &ctx->bc, cexpr->next);
  5155. if( !rtemp.dataType.IsPrimitive() )
  5156. ctx->bc.Pop(le.type.dataType.GetSizeOnStackDWords()); // Pop the original value
  5157. // Release the old temporary variable
  5158. ReleaseTemporaryVariable(le.type, &ctx->bc);
  5159. ctx->bc.InstrINT(asBC_JMP, afterLabel);
  5160. // Start of the right expression
  5161. ctx->bc.Label((short)elseLabel);
  5162. // Copy the result to the same temporary variable
  5163. PrepareForAssignment(&rtemp.dataType, &re, cexpr->next, true);
  5164. MergeExprBytecode(ctx, &re);
  5165. if( !rtemp.dataType.IsPrimitive() )
  5166. {
  5167. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5168. rtemp.dataType.MakeReference(IsVariableOnHeap(offset));
  5169. }
  5170. PerformAssignment(&rtemp, &re.type, &ctx->bc, cexpr->next);
  5171. if( !rtemp.dataType.IsPrimitive() )
  5172. ctx->bc.Pop(le.type.dataType.GetSizeOnStackDWords()); // Pop the original value
  5173. // Release the old temporary variable
  5174. ReleaseTemporaryVariable(re.type, &ctx->bc);
  5175. ctx->bc.Label((short)afterLabel);
  5176. // Make sure both expressions have the same type
  5177. if( !le.type.dataType.IsEqualExceptConst(re.type.dataType) )
  5178. Error(TXT_BOTH_MUST_BE_SAME, expr);
  5179. // Set the temporary variable as output
  5180. ctx->type = rtemp;
  5181. ctx->type.isExplicitHandle = isExplicitHandle;
  5182. if( !ctx->type.dataType.IsPrimitive() )
  5183. {
  5184. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  5185. ctx->type.dataType.MakeReference(IsVariableOnHeap(offset));
  5186. }
  5187. // Make sure the output isn't marked as being a literal constant
  5188. ctx->type.isConstant = false;
  5189. }
  5190. }
  5191. else
  5192. {
  5193. ctx->type.SetDummy();
  5194. return -1;
  5195. }
  5196. }
  5197. else
  5198. return CompileExpression(cexpr, ctx);
  5199. return 0;
  5200. }
  5201. int asCCompiler::CompileExpression(asCScriptNode *expr, asSExprContext *ctx)
  5202. {
  5203. asASSERT(expr->nodeType == snExpression);
  5204. // Convert to polish post fix, i.e: a+b => ab+
  5205. // The algorithm that I've implemented here is similar to
  5206. // Djikstra's Shunting Yard algorithm, though I didn't know it at the time.
  5207. // ref: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
  5208. // Count the nodes in order to preallocate the buffers
  5209. int count = 0;
  5210. asCScriptNode *node = expr->firstChild;
  5211. while( node )
  5212. {
  5213. count++;
  5214. node = node->next;
  5215. }
  5216. asCArray<asCScriptNode *> stack(count);
  5217. asCArray<asCScriptNode *> stack2(count);
  5218. asCArray<asCScriptNode *> postfix(count);
  5219. node = expr->firstChild;
  5220. while( node )
  5221. {
  5222. int precedence = GetPrecedence(node);
  5223. while( stack.GetLength() > 0 &&
  5224. precedence <= GetPrecedence(stack[stack.GetLength()-1]) )
  5225. stack2.PushLast(stack.PopLast());
  5226. stack.PushLast(node);
  5227. node = node->next;
  5228. }
  5229. while( stack.GetLength() > 0 )
  5230. stack2.PushLast(stack.PopLast());
  5231. // We need to swap operands so that the left
  5232. // operand is always computed before the right
  5233. SwapPostFixOperands(stack2, postfix);
  5234. // Compile the postfix formatted expression
  5235. return CompilePostFixExpression(&postfix, ctx);
  5236. }
  5237. void asCCompiler::SwapPostFixOperands(asCArray<asCScriptNode *> &postfix, asCArray<asCScriptNode *> &target)
  5238. {
  5239. if( postfix.GetLength() == 0 ) return;
  5240. asCScriptNode *node = postfix.PopLast();
  5241. if( node->nodeType == snExprTerm )
  5242. {
  5243. target.PushLast(node);
  5244. return;
  5245. }
  5246. SwapPostFixOperands(postfix, target);
  5247. SwapPostFixOperands(postfix, target);
  5248. target.PushLast(node);
  5249. }
  5250. int asCCompiler::CompilePostFixExpression(asCArray<asCScriptNode *> *postfix, asSExprContext *ctx)
  5251. {
  5252. // Shouldn't send any byte code
  5253. asASSERT(ctx->bc.GetLastInstr() == -1);
  5254. // Set the context to a dummy type to avoid further
  5255. // errors in case the expression fails to compile
  5256. ctx->type.SetDummy();
  5257. // Pop the last node
  5258. asCScriptNode *node = postfix->PopLast();
  5259. ctx->exprNode = node;
  5260. // If term, compile the term
  5261. if( node->nodeType == snExprTerm )
  5262. return CompileExpressionTerm(node, ctx);
  5263. // Compile the two expression terms
  5264. asSExprContext r(engine), l(engine);
  5265. int ret;
  5266. ret = CompilePostFixExpression(postfix, &l); if( ret < 0 ) return ret;
  5267. ret = CompilePostFixExpression(postfix, &r); if( ret < 0 ) return ret;
  5268. // Compile the operation
  5269. return CompileOperator(node, &l, &r, ctx);
  5270. }
  5271. int asCCompiler::CompileExpressionTerm(asCScriptNode *node, asSExprContext *ctx)
  5272. {
  5273. // Shouldn't send any byte code
  5274. asASSERT(ctx->bc.GetLastInstr() == -1);
  5275. // Set the type as a dummy by default, in case of any compiler errors
  5276. ctx->type.SetDummy();
  5277. // Compile the value node
  5278. asCScriptNode *vnode = node->firstChild;
  5279. while( vnode->nodeType != snExprValue )
  5280. vnode = vnode->next;
  5281. asSExprContext v(engine);
  5282. int r = CompileExpressionValue(vnode, &v); if( r < 0 ) return r;
  5283. // Compile post fix operators
  5284. asCScriptNode *pnode = vnode->next;
  5285. while( pnode )
  5286. {
  5287. r = CompileExpressionPostOp(pnode, &v); if( r < 0 ) return r;
  5288. pnode = pnode->next;
  5289. }
  5290. // Compile pre fix operators
  5291. pnode = vnode->prev;
  5292. while( pnode )
  5293. {
  5294. r = CompileExpressionPreOp(pnode, &v); if( r < 0 ) return r;
  5295. pnode = pnode->prev;
  5296. }
  5297. // Return the byte code and final type description
  5298. MergeExprBytecodeAndType(ctx, &v);
  5299. return 0;
  5300. }
  5301. int asCCompiler::CompileVariableAccess(const asCString &name, const asCString &scope, asSExprContext *ctx, asCScriptNode *errNode, bool isOptional, bool noFunction, asCObjectType *objType)
  5302. {
  5303. bool found = false;
  5304. // It is a local variable or parameter?
  5305. // This is not accessible by default arg expressions
  5306. sVariable *v = 0;
  5307. if( !isCompilingDefaultArg && scope == "" && !objType )
  5308. v = variables->GetVariable(name.AddressOf());
  5309. if( v )
  5310. {
  5311. found = true;
  5312. if( v->isPureConstant )
  5313. ctx->type.SetConstantQW(v->type, v->constantValue);
  5314. else if( v->type.IsPrimitive() )
  5315. {
  5316. if( v->type.IsReference() )
  5317. {
  5318. // Copy the reference into the register
  5319. ctx->bc.InstrSHORT(asBC_PshVPtr, (short)v->stackOffset);
  5320. ctx->bc.Instr(asBC_PopRPtr);
  5321. ctx->type.Set(v->type);
  5322. }
  5323. else
  5324. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5325. ctx->type.isLValue = true;
  5326. }
  5327. else
  5328. {
  5329. ctx->bc.InstrSHORT(asBC_PSF, (short)v->stackOffset);
  5330. ctx->type.SetVariable(v->type, v->stackOffset, false);
  5331. // If the variable is allocated on the heap we have a reference,
  5332. // otherwise the actual object pointer is pushed on the stack.
  5333. if( v->onHeap || v->type.IsObjectHandle() ) ctx->type.dataType.MakeReference(true);
  5334. // Implicitly dereference handle parameters sent by reference
  5335. if( v->type.IsReference() && (!v->type.IsObject() || v->type.IsObjectHandle()) )
  5336. ctx->bc.Instr(asBC_RDSPtr);
  5337. ctx->type.isLValue = true;
  5338. }
  5339. }
  5340. // Is it a class member?
  5341. // This is not accessible by default arg expressions
  5342. if( !isCompilingDefaultArg && !found && ((objType) || (outFunc && outFunc->objectType && scope == "")) )
  5343. {
  5344. if( name == THIS_TOKEN && !objType )
  5345. {
  5346. asCDataType dt = asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly);
  5347. // The object pointer is located at stack position 0
  5348. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5349. ctx->type.SetVariable(dt, 0, false);
  5350. ctx->type.dataType.MakeReference(true);
  5351. ctx->type.isLValue = true;
  5352. found = true;
  5353. }
  5354. if( !found )
  5355. {
  5356. // See if there are any matching property accessors
  5357. asSExprContext access(engine);
  5358. if( objType )
  5359. access.type.Set(asCDataType::CreateObject(objType, false));
  5360. else
  5361. access.type.Set(asCDataType::CreateObject(outFunc->objectType, outFunc->isReadOnly));
  5362. access.type.dataType.MakeReference(true);
  5363. int r = 0;
  5364. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5365. {
  5366. // This is an index access, check if there is a property accessor that takes an index arg
  5367. asSExprContext dummyArg(engine);
  5368. r = FindPropertyAccessor(name, &access, &dummyArg, errNode, true);
  5369. }
  5370. if( r == 0 )
  5371. {
  5372. // Normal property access
  5373. r = FindPropertyAccessor(name, &access, errNode, true);
  5374. }
  5375. if( r < 0 ) return -1;
  5376. if( access.property_get || access.property_set )
  5377. {
  5378. if( !objType )
  5379. {
  5380. // Prepare the bytecode for the member access
  5381. // This is only done when accessing through the implicit this pointer
  5382. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5383. }
  5384. MergeExprBytecodeAndType(ctx, &access);
  5385. found = true;
  5386. }
  5387. }
  5388. if( !found )
  5389. {
  5390. asCDataType dt;
  5391. if( objType )
  5392. dt = asCDataType::CreateObject(objType, false);
  5393. else
  5394. dt = asCDataType::CreateObject(outFunc->objectType, false);
  5395. asCObjectProperty *prop = builder->GetObjectProperty(dt, name.AddressOf());
  5396. if( prop )
  5397. {
  5398. if( !objType )
  5399. {
  5400. // The object pointer is located at stack position 0
  5401. // This is only done when accessing through the implicit this pointer
  5402. ctx->bc.InstrSHORT(asBC_PSF, 0);
  5403. ctx->type.SetVariable(dt, 0, false);
  5404. ctx->type.dataType.MakeReference(true);
  5405. Dereference(ctx, true);
  5406. }
  5407. // TODO: This is the same as what is in CompileExpressionPostOp
  5408. // Put the offset on the stack
  5409. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(dt));
  5410. if( prop->type.IsReference() )
  5411. ctx->bc.Instr(asBC_RDSPtr);
  5412. // Reference to primitive must be stored in the temp register
  5413. if( prop->type.IsPrimitive() )
  5414. {
  5415. // TODO: optimize: The ADD offset command should store the reference in the register directly
  5416. ctx->bc.Instr(asBC_PopRPtr);
  5417. }
  5418. // Set the new type (keeping info about temp variable)
  5419. ctx->type.dataType = prop->type;
  5420. ctx->type.dataType.MakeReference(true);
  5421. ctx->type.isVariable = false;
  5422. ctx->type.isLValue = true;
  5423. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  5424. {
  5425. // Objects that are members are not references
  5426. ctx->type.dataType.MakeReference(false);
  5427. }
  5428. // If the object reference is const, the property will also be const
  5429. ctx->type.dataType.MakeReadOnly(outFunc->isReadOnly);
  5430. found = true;
  5431. }
  5432. }
  5433. }
  5434. // Is it a global property?
  5435. if( !found && !objType )
  5436. {
  5437. // See if there are any matching global property accessors
  5438. // TODO: namespace: Support namespaces for global property accessors too
  5439. asSExprContext access(engine);
  5440. int r = 0;
  5441. if( errNode->next && errNode->next->tokenType == ttOpenBracket )
  5442. {
  5443. // This is an index access, check if there is a property accessor that takes an index arg
  5444. asSExprContext dummyArg(engine);
  5445. r = FindPropertyAccessor(name, &access, &dummyArg, errNode);
  5446. }
  5447. if( r == 0 )
  5448. {
  5449. // Normal property access
  5450. r = FindPropertyAccessor(name, &access, errNode);
  5451. }
  5452. if( r < 0 ) return -1;
  5453. if( access.property_get || access.property_set )
  5454. {
  5455. // Prepare the bytecode for the function call
  5456. MergeExprBytecodeAndType(ctx, &access);
  5457. found = true;
  5458. }
  5459. // See if there is any matching global property
  5460. if( !found )
  5461. {
  5462. bool isCompiled = true;
  5463. bool isPureConstant = false;
  5464. bool isAppProp = false;
  5465. asQWORD constantValue;
  5466. asCString ns = scope == "::" ? "" : scope;
  5467. if( ns == "" )
  5468. {
  5469. if( outFunc->nameSpace != "" )
  5470. ns = outFunc->nameSpace;
  5471. else if( outFunc->objectType && outFunc->objectType->nameSpace != "" )
  5472. ns = outFunc->objectType->nameSpace;
  5473. }
  5474. asCGlobalProperty *prop = builder->GetGlobalProperty(name.AddressOf(), ns, &isCompiled, &isPureConstant, &constantValue, &isAppProp);
  5475. if( prop )
  5476. {
  5477. found = true;
  5478. // Verify that the global property has been compiled already
  5479. if( isCompiled )
  5480. {
  5481. if( ctx->type.dataType.GetObjectType() && (ctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE) )
  5482. {
  5483. ctx->type.dataType.MakeHandle(true);
  5484. ctx->type.isExplicitHandle = true;
  5485. }
  5486. // If the global property is a pure constant
  5487. // we can allow the compiler to optimize it. Pure
  5488. // constants are global constant variables that were
  5489. // initialized by literal constants.
  5490. if( isPureConstant )
  5491. ctx->type.SetConstantQW(prop->type, constantValue);
  5492. else
  5493. {
  5494. // A shared type must not access global vars, unless they
  5495. // too are shared, e.g. application registered vars
  5496. if( outFunc->IsShared() )
  5497. {
  5498. if( !isAppProp )
  5499. {
  5500. asCString str;
  5501. str.Format(TXT_SHARED_CANNOT_ACCESS_NON_SHARED_VAR_s, prop->name.AddressOf());
  5502. Error(str.AddressOf(), errNode);
  5503. // Allow the compilation to continue to catch other problems
  5504. }
  5505. }
  5506. ctx->type.Set(prop->type);
  5507. ctx->type.dataType.MakeReference(true);
  5508. ctx->type.isLValue = true;
  5509. if( ctx->type.dataType.IsPrimitive() )
  5510. {
  5511. // Load the address of the variable into the register
  5512. ctx->bc.InstrPTR(asBC_LDG, prop->GetAddressOfValue());
  5513. }
  5514. else
  5515. {
  5516. // Push the address of the variable on the stack
  5517. ctx->bc.InstrPTR(asBC_PGA, prop->GetAddressOfValue());
  5518. // If the object is a value type, then we must validate the existance,
  5519. // as it could potentially be accessed before it is initialized.
  5520. if( ctx->type.dataType.GetObjectType()->flags & asOBJ_VALUE ||
  5521. !ctx->type.dataType.IsObjectHandle() )
  5522. {
  5523. // TODO: optimize: This is not necessary for application registered properties
  5524. ctx->bc.Instr(asBC_ChkRefS);
  5525. }
  5526. }
  5527. }
  5528. }
  5529. else
  5530. {
  5531. asCString str;
  5532. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, prop->name.AddressOf());
  5533. Error(str.AddressOf(), errNode);
  5534. return -1;
  5535. }
  5536. }
  5537. }
  5538. }
  5539. // Is it the name of a global function?
  5540. if( !noFunction && !found && !objType )
  5541. {
  5542. asCArray<int> funcs;
  5543. asCString ns = scope == "::" ? "" : scope;
  5544. if( ns == "" )
  5545. {
  5546. if( outFunc->nameSpace != "" )
  5547. ns = outFunc->nameSpace;
  5548. else if( outFunc->objectType && outFunc->objectType->nameSpace != "" )
  5549. ns = outFunc->objectType->nameSpace;
  5550. }
  5551. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  5552. if( funcs.GetLength() > 1 )
  5553. {
  5554. // TODO: funcdef: If multiple functions are found, then the compiler should defer the decision
  5555. // to which one it should use until the value is actually used.
  5556. //
  5557. // - assigning the function pointer to a variable
  5558. // - performing an explicit cast
  5559. // - passing the function pointer to a function as parameter
  5560. asCString str;
  5561. str.Format(TXT_MULTIPLE_MATCHING_SIGNATURES_TO_s, name.AddressOf());
  5562. Error(str.AddressOf(), errNode);
  5563. return -1;
  5564. }
  5565. else if( funcs.GetLength() == 1 )
  5566. {
  5567. found = true;
  5568. // A shared object may not access global functions unless they too are shared (e.g. registered functions)
  5569. if( !builder->GetFunctionDescription(funcs[0])->IsShared() &&
  5570. outFunc->IsShared() )
  5571. {
  5572. asCString msg;
  5573. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, builder->GetFunctionDescription(funcs[0])->GetDeclaration());
  5574. Error(msg.AddressOf(), errNode);
  5575. return -1;
  5576. }
  5577. // Push the function pointer on the stack
  5578. ctx->bc.InstrPTR(asBC_FuncPtr, builder->GetFunctionDescription(funcs[0]));
  5579. ctx->type.Set(asCDataType::CreateFuncDef(builder->GetFunctionDescription(funcs[0])));
  5580. }
  5581. }
  5582. // Is it an enum value?
  5583. if( !found && !objType )
  5584. {
  5585. // The enum type may be declared in a namespace too
  5586. asCObjectType *scopeType = 0;
  5587. if( scope != "" && scope != "::" )
  5588. {
  5589. // Use the last scope name as the enum type
  5590. asCString enumType = scope;
  5591. asCString ns;
  5592. int p = scope.FindLast("::");
  5593. if( p != -1 )
  5594. {
  5595. enumType = scope.SubString(p+2);
  5596. ns = scope.SubString(0, p);
  5597. }
  5598. // resolve the type before the scope
  5599. scopeType = builder->GetObjectType(enumType.AddressOf(), ns);
  5600. }
  5601. asDWORD value = 0;
  5602. asCDataType dt;
  5603. if( scopeType && builder->GetEnumValueFromObjectType(scopeType, name.AddressOf(), dt, value) )
  5604. {
  5605. // scoped enum value found
  5606. found = true;
  5607. }
  5608. else if( !engine->ep.requireEnumScope )
  5609. {
  5610. // Look for the enum value without explicitly informing the enum type
  5611. asCString ns = scope == "::" ? "" : scope;
  5612. if( ns == "" )
  5613. {
  5614. // Use implicit scope from the current function that is being compiled
  5615. // TODO: cleanup: This is repeated in a lot of places. Should use function for it
  5616. if( outFunc->nameSpace != "" )
  5617. ns = outFunc->nameSpace;
  5618. else if( outFunc->objectType && outFunc->objectType->nameSpace != "" )
  5619. ns = outFunc->objectType->nameSpace;
  5620. }
  5621. int e = builder->GetEnumValue(name.AddressOf(), dt, value, ns);
  5622. if( e )
  5623. {
  5624. found = true;
  5625. if( e == 2 )
  5626. {
  5627. Error(TXT_FOUND_MULTIPLE_ENUM_VALUES, errNode);
  5628. }
  5629. }
  5630. }
  5631. if( found )
  5632. {
  5633. // Even if the enum type is not shared, and we're compiling a shared object,
  5634. // the use of the values are still allowed, since they are treated as constants.
  5635. // an enum value was resolved
  5636. ctx->type.SetConstantDW(dt, value);
  5637. }
  5638. }
  5639. // The name doesn't match any variable
  5640. if( !found )
  5641. {
  5642. // Give dummy value
  5643. ctx->type.SetDummy();
  5644. if( !isOptional )
  5645. {
  5646. // Prepend the scope to the name for the error message
  5647. asCString ename;
  5648. if( scope != "" && scope != "::" )
  5649. ename = scope + "::";
  5650. else
  5651. ename = scope;
  5652. ename += name;
  5653. asCString str;
  5654. str.Format(TXT_s_NOT_DECLARED, ename.AddressOf());
  5655. Error(str.AddressOf(), errNode);
  5656. // Declare the variable now so that it will not be reported again
  5657. variables->DeclareVariable(name.AddressOf(), asCDataType::CreatePrimitive(ttInt, false), 0x7FFF, true);
  5658. // Mark the variable as initialized so that the user will not be bother by it again
  5659. sVariable *v = variables->GetVariable(name.AddressOf());
  5660. asASSERT(v);
  5661. if( v ) v->isInitialized = true;
  5662. }
  5663. // Return -1 to signal that the variable wasn't found
  5664. return -1;
  5665. }
  5666. return 0;
  5667. }
  5668. int asCCompiler::CompileExpressionValue(asCScriptNode *node, asSExprContext *ctx)
  5669. {
  5670. // Shouldn't receive any byte code
  5671. asASSERT(ctx->bc.GetLastInstr() == -1);
  5672. asCScriptNode *vnode = node->firstChild;
  5673. ctx->exprNode = vnode;
  5674. if( vnode->nodeType == snVariableAccess )
  5675. {
  5676. // Determine the scope resolution of the variable
  5677. asCString scope = builder->GetScopeFromNode(vnode->firstChild, script, &vnode);
  5678. // Determine the name of the variable
  5679. asASSERT(vnode->nodeType == snIdentifier );
  5680. asCString name(&script->code[vnode->tokenPos], vnode->tokenLength);
  5681. return CompileVariableAccess(name, scope, ctx, node);
  5682. }
  5683. else if( vnode->nodeType == snConstant )
  5684. {
  5685. if( vnode->tokenType == ttIntConstant )
  5686. {
  5687. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5688. asQWORD val = asStringScanUInt64(value.AddressOf(), 10, 0);
  5689. // Do we need 64 bits?
  5690. if( val>>32 )
  5691. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  5692. else
  5693. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  5694. }
  5695. else if( vnode->tokenType == ttBitsConstant )
  5696. {
  5697. asCString value(&script->code[vnode->tokenPos+2], vnode->tokenLength-2);
  5698. // TODO: Check for overflow
  5699. asQWORD val = asStringScanUInt64(value.AddressOf(), 16, 0);
  5700. // Do we need 64 bits?
  5701. if( val>>32 )
  5702. ctx->type.SetConstantQW(asCDataType::CreatePrimitive(ttUInt64, true), val);
  5703. else
  5704. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), asDWORD(val));
  5705. }
  5706. else if( vnode->tokenType == ttFloatConstant )
  5707. {
  5708. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5709. // TODO: Check for overflow
  5710. size_t numScanned;
  5711. float v = float(asStringScanDouble(value.AddressOf(), &numScanned));
  5712. ctx->type.SetConstantF(asCDataType::CreatePrimitive(ttFloat, true), v);
  5713. #ifndef AS_USE_DOUBLE_AS_FLOAT
  5714. // Don't check this if we have double as float, because then the whole token would be scanned (i.e. no f suffix)
  5715. asASSERT(numScanned == vnode->tokenLength - 1);
  5716. #endif
  5717. }
  5718. else if( vnode->tokenType == ttDoubleConstant )
  5719. {
  5720. asCString value(&script->code[vnode->tokenPos], vnode->tokenLength);
  5721. // TODO: Check for overflow
  5722. size_t numScanned;
  5723. double v = asStringScanDouble(value.AddressOf(), &numScanned);
  5724. ctx->type.SetConstantD(asCDataType::CreatePrimitive(ttDouble, true), v);
  5725. asASSERT(numScanned == vnode->tokenLength);
  5726. }
  5727. else if( vnode->tokenType == ttTrue ||
  5728. vnode->tokenType == ttFalse )
  5729. {
  5730. #if AS_SIZEOF_BOOL == 1
  5731. ctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  5732. #else
  5733. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), vnode->tokenType == ttTrue ? VALUE_OF_BOOLEAN_TRUE : 0);
  5734. #endif
  5735. }
  5736. else if( vnode->tokenType == ttStringConstant ||
  5737. vnode->tokenType == ttMultilineStringConstant ||
  5738. vnode->tokenType == ttHeredocStringConstant )
  5739. {
  5740. asCString str;
  5741. asCScriptNode *snode = vnode->firstChild;
  5742. if( script->code[snode->tokenPos] == '\'' && engine->ep.useCharacterLiterals )
  5743. {
  5744. // Treat the single quoted string as a single character literal
  5745. str.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5746. asDWORD val = 0;
  5747. if( str.GetLength() && (unsigned char)str[0] > 127 && engine->ep.scanner == 1 )
  5748. {
  5749. // This is the start of a UTF8 encoded character. We need to decode it
  5750. val = asStringDecodeUTF8(str.AddressOf(), 0);
  5751. if( val == (asDWORD)-1 )
  5752. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  5753. }
  5754. else
  5755. {
  5756. val = ProcessStringConstant(str, snode);
  5757. if( val == (asDWORD)-1 )
  5758. Error(TXT_INVALID_CHAR_LITERAL, vnode);
  5759. }
  5760. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttUInt, true), val);
  5761. }
  5762. else
  5763. {
  5764. // Process the string constants
  5765. while( snode )
  5766. {
  5767. asCString cat;
  5768. if( snode->tokenType == ttStringConstant )
  5769. {
  5770. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5771. ProcessStringConstant(cat, snode);
  5772. }
  5773. else if( snode->tokenType == ttMultilineStringConstant )
  5774. {
  5775. if( !engine->ep.allowMultilineStrings )
  5776. Error(TXT_MULTILINE_STRINGS_NOT_ALLOWED, snode);
  5777. cat.Assign(&script->code[snode->tokenPos+1], snode->tokenLength-2);
  5778. ProcessStringConstant(cat, snode);
  5779. }
  5780. else if( snode->tokenType == ttHeredocStringConstant )
  5781. {
  5782. cat.Assign(&script->code[snode->tokenPos+3], snode->tokenLength-6);
  5783. ProcessHeredocStringConstant(cat, snode);
  5784. }
  5785. str += cat;
  5786. snode = snode->next;
  5787. }
  5788. // Call the string factory function to create a string object
  5789. asCScriptFunction *descr = engine->stringFactory;
  5790. if( descr == 0 )
  5791. {
  5792. // Error
  5793. Error(TXT_STRINGS_NOT_RECOGNIZED, vnode);
  5794. // Give dummy value
  5795. ctx->type.SetDummy();
  5796. return -1;
  5797. }
  5798. else
  5799. {
  5800. // Register the constant string with the engine
  5801. int id = engine->AddConstantString(str.AddressOf(), str.GetLength());
  5802. ctx->bc.InstrWORD(asBC_STR, (asWORD)id);
  5803. bool useVariable = false;
  5804. int stackOffset = 0;
  5805. if( descr->DoesReturnOnStack() )
  5806. {
  5807. useVariable = true;
  5808. stackOffset = AllocateVariable(descr->returnType, true);
  5809. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  5810. }
  5811. PerformFunctionCall(descr->id, ctx, false, 0, 0, useVariable, stackOffset);
  5812. }
  5813. }
  5814. }
  5815. else if( vnode->tokenType == ttNull )
  5816. {
  5817. ctx->bc.Instr(asBC_PshNull);
  5818. ctx->type.SetNullConstant();
  5819. }
  5820. else
  5821. asASSERT(false);
  5822. }
  5823. else if( vnode->nodeType == snFunctionCall )
  5824. {
  5825. // Determine the scope resolution
  5826. asCString scope = builder->GetScopeFromNode(vnode->firstChild, script);
  5827. return CompileFunctionCall(vnode, ctx, 0, false, scope);
  5828. }
  5829. else if( vnode->nodeType == snConstructCall )
  5830. {
  5831. CompileConstructCall(vnode, ctx);
  5832. }
  5833. else if( vnode->nodeType == snAssignment )
  5834. {
  5835. asSExprContext e(engine);
  5836. int r = CompileAssignment(vnode, &e);
  5837. if( r < 0 )
  5838. {
  5839. ctx->type.SetDummy();
  5840. return r;
  5841. }
  5842. MergeExprBytecodeAndType(ctx, &e);
  5843. }
  5844. else if( vnode->nodeType == snCast )
  5845. {
  5846. // Implement the cast operator
  5847. CompileConversion(vnode, ctx);
  5848. }
  5849. else
  5850. asASSERT(false);
  5851. return 0;
  5852. }
  5853. asUINT asCCompiler::ProcessStringConstant(asCString &cstr, asCScriptNode *node, bool processEscapeSequences)
  5854. {
  5855. int charLiteral = -1;
  5856. // Process escape sequences
  5857. asCArray<char> str((int)cstr.GetLength());
  5858. for( asUINT n = 0; n < cstr.GetLength(); n++ )
  5859. {
  5860. #ifdef AS_DOUBLEBYTE_CHARSET
  5861. // Double-byte charset is only allowed for ASCII and not UTF16 encoded strings
  5862. if( (cstr[n] & 0x80) && engine->ep.scanner == 0 && engine->ep.stringEncoding != 1 )
  5863. {
  5864. // This is the lead character of a double byte character
  5865. // include the trail character without checking it's value.
  5866. str.PushLast(cstr[n]);
  5867. n++;
  5868. str.PushLast(cstr[n]);
  5869. continue;
  5870. }
  5871. #endif
  5872. asUINT val;
  5873. if( processEscapeSequences && cstr[n] == '\\' )
  5874. {
  5875. ++n;
  5876. if( n == cstr.GetLength() )
  5877. {
  5878. if( charLiteral == -1 ) charLiteral = 0;
  5879. return charLiteral;
  5880. }
  5881. // Hexadecimal escape sequences will allow the construction of
  5882. // invalid unicode sequences, but the string should also work as
  5883. // a bytearray so we must support this. The code for working with
  5884. // unicode text must be prepared to handle invalid unicode sequences
  5885. if( cstr[n] == 'x' || cstr[n] == 'X' )
  5886. {
  5887. ++n;
  5888. if( n == cstr.GetLength() ) break;
  5889. val = 0;
  5890. int c = engine->ep.stringEncoding == 1 ? 4 : 2;
  5891. for( ; c > 0 && n < cstr.GetLength(); c--, n++ )
  5892. {
  5893. if( cstr[n] >= '0' && cstr[n] <= '9' )
  5894. val = val*16 + cstr[n] - '0';
  5895. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  5896. val = val*16 + cstr[n] - 'a' + 10;
  5897. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  5898. val = val*16 + cstr[n] - 'A' + 10;
  5899. else
  5900. break;
  5901. }
  5902. // Rewind one, since the loop will increment it again
  5903. n--;
  5904. // Hexadecimal escape sequences produce exact value, even if it is not proper unicode chars
  5905. if( engine->ep.stringEncoding == 0 )
  5906. {
  5907. str.PushLast((asBYTE)val);
  5908. }
  5909. else
  5910. {
  5911. #ifndef AS_BIG_ENDIAN
  5912. str.PushLast((asBYTE)val);
  5913. str.PushLast((asBYTE)(val>>8));
  5914. #else
  5915. str.PushLast((asBYTE)(val>>8));
  5916. str.PushLast((asBYTE)val);
  5917. #endif
  5918. }
  5919. if( charLiteral == -1 ) charLiteral = val;
  5920. continue;
  5921. }
  5922. else if( cstr[n] == 'u' || cstr[n] == 'U' )
  5923. {
  5924. // \u expects 4 hex digits
  5925. // \U expects 8 hex digits
  5926. bool expect2 = cstr[n] == 'u';
  5927. int c = expect2 ? 4 : 8;
  5928. val = 0;
  5929. for( ; c > 0; c-- )
  5930. {
  5931. ++n;
  5932. if( n == cstr.GetLength() ) break;
  5933. if( cstr[n] >= '0' && cstr[n] <= '9' )
  5934. val = val*16 + cstr[n] - '0';
  5935. else if( cstr[n] >= 'a' && cstr[n] <= 'f' )
  5936. val = val*16 + cstr[n] - 'a' + 10;
  5937. else if( cstr[n] >= 'A' && cstr[n] <= 'F' )
  5938. val = val*16 + cstr[n] - 'A' + 10;
  5939. else
  5940. break;
  5941. }
  5942. if( c != 0 )
  5943. {
  5944. // Give warning about invalid code point
  5945. // TODO: Need code position for warning
  5946. asCString msg;
  5947. msg.Format(TXT_INVALID_UNICODE_FORMAT_EXPECTED_d, expect2 ? 4 : 8);
  5948. Warning(msg.AddressOf(), node);
  5949. continue;
  5950. }
  5951. }
  5952. else
  5953. {
  5954. if( cstr[n] == '"' )
  5955. val = '"';
  5956. else if( cstr[n] == '\'' )
  5957. val = '\'';
  5958. else if( cstr[n] == 'n' )
  5959. val = '\n';
  5960. else if( cstr[n] == 'r' )
  5961. val = '\r';
  5962. else if( cstr[n] == 't' )
  5963. val = '\t';
  5964. else if( cstr[n] == '0' )
  5965. val = '\0';
  5966. else if( cstr[n] == '\\' )
  5967. val = '\\';
  5968. else
  5969. {
  5970. // Invalid escape sequence
  5971. Warning(TXT_INVALID_ESCAPE_SEQUENCE, node);
  5972. continue;
  5973. }
  5974. }
  5975. }
  5976. else
  5977. {
  5978. if( engine->ep.scanner == 1 && (cstr[n] & 0x80) )
  5979. {
  5980. unsigned int len;
  5981. val = asStringDecodeUTF8(&cstr[n], &len);
  5982. if( val == 0xFFFFFFFF )
  5983. {
  5984. // Incorrect UTF8 encoding. Use only the first byte
  5985. // TODO: Need code position for warning
  5986. Warning(TXT_INVALID_UNICODE_SEQUENCE_IN_SRC, node);
  5987. val = (unsigned char)cstr[n];
  5988. }
  5989. else
  5990. n += len-1;
  5991. }
  5992. else
  5993. val = (unsigned char)cstr[n];
  5994. }
  5995. // Add the character to the final string
  5996. char encodedValue[5];
  5997. int len;
  5998. if( engine->ep.scanner == 1 && engine->ep.stringEncoding == 0 )
  5999. {
  6000. // Convert to UTF8 encoded
  6001. len = asStringEncodeUTF8(val, encodedValue);
  6002. }
  6003. else if( engine->ep.stringEncoding == 1 )
  6004. {
  6005. // Convert to 16bit wide character string (even if the script is scanned as ASCII)
  6006. len = asStringEncodeUTF16(val, encodedValue);
  6007. }
  6008. else
  6009. {
  6010. // Do not convert ASCII characters
  6011. encodedValue[0] = (asBYTE)val;
  6012. len = 1;
  6013. }
  6014. if( len < 0 )
  6015. {
  6016. // Give warning about invalid code point
  6017. // TODO: Need code position for warning
  6018. Warning(TXT_INVALID_UNICODE_VALUE, node);
  6019. }
  6020. else
  6021. {
  6022. // Add the encoded value to the final string
  6023. str.Concatenate(encodedValue, len);
  6024. if( charLiteral == -1 ) charLiteral = val;
  6025. }
  6026. }
  6027. cstr.Assign(str.AddressOf(), str.GetLength());
  6028. return charLiteral;
  6029. }
  6030. void asCCompiler::ProcessHeredocStringConstant(asCString &str, asCScriptNode *node)
  6031. {
  6032. // Remove first line if it only contains whitespace
  6033. int start;
  6034. for( start = 0; start < (int)str.GetLength(); start++ )
  6035. {
  6036. if( str[start] == '\n' )
  6037. {
  6038. // Remove the linebreak as well
  6039. start++;
  6040. break;
  6041. }
  6042. if( str[start] != ' ' &&
  6043. str[start] != '\t' &&
  6044. str[start] != '\r' )
  6045. {
  6046. // Don't remove anything
  6047. start = 0;
  6048. break;
  6049. }
  6050. }
  6051. // Remove last line break and the line after that if it only contains whitespaces
  6052. int end;
  6053. for( end = (int)str.GetLength() - 1; end >= 0; end-- )
  6054. {
  6055. if( str[end] == '\n' )
  6056. break;
  6057. if( str[end] != ' ' &&
  6058. str[end] != '\t' &&
  6059. str[end] != '\r' )
  6060. {
  6061. // Don't remove anything
  6062. end = (int)str.GetLength();
  6063. break;
  6064. }
  6065. }
  6066. if( end < 0 ) end = 0;
  6067. asCString tmp;
  6068. if( end > start )
  6069. tmp.Assign(&str[start], end-start);
  6070. ProcessStringConstant(tmp, node, false);
  6071. str = tmp;
  6072. }
  6073. void asCCompiler::CompileConversion(asCScriptNode *node, asSExprContext *ctx)
  6074. {
  6075. asSExprContext expr(engine);
  6076. asCDataType to;
  6077. bool anyErrors = false;
  6078. EImplicitConv convType;
  6079. if( node->nodeType == snConstructCall )
  6080. {
  6081. convType = asIC_EXPLICIT_VAL_CAST;
  6082. // Verify that there is only one argument
  6083. if( node->lastChild->firstChild == 0 ||
  6084. node->lastChild->firstChild != node->lastChild->lastChild )
  6085. {
  6086. Error(TXT_ONLY_ONE_ARGUMENT_IN_CAST, node->lastChild);
  6087. expr.type.SetDummy();
  6088. anyErrors = true;
  6089. }
  6090. else
  6091. {
  6092. // Compile the expression
  6093. int r = CompileAssignment(node->lastChild->firstChild, &expr);
  6094. if( r < 0 )
  6095. anyErrors = true;
  6096. }
  6097. // Determine the requested type
  6098. // TODO: namespace: Use correct implicit namespace from function
  6099. to = builder->CreateDataTypeFromNode(node->firstChild, script, "");
  6100. to.MakeReadOnly(true); // Default to const
  6101. asASSERT(to.IsPrimitive());
  6102. }
  6103. else
  6104. {
  6105. convType = asIC_EXPLICIT_REF_CAST;
  6106. // Compile the expression
  6107. int r = CompileAssignment(node->lastChild, &expr);
  6108. if( r < 0 )
  6109. anyErrors = true;
  6110. // Determine the requested type
  6111. // TODO: namespace: Use correct implicit namespace from function
  6112. to = builder->CreateDataTypeFromNode(node->firstChild, script, "");
  6113. to = builder->ModifyDataTypeFromNode(to, node->firstChild->next, script, 0, 0);
  6114. // If the type support object handles, then use it
  6115. if( to.SupportHandles() )
  6116. {
  6117. to.MakeHandle(true);
  6118. }
  6119. else if( !to.IsObjectHandle() )
  6120. {
  6121. // The cast<type> operator can only be used for reference casts
  6122. Error(TXT_ILLEGAL_TARGET_TYPE_FOR_REF_CAST, node->firstChild);
  6123. anyErrors = true;
  6124. }
  6125. }
  6126. // Do not allow casting to non shared type if we're compiling a shared method
  6127. if( outFunc->IsShared() &&
  6128. to.GetObjectType() && !to.GetObjectType()->IsShared() )
  6129. {
  6130. asCString msg;
  6131. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, to.GetObjectType()->name.AddressOf());
  6132. Error(msg.AddressOf(), node);
  6133. anyErrors = true;
  6134. }
  6135. if( anyErrors )
  6136. {
  6137. // Assume that the error can be fixed and allow the compilation to continue
  6138. ctx->type.SetConstantDW(to, 0);
  6139. return;
  6140. }
  6141. ProcessPropertyGetAccessor(&expr, node);
  6142. // We don't want a reference
  6143. if( expr.type.dataType.IsReference() )
  6144. {
  6145. if( expr.type.dataType.IsObject() )
  6146. Dereference(&expr, true);
  6147. else
  6148. ConvertToVariable(&expr);
  6149. }
  6150. ImplicitConversion(&expr, to, node, convType);
  6151. IsVariableInitialized(&expr.type, node);
  6152. // If no type conversion is really tried ignore it
  6153. if( to == expr.type.dataType )
  6154. {
  6155. // This will keep information about constant type
  6156. MergeExprBytecode(ctx, &expr);
  6157. ctx->type = expr.type;
  6158. return;
  6159. }
  6160. if( to.IsEqualExceptConst(expr.type.dataType) && to.IsPrimitive() )
  6161. {
  6162. MergeExprBytecode(ctx, &expr);
  6163. ctx->type = expr.type;
  6164. ctx->type.dataType.MakeReadOnly(true);
  6165. return;
  6166. }
  6167. // The implicit conversion already does most of the conversions permitted,
  6168. // here we'll only treat those conversions that require an explicit cast.
  6169. bool conversionOK = false;
  6170. if( !expr.type.isConstant )
  6171. {
  6172. if( !expr.type.dataType.IsObject() )
  6173. ConvertToTempVariable(&expr);
  6174. if( to.IsObjectHandle() &&
  6175. expr.type.dataType.IsObjectHandle() &&
  6176. !(!to.IsHandleToConst() && expr.type.dataType.IsHandleToConst()) )
  6177. {
  6178. conversionOK = CompileRefCast(&expr, to, true, node);
  6179. MergeExprBytecode(ctx, &expr);
  6180. ctx->type = expr.type;
  6181. }
  6182. }
  6183. if( conversionOK )
  6184. return;
  6185. // Conversion not available
  6186. ctx->type.SetDummy();
  6187. asCString strTo, strFrom;
  6188. strTo = to.Format();
  6189. strFrom = expr.type.dataType.Format();
  6190. asCString msg;
  6191. msg.Format(TXT_NO_CONVERSION_s_TO_s, strFrom.AddressOf(), strTo.AddressOf());
  6192. Error(msg.AddressOf(), node);
  6193. }
  6194. void asCCompiler::AfterFunctionCall(int funcID, asCArray<asSExprContext*> &args, asSExprContext *ctx, bool deferAll)
  6195. {
  6196. asCScriptFunction *descr = builder->GetFunctionDescription(funcID);
  6197. // Parameters that are sent by reference should be assigned
  6198. // to the evaluated expression if it is an lvalue
  6199. // Evaluate the arguments from last to first
  6200. int n = (int)descr->parameterTypes.GetLength() - 1;
  6201. for( ; n >= 0; n-- )
  6202. {
  6203. if( (descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] & asTM_OUTREF)) ||
  6204. (descr->parameterTypes[n].IsObject() && deferAll) )
  6205. {
  6206. asASSERT( !(descr->parameterTypes[n].IsReference() && (descr->inOutFlags[n] == asTM_OUTREF)) || args[n]->origExpr );
  6207. // For &inout, only store the argument if it is for a temporary variable
  6208. if( engine->ep.allowUnsafeReferences ||
  6209. descr->inOutFlags[n] != asTM_INOUTREF || args[n]->type.isTemporary )
  6210. {
  6211. // Store the argument for later processing
  6212. asSDeferredParam outParam;
  6213. outParam.argNode = args[n]->exprNode;
  6214. outParam.argType = args[n]->type;
  6215. outParam.argInOutFlags = descr->inOutFlags[n];
  6216. outParam.origExpr = args[n]->origExpr;
  6217. ctx->deferredParams.PushLast(outParam);
  6218. }
  6219. }
  6220. else
  6221. {
  6222. // Release the temporary variable now
  6223. ReleaseTemporaryVariable(args[n]->type, &ctx->bc);
  6224. }
  6225. // Move the argument's deferred expressions over to the final expression
  6226. for( asUINT m = 0; m < args[n]->deferredParams.GetLength(); m++ )
  6227. {
  6228. ctx->deferredParams.PushLast(args[n]->deferredParams[m]);
  6229. args[n]->deferredParams[m].origExpr = 0;
  6230. }
  6231. args[n]->deferredParams.SetLength(0);
  6232. }
  6233. }
  6234. void asCCompiler::ProcessDeferredParams(asSExprContext *ctx)
  6235. {
  6236. if( isProcessingDeferredParams ) return;
  6237. isProcessingDeferredParams = true;
  6238. for( asUINT n = 0; n < ctx->deferredParams.GetLength(); n++ )
  6239. {
  6240. asSDeferredParam outParam = ctx->deferredParams[n];
  6241. if( outParam.argInOutFlags < asTM_OUTREF ) // &in, or not reference
  6242. {
  6243. // Just release the variable
  6244. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6245. }
  6246. else if( outParam.argInOutFlags == asTM_OUTREF )
  6247. {
  6248. asSExprContext *expr = outParam.origExpr;
  6249. outParam.origExpr = 0;
  6250. if( outParam.argType.dataType.IsObjectHandle() )
  6251. {
  6252. // Implicitly convert the value to a handle
  6253. if( expr->type.dataType.IsObjectHandle() )
  6254. expr->type.isExplicitHandle = true;
  6255. }
  6256. // Verify that the expression result in a lvalue, or a property accessor
  6257. if( IsLValue(expr->type) || expr->property_get || expr->property_set )
  6258. {
  6259. asSExprContext rctx(engine);
  6260. rctx.type = outParam.argType;
  6261. if( rctx.type.dataType.IsPrimitive() )
  6262. rctx.type.dataType.MakeReference(false);
  6263. else
  6264. {
  6265. rctx.bc.InstrSHORT(asBC_PSF, outParam.argType.stackOffset);
  6266. rctx.type.dataType.MakeReference(IsVariableOnHeap(outParam.argType.stackOffset));
  6267. if( expr->type.isExplicitHandle )
  6268. rctx.type.isExplicitHandle = true;
  6269. }
  6270. asSExprContext o(engine);
  6271. DoAssignment(&o, expr, &rctx, outParam.argNode, outParam.argNode, ttAssignment, outParam.argNode);
  6272. if( !o.type.dataType.IsPrimitive() ) o.bc.Pop(AS_PTR_SIZE);
  6273. MergeExprBytecode(ctx, &o);
  6274. }
  6275. else
  6276. {
  6277. // We must still evaluate the expression
  6278. MergeExprBytecode(ctx, expr);
  6279. if( !expr->type.isConstant || expr->type.IsNullConstant() )
  6280. ctx->bc.Pop(expr->type.dataType.GetSizeOnStackDWords());
  6281. // Give a warning, except if the argument is null or 0 which indicate the argument is really to be ignored
  6282. if( !expr->type.IsNullConstant() && !(expr->type.isConstant && expr->type.qwordValue == 0) )
  6283. Warning(TXT_ARG_NOT_LVALUE, outParam.argNode);
  6284. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6285. }
  6286. ReleaseTemporaryVariable(expr->type, &ctx->bc);
  6287. // Delete the original expression context
  6288. asDELETE(expr,asSExprContext);
  6289. }
  6290. else // &inout
  6291. {
  6292. if( outParam.argType.isTemporary )
  6293. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6294. else if( !outParam.argType.isVariable )
  6295. {
  6296. if( outParam.argType.dataType.IsObject() &&
  6297. ((outParam.argType.dataType.GetBehaviour()->addref &&
  6298. outParam.argType.dataType.GetBehaviour()->release) ||
  6299. (outParam.argType.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) )
  6300. {
  6301. // Release the object handle that was taken to guarantee the reference
  6302. ReleaseTemporaryVariable(outParam.argType, &ctx->bc);
  6303. }
  6304. }
  6305. }
  6306. }
  6307. ctx->deferredParams.SetLength(0);
  6308. isProcessingDeferredParams = false;
  6309. }
  6310. void asCCompiler::CompileConstructCall(asCScriptNode *node, asSExprContext *ctx)
  6311. {
  6312. // The first node is a datatype node
  6313. asCString name;
  6314. asCTypeInfo tempObj;
  6315. bool onHeap = true;
  6316. asCArray<int> funcs;
  6317. // It is possible that the name is really a constructor
  6318. asCDataType dt;
  6319. // TODO: namespace: Use correct implicit namespace from function
  6320. dt = builder->CreateDataTypeFromNode(node->firstChild, script, "");
  6321. if( dt.IsPrimitive() )
  6322. {
  6323. // This is a cast to a primitive type
  6324. CompileConversion(node, ctx);
  6325. return;
  6326. }
  6327. // Do not allow constructing non-shared types in shared functions
  6328. if( outFunc->IsShared() &&
  6329. dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  6330. {
  6331. asCString msg;
  6332. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  6333. Error(msg.AddressOf(), node);
  6334. }
  6335. // Compile the arguments
  6336. asCArray<asSExprContext *> args;
  6337. asCArray<asCTypeInfo> temporaryVariables;
  6338. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6339. {
  6340. // Check for a value cast behaviour
  6341. if( args.GetLength() == 1 && args[0]->type.dataType.GetObjectType() )
  6342. {
  6343. asSExprContext conv(engine);
  6344. conv.type = args[0]->type;
  6345. ImplicitConversion(&conv, dt, node->lastChild, asIC_EXPLICIT_VAL_CAST, false);
  6346. if( conv.type.dataType.IsEqualExceptRef(dt) )
  6347. {
  6348. ImplicitConversion(args[0], dt, node->lastChild, asIC_EXPLICIT_VAL_CAST);
  6349. ctx->bc.AddCode(&args[0]->bc);
  6350. ctx->type = args[0]->type;
  6351. asDELETE(args[0],asSExprContext);
  6352. return;
  6353. }
  6354. }
  6355. // Check for possible constructor/factory
  6356. name = dt.Format();
  6357. asSTypeBehaviour *beh = dt.GetBehaviour();
  6358. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6359. {
  6360. funcs = beh->constructors;
  6361. // Value types and script types are allocated through the constructor
  6362. tempObj.dataType = dt;
  6363. tempObj.stackOffset = (short)AllocateVariable(dt, true);
  6364. tempObj.dataType.MakeReference(true);
  6365. tempObj.isTemporary = true;
  6366. tempObj.isVariable = true;
  6367. onHeap = IsVariableOnHeap(tempObj.stackOffset);
  6368. // Push the address of the object on the stack
  6369. if( onHeap )
  6370. ctx->bc.InstrSHORT(asBC_VAR, tempObj.stackOffset);
  6371. }
  6372. else
  6373. {
  6374. funcs = beh->factories;
  6375. }
  6376. // Special case: Allow calling func(void) with a void expression.
  6377. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6378. {
  6379. // Evaluate the expression before the function call
  6380. MergeExprBytecode(ctx, args[0]);
  6381. asDELETE(args[0],asSExprContext);
  6382. args.SetLength(0);
  6383. }
  6384. // Special case: If this is an object constructor and there are no arguments use the default constructor.
  6385. // If none has been registered, just allocate the variable and push it on the stack.
  6386. if( args.GetLength() == 0 )
  6387. {
  6388. asSTypeBehaviour *beh = tempObj.dataType.GetBehaviour();
  6389. if( beh && beh->construct == 0 && !(dt.GetObjectType()->flags & asOBJ_REF) )
  6390. {
  6391. // Call the default constructor
  6392. ctx->type = tempObj;
  6393. if( onHeap )
  6394. {
  6395. asASSERT(ctx->bc.GetLastInstr() == asBC_VAR);
  6396. ctx->bc.RemoveLastInstr();
  6397. }
  6398. CallDefaultConstructor(tempObj.dataType, tempObj.stackOffset, IsVariableOnHeap(tempObj.stackOffset), &ctx->bc, node);
  6399. // Push the reference on the stack
  6400. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6401. return;
  6402. }
  6403. }
  6404. MatchFunctions(funcs, args, node, name.AddressOf(), NULL, false);
  6405. if( funcs.GetLength() != 1 )
  6406. {
  6407. // The error was reported by MatchFunctions()
  6408. // Dummy value
  6409. ctx->type.SetDummy();
  6410. }
  6411. else
  6412. {
  6413. int r = asSUCCESS;
  6414. // Add the default values for arguments not explicitly supplied
  6415. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  6416. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  6417. r = CompileDefaultArgs(node, args, func);
  6418. if( r == asSUCCESS )
  6419. {
  6420. asCByteCode objBC(engine);
  6421. PrepareFunctionCall(funcs[0], &ctx->bc, args);
  6422. MoveArgsToStack(funcs[0], &ctx->bc, args, false);
  6423. if( !(dt.GetObjectType()->flags & asOBJ_REF) )
  6424. {
  6425. // If the object is allocated on the stack, then call the constructor as a normal function
  6426. if( onHeap )
  6427. {
  6428. int offset = 0;
  6429. asCScriptFunction *descr = builder->GetFunctionDescription(funcs[0]);
  6430. for( asUINT n = 0; n < args.GetLength(); n++ )
  6431. offset += descr->parameterTypes[n].GetSizeOnStackDWords();
  6432. ctx->bc.InstrWORD(asBC_GETREF, (asWORD)offset);
  6433. }
  6434. else
  6435. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6436. PerformFunctionCall(funcs[0], ctx, onHeap, &args, tempObj.dataType.GetObjectType());
  6437. // Add tag that the object has been initialized
  6438. ctx->bc.ObjInfo(tempObj.stackOffset, asOBJ_INIT);
  6439. // The constructor doesn't return anything,
  6440. // so we have to manually inform the type of
  6441. // the return value
  6442. ctx->type = tempObj;
  6443. if( !onHeap )
  6444. ctx->type.dataType.MakeReference(false);
  6445. // Push the address of the object on the stack again
  6446. ctx->bc.InstrSHORT(asBC_PSF, tempObj.stackOffset);
  6447. }
  6448. else
  6449. {
  6450. // Call the factory to create the reference type
  6451. PerformFunctionCall(funcs[0], ctx, false, &args);
  6452. }
  6453. }
  6454. }
  6455. }
  6456. else
  6457. {
  6458. // Failed to compile the argument list, set the result to the dummy type
  6459. ctx->type.SetDummy();
  6460. }
  6461. // Cleanup
  6462. for( asUINT n = 0; n < args.GetLength(); n++ )
  6463. if( args[n] )
  6464. {
  6465. asDELETE(args[n],asSExprContext);
  6466. }
  6467. }
  6468. int asCCompiler::CompileFunctionCall(asCScriptNode *node, asSExprContext *ctx, asCObjectType *objectType, bool objIsConst, const asCString &scope)
  6469. {
  6470. asCString name;
  6471. asCTypeInfo tempObj;
  6472. asCArray<int> funcs;
  6473. int r = -1;
  6474. asCScriptNode *nm = node->lastChild->prev;
  6475. name.Assign(&script->code[nm->tokenPos], nm->tokenLength);
  6476. // If we're compiling a class method, then the call may be to a class method
  6477. // even though it looks like an ordinary call to a global function. If it is
  6478. // to a class method it is necessary to implicitly add the this pointer.
  6479. if( objectType == 0 && outFunc && outFunc->objectType && scope != "::" )
  6480. {
  6481. // The special keyword 'super' may be used in constructors to invoke the base
  6482. // class' constructor. This can only be used without any scoping operator
  6483. if( m_isConstructor && name == SUPER_TOKEN && scope == "" )
  6484. {
  6485. // We are calling the base class' constructor, so set the objectType
  6486. objectType = outFunc->objectType;
  6487. }
  6488. else
  6489. {
  6490. // Are there any class methods that may match?
  6491. // TODO: namespace: Should really make sure the scope also match. Because the scope
  6492. // may match a base class, or it may match a global namespace. If it is
  6493. // matching a global scope then we're not calling a class method even
  6494. // if there is a method with the same name.
  6495. asCArray<int> funcs;
  6496. builder->GetObjectMethodDescriptions(name.AddressOf(), outFunc->objectType, funcs, false);
  6497. if( funcs.GetLength() )
  6498. {
  6499. // We're calling a class method, so set the objectType
  6500. objectType = outFunc->objectType;
  6501. }
  6502. }
  6503. // If a class method is being called then implicitly add the this pointer for the call
  6504. if( objectType )
  6505. {
  6506. asCDataType dt = asCDataType::CreateObject(objectType, false);
  6507. // The object pointer is located at stack position 0
  6508. ctx->bc.InstrSHORT(asBC_PSF, 0);
  6509. ctx->type.SetVariable(dt, 0, false);
  6510. ctx->type.dataType.MakeReference(true);
  6511. // TODO: optimize: This adds a CHKREF. Is that really necessary? It isn't as the
  6512. // VM will check for null pointer anyway before calling the method.
  6513. // The bytecode optimizer should know this and remove the unnecessary CHKREF
  6514. Dereference(ctx, true);
  6515. }
  6516. }
  6517. // First check for a local variable of a function type
  6518. // Must not allow function names, nor global variables to be returned in this instance
  6519. asSExprContext funcPtr(engine);
  6520. if( objectType == 0 )
  6521. r = CompileVariableAccess(name, scope, &funcPtr, node, true, true);
  6522. if( r < 0 )
  6523. {
  6524. if( objectType )
  6525. {
  6526. // If we're compiling a constructor and the name of the function is super then
  6527. // the constructor of the base class is being called.
  6528. // super cannot be prefixed with a scope operator
  6529. if( scope == "" && m_isConstructor && name == SUPER_TOKEN )
  6530. {
  6531. // If the class is not derived from anyone else, calling super should give an error
  6532. if( objectType->derivedFrom )
  6533. funcs = objectType->derivedFrom->beh.constructors;
  6534. // Must not allow calling base class' constructor multiple times
  6535. if( continueLabels.GetLength() > 0 )
  6536. {
  6537. // If a continue label is set we are in a loop
  6538. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_LOOPS, node);
  6539. }
  6540. else if( breakLabels.GetLength() > 0 )
  6541. {
  6542. // TODO: inheritance: Should eventually allow constructors in switch statements
  6543. // If a break label is set we are either in a loop or a switch statements
  6544. Error(TXT_CANNOT_CALL_CONSTRUCTOR_IN_SWITCH, node);
  6545. }
  6546. else if( m_isConstructorCalled )
  6547. {
  6548. Error(TXT_CANNOT_CALL_CONSTRUCTOR_TWICE, node);
  6549. }
  6550. m_isConstructorCalled = true;
  6551. }
  6552. else
  6553. {
  6554. // The scope is can be used to specify the base class
  6555. builder->GetObjectMethodDescriptions(name.AddressOf(), objectType, funcs, objIsConst, scope);
  6556. }
  6557. // It is still possible that there is a class member of a function type
  6558. if( funcs.GetLength() == 0 )
  6559. CompileVariableAccess(name, scope, &funcPtr, node, true, true, objectType);
  6560. }
  6561. else
  6562. {
  6563. // The scope is used to define the namespace
  6564. asCString ns = scope == "::" ? "" : scope;
  6565. if( ns == "" )
  6566. {
  6567. if( outFunc->nameSpace != "" )
  6568. ns = outFunc->nameSpace;
  6569. else if( outFunc->objectType && outFunc->objectType->nameSpace != "" )
  6570. ns = outFunc->objectType->nameSpace;
  6571. }
  6572. builder->GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  6573. // TODO: funcdef: It is still possible that there is a global variable of a function type
  6574. }
  6575. }
  6576. else if( !funcPtr.type.dataType.GetFuncDef() )
  6577. {
  6578. // The variable is not a function
  6579. asCString msg;
  6580. msg.Format(TXT_NOT_A_FUNC_s_IS_VAR, name.AddressOf());
  6581. Error(msg.AddressOf(), node);
  6582. return -1;
  6583. }
  6584. if( funcs.GetLength() == 0 && funcPtr.type.dataType.GetFuncDef() )
  6585. {
  6586. funcs.PushLast(funcPtr.type.dataType.GetFuncDef()->id);
  6587. }
  6588. // Compile the arguments
  6589. asCArray<asSExprContext *> args;
  6590. asCArray<asCTypeInfo> temporaryVariables;
  6591. if( CompileArgumentList(node->lastChild, args) >= 0 )
  6592. {
  6593. // Special case: Allow calling func(void) with a void expression.
  6594. if( args.GetLength() == 1 && args[0]->type.dataType == asCDataType::CreatePrimitive(ttVoid, false) )
  6595. {
  6596. // Evaluate the expression before the function call
  6597. MergeExprBytecode(ctx, args[0]);
  6598. asDELETE(args[0],asSExprContext);
  6599. args.SetLength(0);
  6600. }
  6601. MatchFunctions(funcs, args, node, name.AddressOf(), objectType, objIsConst, false, true, scope);
  6602. if( funcs.GetLength() != 1 )
  6603. {
  6604. // The error was reported by MatchFunctions()
  6605. // Dummy value
  6606. ctx->type.SetDummy();
  6607. }
  6608. else
  6609. {
  6610. int r = asSUCCESS;
  6611. // Add the default values for arguments not explicitly supplied
  6612. asCScriptFunction *func = (funcs[0] & 0xFFFF0000) == 0 ? engine->scriptFunctions[funcs[0]] : 0;
  6613. if( func && args.GetLength() < (asUINT)func->GetParamCount() )
  6614. r = CompileDefaultArgs(node, args, func);
  6615. // TODO: funcdef: Do we have to make sure the handle is stored in a temporary variable, or
  6616. // is it enough to make sure it is in a local variable?
  6617. // For function pointer we must guarantee that the function is safe, i.e.
  6618. // by first storing the function pointer in a local variable (if it isn't already in one)
  6619. if( r == asSUCCESS )
  6620. {
  6621. if( (funcs[0] & 0xFFFF0000) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  6622. {
  6623. if( objectType )
  6624. {
  6625. Dereference(ctx, true); // Dereference the object pointer to access the member
  6626. // The actual function should be called as if a global function
  6627. objectType = 0;
  6628. }
  6629. Dereference(&funcPtr, true);
  6630. ConvertToVariable(&funcPtr);
  6631. ctx->bc.AddCode(&funcPtr.bc);
  6632. if( !funcPtr.type.isTemporary )
  6633. ctx->bc.Pop(AS_PTR_SIZE);
  6634. }
  6635. MakeFunctionCall(ctx, funcs[0], objectType, args, node, false, 0, funcPtr.type.stackOffset);
  6636. // If the function pointer was copied to a local variable for the call, then
  6637. // release it again (temporary local variable)
  6638. if( (funcs[0] & 0xFFFF0000) == 0 && engine->scriptFunctions[funcs[0]]->funcType == asFUNC_FUNCDEF )
  6639. {
  6640. ReleaseTemporaryVariable(funcPtr.type, &ctx->bc);
  6641. }
  6642. }
  6643. }
  6644. }
  6645. else
  6646. {
  6647. // Failed to compile the argument list, set the dummy type and continue compilation
  6648. ctx->type.SetDummy();
  6649. }
  6650. // Cleanup
  6651. for( asUINT n = 0; n < args.GetLength(); n++ )
  6652. if( args[n] )
  6653. {
  6654. asDELETE(args[n],asSExprContext);
  6655. }
  6656. return 0;
  6657. }
  6658. int asCCompiler::CompileExpressionPreOp(asCScriptNode *node, asSExprContext *ctx)
  6659. {
  6660. int op = node->tokenType;
  6661. IsVariableInitialized(&ctx->type, node);
  6662. if( op == ttHandle )
  6663. {
  6664. // Verify that the type allow its handle to be taken
  6665. if( ctx->type.isExplicitHandle ||
  6666. !ctx->type.dataType.IsObject() ||
  6667. !(((ctx->type.dataType.GetObjectType()->beh.addref && ctx->type.dataType.GetObjectType()->beh.release) || (ctx->type.dataType.GetObjectType()->flags & asOBJ_NOCOUNT)) ||
  6668. (ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) )
  6669. {
  6670. Error(TXT_OBJECT_HANDLE_NOT_SUPPORTED, node);
  6671. return -1;
  6672. }
  6673. // Objects that are not local variables are not references
  6674. // Objects allocated on the stack are also not marked as references
  6675. if( !ctx->type.dataType.IsReference() &&
  6676. !(ctx->type.dataType.IsObject() && !ctx->type.isVariable) &&
  6677. !(ctx->type.isVariable && !IsVariableOnHeap(ctx->type.stackOffset)) )
  6678. {
  6679. Error(TXT_NOT_VALID_REFERENCE, node);
  6680. return -1;
  6681. }
  6682. // If this is really an object then the handle created is a const handle
  6683. bool makeConst = !ctx->type.dataType.IsObjectHandle() && !(ctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE);
  6684. // Mark the type as an object handle
  6685. ctx->type.dataType.MakeHandle(true);
  6686. ctx->type.isExplicitHandle = true;
  6687. if( makeConst )
  6688. ctx->type.dataType.MakeReadOnly(true);
  6689. }
  6690. else if( (op == ttMinus || op == ttBitNot || op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  6691. {
  6692. // Look for the appropriate method
  6693. const char *opName = 0;
  6694. switch( op )
  6695. {
  6696. case ttMinus: opName = "opNeg"; break;
  6697. case ttBitNot: opName = "opCom"; break;
  6698. case ttInc: opName = "opPreInc"; break;
  6699. case ttDec: opName = "opPreDec"; break;
  6700. }
  6701. if( opName )
  6702. {
  6703. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  6704. ProcessPropertyGetAccessor(ctx, node);
  6705. // Is it a const value?
  6706. bool isConst = false;
  6707. if( ctx->type.dataType.IsObjectHandle() )
  6708. isConst = ctx->type.dataType.IsHandleToConst();
  6709. else
  6710. isConst = ctx->type.dataType.IsReadOnly();
  6711. // 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
  6712. // Find the correct method
  6713. asCArray<int> funcs;
  6714. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  6715. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  6716. {
  6717. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  6718. if( func->name == opName &&
  6719. func->parameterTypes.GetLength() == 0 &&
  6720. (!isConst || func->isReadOnly) )
  6721. {
  6722. funcs.PushLast(func->id);
  6723. }
  6724. }
  6725. // Did we find the method?
  6726. if( funcs.GetLength() == 1 )
  6727. {
  6728. asCTypeInfo objType = ctx->type;
  6729. asCArray<asSExprContext *> args;
  6730. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  6731. ReleaseTemporaryVariable(objType, &ctx->bc);
  6732. return 0;
  6733. }
  6734. else if( funcs.GetLength() == 0 )
  6735. {
  6736. asCString str;
  6737. str = asCString(opName) + "()";
  6738. if( isConst )
  6739. str += " const";
  6740. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  6741. Error(str.AddressOf(), node);
  6742. ctx->type.SetDummy();
  6743. return -1;
  6744. }
  6745. else if( funcs.GetLength() > 1 )
  6746. {
  6747. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  6748. PrintMatchingFuncs(funcs, node);
  6749. ctx->type.SetDummy();
  6750. return -1;
  6751. }
  6752. }
  6753. }
  6754. else if( op == ttPlus || op == ttMinus )
  6755. {
  6756. ProcessPropertyGetAccessor(ctx, node);
  6757. asCDataType to = ctx->type.dataType;
  6758. // TODO: The case -2147483648 gives an unecessary warning of changed sign for implicit conversion
  6759. if( ctx->type.dataType.IsUnsignedType() || ctx->type.dataType.IsEnumType() )
  6760. {
  6761. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  6762. to = asCDataType::CreatePrimitive(ttInt8, false);
  6763. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  6764. to = asCDataType::CreatePrimitive(ttInt16, false);
  6765. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  6766. to = asCDataType::CreatePrimitive(ttInt, false);
  6767. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  6768. to = asCDataType::CreatePrimitive(ttInt64, false);
  6769. else
  6770. {
  6771. Error(TXT_INVALID_TYPE, node);
  6772. return -1;
  6773. }
  6774. }
  6775. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  6776. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  6777. if( !ctx->type.isConstant )
  6778. {
  6779. ConvertToTempVariable(ctx);
  6780. asASSERT(!ctx->type.isLValue);
  6781. if( op == ttMinus )
  6782. {
  6783. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6784. ctx->bc.InstrSHORT(asBC_NEGi, ctx->type.stackOffset);
  6785. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  6786. ctx->bc.InstrSHORT(asBC_NEGi64, ctx->type.stackOffset);
  6787. else if( ctx->type.dataType.IsFloatType() )
  6788. ctx->bc.InstrSHORT(asBC_NEGf, ctx->type.stackOffset);
  6789. else if( ctx->type.dataType.IsDoubleType() )
  6790. ctx->bc.InstrSHORT(asBC_NEGd, ctx->type.stackOffset);
  6791. else
  6792. {
  6793. Error(TXT_ILLEGAL_OPERATION, node);
  6794. return -1;
  6795. }
  6796. return 0;
  6797. }
  6798. }
  6799. else
  6800. {
  6801. if( op == ttMinus )
  6802. {
  6803. if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6804. ctx->type.intValue = -ctx->type.intValue;
  6805. else if( ctx->type.dataType.IsIntegerType() && ctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  6806. ctx->type.qwordValue = -(asINT64)ctx->type.qwordValue;
  6807. else if( ctx->type.dataType.IsFloatType() )
  6808. ctx->type.floatValue = -ctx->type.floatValue;
  6809. else if( ctx->type.dataType.IsDoubleType() )
  6810. ctx->type.doubleValue = -ctx->type.doubleValue;
  6811. else
  6812. {
  6813. Error(TXT_ILLEGAL_OPERATION, node);
  6814. return -1;
  6815. }
  6816. return 0;
  6817. }
  6818. }
  6819. if( op == ttPlus )
  6820. {
  6821. if( !ctx->type.dataType.IsIntegerType() &&
  6822. !ctx->type.dataType.IsFloatType() &&
  6823. !ctx->type.dataType.IsDoubleType() )
  6824. {
  6825. Error(TXT_ILLEGAL_OPERATION, node);
  6826. return -1;
  6827. }
  6828. }
  6829. }
  6830. else if( op == ttNot )
  6831. {
  6832. if( ctx->type.dataType.IsEqualExceptRefAndConst(asCDataType::CreatePrimitive(ttBool, true)) )
  6833. {
  6834. if( ctx->type.isConstant )
  6835. {
  6836. ctx->type.dwordValue = (ctx->type.dwordValue == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  6837. return 0;
  6838. }
  6839. ProcessPropertyGetAccessor(ctx, node);
  6840. ConvertToTempVariable(ctx);
  6841. asASSERT(!ctx->type.isLValue);
  6842. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  6843. }
  6844. else
  6845. {
  6846. Error(TXT_ILLEGAL_OPERATION, node);
  6847. return -1;
  6848. }
  6849. }
  6850. else if( op == ttBitNot )
  6851. {
  6852. ProcessPropertyGetAccessor(ctx, node);
  6853. asCDataType to = ctx->type.dataType;
  6854. if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsEnumType() )
  6855. {
  6856. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  6857. to = asCDataType::CreatePrimitive(ttUInt8, false);
  6858. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  6859. to = asCDataType::CreatePrimitive(ttUInt16, false);
  6860. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  6861. to = asCDataType::CreatePrimitive(ttUInt, false);
  6862. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 8 )
  6863. to = asCDataType::CreatePrimitive(ttUInt64, false);
  6864. else
  6865. {
  6866. Error(TXT_INVALID_TYPE, node);
  6867. return -1;
  6868. }
  6869. }
  6870. if( ctx->type.dataType.IsReference() ) ConvertToVariable(ctx);
  6871. ImplicitConversion(ctx, to, node, asIC_IMPLICIT_CONV);
  6872. if( ctx->type.dataType.IsUnsignedType() )
  6873. {
  6874. if( ctx->type.isConstant )
  6875. {
  6876. ctx->type.qwordValue = ~ctx->type.qwordValue;
  6877. return 0;
  6878. }
  6879. ConvertToTempVariable(ctx);
  6880. asASSERT(!ctx->type.isLValue);
  6881. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  6882. ctx->bc.InstrSHORT(asBC_BNOT, ctx->type.stackOffset);
  6883. else
  6884. ctx->bc.InstrSHORT(asBC_BNOT64, ctx->type.stackOffset);
  6885. }
  6886. else
  6887. {
  6888. Error(TXT_ILLEGAL_OPERATION, node);
  6889. return -1;
  6890. }
  6891. }
  6892. else if( op == ttInc || op == ttDec )
  6893. {
  6894. // Need a reference to the primitive that will be updated
  6895. // The result of this expression is the same reference as before
  6896. // Make sure the reference isn't a temporary variable
  6897. if( ctx->type.isTemporary )
  6898. {
  6899. Error(TXT_REF_IS_TEMP, node);
  6900. return -1;
  6901. }
  6902. if( ctx->type.dataType.IsReadOnly() )
  6903. {
  6904. Error(TXT_REF_IS_READ_ONLY, node);
  6905. return -1;
  6906. }
  6907. if( ctx->property_get || ctx->property_set )
  6908. {
  6909. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  6910. return -1;
  6911. }
  6912. if( !ctx->type.isLValue )
  6913. {
  6914. Error(TXT_NOT_LVALUE, node);
  6915. return -1;
  6916. }
  6917. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  6918. ConvertToReference(ctx);
  6919. else if( !ctx->type.dataType.IsReference() )
  6920. {
  6921. Error(TXT_NOT_VALID_REFERENCE, node);
  6922. return -1;
  6923. }
  6924. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  6925. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  6926. {
  6927. if( op == ttInc )
  6928. ctx->bc.Instr(asBC_INCi64);
  6929. else
  6930. ctx->bc.Instr(asBC_DECi64);
  6931. }
  6932. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt, false)) ||
  6933. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt, false)) )
  6934. {
  6935. if( op == ttInc )
  6936. ctx->bc.Instr(asBC_INCi);
  6937. else
  6938. ctx->bc.Instr(asBC_DECi);
  6939. }
  6940. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  6941. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  6942. {
  6943. if( op == ttInc )
  6944. ctx->bc.Instr(asBC_INCi16);
  6945. else
  6946. ctx->bc.Instr(asBC_DECi16);
  6947. }
  6948. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  6949. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  6950. {
  6951. if( op == ttInc )
  6952. ctx->bc.Instr(asBC_INCi8);
  6953. else
  6954. ctx->bc.Instr(asBC_DECi8);
  6955. }
  6956. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttFloat, false)) )
  6957. {
  6958. if( op == ttInc )
  6959. ctx->bc.Instr(asBC_INCf);
  6960. else
  6961. ctx->bc.Instr(asBC_DECf);
  6962. }
  6963. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttDouble, false)) )
  6964. {
  6965. if( op == ttInc )
  6966. ctx->bc.Instr(asBC_INCd);
  6967. else
  6968. ctx->bc.Instr(asBC_DECd);
  6969. }
  6970. else
  6971. {
  6972. Error(TXT_ILLEGAL_OPERATION, node);
  6973. return -1;
  6974. }
  6975. }
  6976. else
  6977. {
  6978. // Unknown operator
  6979. asASSERT(false);
  6980. return -1;
  6981. }
  6982. return 0;
  6983. }
  6984. void asCCompiler::ConvertToReference(asSExprContext *ctx)
  6985. {
  6986. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  6987. {
  6988. ctx->bc.InstrSHORT(asBC_LDV, ctx->type.stackOffset);
  6989. ctx->type.dataType.MakeReference(true);
  6990. ctx->type.SetVariable(ctx->type.dataType, ctx->type.stackOffset, ctx->type.isTemporary);
  6991. }
  6992. }
  6993. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asCScriptNode *node, bool isThisAccess)
  6994. {
  6995. return FindPropertyAccessor(name, ctx, 0, node, isThisAccess);
  6996. }
  6997. int asCCompiler::FindPropertyAccessor(const asCString &name, asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node, bool isThisAccess)
  6998. {
  6999. if( engine->ep.propertyAccessorMode == 0 )
  7000. {
  7001. // Property accessors have been disabled by the application
  7002. return 0;
  7003. }
  7004. int getId = 0, setId = 0;
  7005. asCString getName = "get_" + name;
  7006. asCString setName = "set_" + name;
  7007. asCArray<int> multipleGetFuncs, multipleSetFuncs;
  7008. if( ctx->type.dataType.IsObject() )
  7009. {
  7010. // Check if the object has any methods with the corresponding accessor name(s)
  7011. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  7012. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7013. {
  7014. asCScriptFunction *f = engine->scriptFunctions[ot->methods[n]];
  7015. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  7016. if( f->name == getName && (int)f->parameterTypes.GetLength() == (arg?1:0) )
  7017. {
  7018. if( getId == 0 )
  7019. getId = ot->methods[n];
  7020. else
  7021. {
  7022. if( multipleGetFuncs.GetLength() == 0 )
  7023. multipleGetFuncs.PushLast(getId);
  7024. multipleGetFuncs.PushLast(ot->methods[n]);
  7025. }
  7026. }
  7027. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  7028. if( f->name == setName && (int)f->parameterTypes.GetLength() == (arg?2:1) )
  7029. {
  7030. if( setId == 0 )
  7031. setId = ot->methods[n];
  7032. else
  7033. {
  7034. if( multipleSetFuncs.GetLength() == 0 )
  7035. multipleSetFuncs.PushLast(setId);
  7036. multipleSetFuncs.PushLast(ot->methods[n]);
  7037. }
  7038. }
  7039. }
  7040. }
  7041. else
  7042. {
  7043. // Look for appropriate global functions.
  7044. asCArray<int> funcs;
  7045. asUINT n;
  7046. // TODO: namespace: use the proper namespace
  7047. builder->GetFunctionDescriptions(getName.AddressOf(), funcs, "");
  7048. for( n = 0; n < funcs.GetLength(); n++ )
  7049. {
  7050. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  7051. // TODO: The type of the parameter should match the argument (unless the arg is a dummy)
  7052. if( (int)f->parameterTypes.GetLength() == (arg?1:0) )
  7053. {
  7054. if( getId == 0 )
  7055. getId = funcs[n];
  7056. else
  7057. {
  7058. if( multipleGetFuncs.GetLength() == 0 )
  7059. multipleGetFuncs.PushLast(getId);
  7060. multipleGetFuncs.PushLast(funcs[n]);
  7061. }
  7062. }
  7063. }
  7064. funcs.SetLength(0);
  7065. // TODO: namespace: use the proper namespace
  7066. builder->GetFunctionDescriptions(setName.AddressOf(), funcs, "");
  7067. for( n = 0; n < funcs.GetLength(); n++ )
  7068. {
  7069. asCScriptFunction *f = builder->GetFunctionDescription(funcs[n]);
  7070. // TODO: getset: If the parameter is a reference, it must not be an out reference. Should we allow inout ref?
  7071. if( (int)f->parameterTypes.GetLength() == (arg?2:1) )
  7072. {
  7073. if( setId == 0 )
  7074. setId = funcs[n];
  7075. else
  7076. {
  7077. if( multipleSetFuncs.GetLength() == 0 )
  7078. multipleSetFuncs.PushLast(getId);
  7079. multipleSetFuncs.PushLast(funcs[n]);
  7080. }
  7081. }
  7082. }
  7083. }
  7084. // Check for multiple matches
  7085. if( multipleGetFuncs.GetLength() > 0 )
  7086. {
  7087. asCString str;
  7088. str.Format(TXT_MULTIPLE_PROP_GET_ACCESSOR_FOR_s, name.AddressOf());
  7089. Error(str.AddressOf(), node);
  7090. PrintMatchingFuncs(multipleGetFuncs, node);
  7091. return -1;
  7092. }
  7093. if( multipleSetFuncs.GetLength() > 0 )
  7094. {
  7095. asCString str;
  7096. str.Format(TXT_MULTIPLE_PROP_SET_ACCESSOR_FOR_s, name.AddressOf());
  7097. Error(str.AddressOf(), node);
  7098. PrintMatchingFuncs(multipleSetFuncs, node);
  7099. return -1;
  7100. }
  7101. // Check for type compatibility between get and set accessor
  7102. if( getId && setId )
  7103. {
  7104. asCScriptFunction *getFunc = builder->GetFunctionDescription(getId);
  7105. asCScriptFunction *setFunc = builder->GetFunctionDescription(setId);
  7106. // It is permitted for a getter to return a handle and the setter to take a reference
  7107. int idx = (arg?1:0);
  7108. if( !getFunc->returnType.IsEqualExceptRefAndConst(setFunc->parameterTypes[idx]) &&
  7109. !((getFunc->returnType.IsObjectHandle() && !setFunc->parameterTypes[idx].IsObjectHandle()) &&
  7110. (getFunc->returnType.GetObjectType() == setFunc->parameterTypes[idx].GetObjectType())) )
  7111. {
  7112. asCString str;
  7113. str.Format(TXT_GET_SET_ACCESSOR_TYPE_MISMATCH_FOR_s, name.AddressOf());
  7114. Error(str.AddressOf(), node);
  7115. asCArray<int> funcs;
  7116. funcs.PushLast(getId);
  7117. funcs.PushLast(setId);
  7118. PrintMatchingFuncs(funcs, node);
  7119. return -1;
  7120. }
  7121. }
  7122. // Check if we are within one of the accessors
  7123. int realGetId = getId;
  7124. int realSetId = setId;
  7125. if( outFunc->objectType && isThisAccess )
  7126. {
  7127. // The property accessors would be virtual functions, so we need to find the real implementation
  7128. asCScriptFunction *getFunc = getId ? builder->GetFunctionDescription(getId) : 0;
  7129. if( getFunc &&
  7130. getFunc->funcType == asFUNC_VIRTUAL &&
  7131. outFunc->objectType->DerivesFrom(getFunc->objectType) )
  7132. realGetId = outFunc->objectType->virtualFunctionTable[getFunc->vfTableIdx]->id;
  7133. asCScriptFunction *setFunc = setId ? builder->GetFunctionDescription(setId) : 0;
  7134. if( setFunc &&
  7135. setFunc->funcType == asFUNC_VIRTUAL &&
  7136. outFunc->objectType->DerivesFrom(setFunc->objectType) )
  7137. realSetId = outFunc->objectType->virtualFunctionTable[setFunc->vfTableIdx]->id;
  7138. }
  7139. // Avoid recursive call, by not treating this as a property accessor call.
  7140. // This will also allow having the real property with the same name as the accessors.
  7141. if( (isThisAccess || outFunc->objectType == 0) &&
  7142. ((realGetId && realGetId == outFunc->id) ||
  7143. (realSetId && realSetId == outFunc->id)) )
  7144. {
  7145. getId = 0;
  7146. setId = 0;
  7147. }
  7148. // Check if the application has disabled script written property accessors
  7149. if( engine->ep.propertyAccessorMode == 1 )
  7150. {
  7151. if( getId && builder->GetFunctionDescription(getId)->funcType != asFUNC_SYSTEM )
  7152. getId = 0;
  7153. if( setId && builder->GetFunctionDescription(setId)->funcType != asFUNC_SYSTEM )
  7154. setId = 0;
  7155. }
  7156. if( getId || setId )
  7157. {
  7158. // Property accessors were found, but we don't know which is to be used yet, so
  7159. // we just prepare the bytecode for the method call, and then store the function ids
  7160. // so that the right one can be used when we get there.
  7161. ctx->property_get = getId;
  7162. ctx->property_set = setId;
  7163. if( ctx->type.dataType.IsObject() )
  7164. {
  7165. // If the object is read-only then we need to remember that
  7166. if( (!ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsReadOnly()) ||
  7167. (ctx->type.dataType.IsObjectHandle() && ctx->type.dataType.IsHandleToConst()) )
  7168. ctx->property_const = true;
  7169. else
  7170. ctx->property_const = false;
  7171. // If the object is a handle then we need to remember that
  7172. ctx->property_handle = ctx->type.dataType.IsObjectHandle();
  7173. ctx->property_ref = ctx->type.dataType.IsReference();
  7174. }
  7175. // The setter's parameter type is used as the property type,
  7176. // unless only the getter is available
  7177. asCDataType dt;
  7178. if( setId )
  7179. dt = builder->GetFunctionDescription(setId)->parameterTypes[(arg?1:0)];
  7180. else
  7181. dt = builder->GetFunctionDescription(getId)->returnType;
  7182. // Just change the type, the context must still maintain information
  7183. // about previous variable offset and the indicator of temporary variable.
  7184. int offset = ctx->type.stackOffset;
  7185. bool isTemp = ctx->type.isTemporary;
  7186. ctx->type.Set(dt);
  7187. ctx->type.stackOffset = (short)offset;
  7188. ctx->type.isTemporary = isTemp;
  7189. ctx->exprNode = node;
  7190. // Store the argument for later use
  7191. if( arg )
  7192. {
  7193. ctx->property_arg = asNEW(asSExprContext)(engine);
  7194. MergeExprBytecodeAndType(ctx->property_arg, arg);
  7195. }
  7196. return 1;
  7197. }
  7198. // No accessor was found
  7199. return 0;
  7200. }
  7201. int asCCompiler::ProcessPropertySetAccessor(asSExprContext *ctx, asSExprContext *arg, asCScriptNode *node)
  7202. {
  7203. // TODO: A lot of this code is similar to ProcessPropertyGetAccessor. Can we unify them?
  7204. if( !ctx->property_set )
  7205. {
  7206. Error(TXT_PROPERTY_HAS_NO_SET_ACCESSOR, node);
  7207. return -1;
  7208. }
  7209. asCTypeInfo objType = ctx->type;
  7210. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_set);
  7211. // Make sure the arg match the property
  7212. asCArray<int> funcs;
  7213. funcs.PushLast(ctx->property_set);
  7214. asCArray<asSExprContext *> args;
  7215. if( ctx->property_arg )
  7216. args.PushLast(ctx->property_arg);
  7217. args.PushLast(arg);
  7218. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  7219. if( funcs.GetLength() == 0 )
  7220. {
  7221. // MatchFunctions already reported the error
  7222. if( ctx->property_arg )
  7223. {
  7224. asDELETE(ctx->property_arg, asSExprContext);
  7225. ctx->property_arg = 0;
  7226. }
  7227. return -1;
  7228. }
  7229. if( func->objectType )
  7230. {
  7231. // Setup the context with the original type so the method call gets built correctly
  7232. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7233. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7234. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7235. // Don't allow the call if the object is read-only and the property accessor is not const
  7236. if( ctx->property_const && !func->isReadOnly )
  7237. {
  7238. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  7239. asCArray<int> funcs;
  7240. funcs.PushLast(ctx->property_set);
  7241. PrintMatchingFuncs(funcs, node);
  7242. }
  7243. }
  7244. // Call the accessor
  7245. MakeFunctionCall(ctx, ctx->property_set, func->objectType, args, node);
  7246. if( func->objectType )
  7247. {
  7248. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  7249. if( !objType.isTemporary ||
  7250. !ctx->type.dataType.IsReference() ||
  7251. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7252. {
  7253. // As the method didn't return a reference to a member
  7254. // we can safely release the original object now
  7255. ReleaseTemporaryVariable(objType, &ctx->bc);
  7256. }
  7257. }
  7258. ctx->property_get = 0;
  7259. ctx->property_set = 0;
  7260. if( ctx->property_arg )
  7261. {
  7262. asDELETE(ctx->property_arg, asSExprContext);
  7263. ctx->property_arg = 0;
  7264. }
  7265. return 0;
  7266. }
  7267. void asCCompiler::ProcessPropertyGetAccessor(asSExprContext *ctx, asCScriptNode *node)
  7268. {
  7269. // If no property accessor has been prepared then don't do anything
  7270. if( !ctx->property_get && !ctx->property_set )
  7271. return;
  7272. if( !ctx->property_get )
  7273. {
  7274. // Raise error on missing accessor
  7275. Error(TXT_PROPERTY_HAS_NO_GET_ACCESSOR, node);
  7276. ctx->type.SetDummy();
  7277. return;
  7278. }
  7279. asCTypeInfo objType = ctx->type;
  7280. asCScriptFunction *func = builder->GetFunctionDescription(ctx->property_get);
  7281. // Make sure the arg match the property
  7282. asCArray<int> funcs;
  7283. funcs.PushLast(ctx->property_get);
  7284. asCArray<asSExprContext *> args;
  7285. if( ctx->property_arg )
  7286. args.PushLast(ctx->property_arg);
  7287. MatchFunctions(funcs, args, node, func->GetName(), func->objectType, ctx->property_const);
  7288. if( funcs.GetLength() == 0 )
  7289. {
  7290. // MatchFunctions already reported the error
  7291. if( ctx->property_arg )
  7292. {
  7293. asDELETE(ctx->property_arg, asSExprContext);
  7294. ctx->property_arg = 0;
  7295. }
  7296. ctx->type.SetDummy();
  7297. return;
  7298. }
  7299. if( func->objectType )
  7300. {
  7301. // Setup the context with the original type so the method call gets built correctly
  7302. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7303. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7304. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7305. // Don't allow the call if the object is read-only and the property accessor is not const
  7306. if( ctx->property_const && !func->isReadOnly )
  7307. {
  7308. Error(TXT_NON_CONST_METHOD_ON_CONST_OBJ, node);
  7309. asCArray<int> funcs;
  7310. funcs.PushLast(ctx->property_get);
  7311. PrintMatchingFuncs(funcs, node);
  7312. }
  7313. }
  7314. // Call the accessor
  7315. MakeFunctionCall(ctx, ctx->property_get, func->objectType, args, node);
  7316. if( func->objectType )
  7317. {
  7318. // TODO: This is from CompileExpressionPostOp, can we unify the code?
  7319. if( !objType.isTemporary ||
  7320. !ctx->type.dataType.IsReference() ||
  7321. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7322. {
  7323. // As the method didn't return a reference to a member
  7324. // we can safely release the original object now
  7325. ReleaseTemporaryVariable(objType, &ctx->bc);
  7326. }
  7327. }
  7328. ctx->property_get = 0;
  7329. ctx->property_set = 0;
  7330. if( ctx->property_arg )
  7331. {
  7332. asDELETE(ctx->property_arg, asSExprContext);
  7333. ctx->property_arg = 0;
  7334. }
  7335. }
  7336. int asCCompiler::CompileExpressionPostOp(asCScriptNode *node, asSExprContext *ctx)
  7337. {
  7338. int op = node->tokenType;
  7339. // Check if the variable is initialized (if it indeed is a variable)
  7340. IsVariableInitialized(&ctx->type, node);
  7341. if( (op == ttInc || op == ttDec) && ctx->type.dataType.IsObject() )
  7342. {
  7343. const char *opName = 0;
  7344. switch( op )
  7345. {
  7346. case ttInc: opName = "opPostInc"; break;
  7347. case ttDec: opName = "opPostDec"; break;
  7348. }
  7349. if( opName )
  7350. {
  7351. // TODO: Should convert this to something similar to CompileOverloadedDualOperator2
  7352. ProcessPropertyGetAccessor(ctx, node);
  7353. // Is it a const value?
  7354. bool isConst = false;
  7355. if( ctx->type.dataType.IsObjectHandle() )
  7356. isConst = ctx->type.dataType.IsHandleToConst();
  7357. else
  7358. isConst = ctx->type.dataType.IsReadOnly();
  7359. // 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
  7360. // Find the correct method
  7361. asCArray<int> funcs;
  7362. asCObjectType *ot = ctx->type.dataType.GetObjectType();
  7363. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7364. {
  7365. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  7366. if( func->name == opName &&
  7367. func->parameterTypes.GetLength() == 0 &&
  7368. (!isConst || func->isReadOnly) )
  7369. {
  7370. funcs.PushLast(func->id);
  7371. }
  7372. }
  7373. // Did we find the method?
  7374. if( funcs.GetLength() == 1 )
  7375. {
  7376. asCTypeInfo objType = ctx->type;
  7377. asCArray<asSExprContext *> args;
  7378. MakeFunctionCall(ctx, funcs[0], objType.dataType.GetObjectType(), args, node);
  7379. ReleaseTemporaryVariable(objType, &ctx->bc);
  7380. return 0;
  7381. }
  7382. else if( funcs.GetLength() == 0 )
  7383. {
  7384. asCString str;
  7385. str = asCString(opName) + "()";
  7386. if( isConst )
  7387. str += " const";
  7388. str.Format(TXT_FUNCTION_s_NOT_FOUND, str.AddressOf());
  7389. Error(str.AddressOf(), node);
  7390. ctx->type.SetDummy();
  7391. return -1;
  7392. }
  7393. else if( funcs.GetLength() > 1 )
  7394. {
  7395. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  7396. PrintMatchingFuncs(funcs, node);
  7397. ctx->type.SetDummy();
  7398. return -1;
  7399. }
  7400. }
  7401. }
  7402. else if( op == ttInc || op == ttDec )
  7403. {
  7404. // Make sure the reference isn't a temporary variable
  7405. if( ctx->type.isTemporary )
  7406. {
  7407. Error(TXT_REF_IS_TEMP, node);
  7408. return -1;
  7409. }
  7410. if( ctx->type.dataType.IsReadOnly() )
  7411. {
  7412. Error(TXT_REF_IS_READ_ONLY, node);
  7413. return -1;
  7414. }
  7415. if( ctx->property_get || ctx->property_set )
  7416. {
  7417. Error(TXT_INVALID_REF_PROP_ACCESS, node);
  7418. return -1;
  7419. }
  7420. if( !ctx->type.isLValue )
  7421. {
  7422. Error(TXT_NOT_LVALUE, node);
  7423. return -1;
  7424. }
  7425. if( ctx->type.isVariable && !ctx->type.dataType.IsReference() )
  7426. ConvertToReference(ctx);
  7427. else if( !ctx->type.dataType.IsReference() )
  7428. {
  7429. Error(TXT_NOT_VALID_REFERENCE, node);
  7430. return -1;
  7431. }
  7432. // Copy the value to a temp before changing it
  7433. ConvertToTempVariable(ctx);
  7434. asASSERT(!ctx->type.isLValue);
  7435. // Increment the value pointed to by the reference still in the register
  7436. asEBCInstr iInc = asBC_INCi, iDec = asBC_DECi;
  7437. if( ctx->type.dataType.IsDoubleType() )
  7438. {
  7439. iInc = asBC_INCd;
  7440. iDec = asBC_DECd;
  7441. }
  7442. else if( ctx->type.dataType.IsFloatType() )
  7443. {
  7444. iInc = asBC_INCf;
  7445. iDec = asBC_DECf;
  7446. }
  7447. else if( ctx->type.dataType.IsIntegerType() || ctx->type.dataType.IsUnsignedType() )
  7448. {
  7449. if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt16, false)) ||
  7450. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt16, false)) )
  7451. {
  7452. iInc = asBC_INCi16;
  7453. iDec = asBC_DECi16;
  7454. }
  7455. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt8, false)) ||
  7456. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt8, false)) )
  7457. {
  7458. iInc = asBC_INCi8;
  7459. iDec = asBC_DECi8;
  7460. }
  7461. else if( ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttInt64, false)) ||
  7462. ctx->type.dataType.IsEqualExceptRef(asCDataType::CreatePrimitive(ttUInt64, false)) )
  7463. {
  7464. iInc = asBC_INCi64;
  7465. iDec = asBC_DECi64;
  7466. }
  7467. }
  7468. else
  7469. {
  7470. Error(TXT_ILLEGAL_OPERATION, node);
  7471. return -1;
  7472. }
  7473. if( op == ttInc ) ctx->bc.Instr(iInc); else ctx->bc.Instr(iDec);
  7474. }
  7475. else if( op == ttDot )
  7476. {
  7477. if( node->firstChild->nodeType == snIdentifier )
  7478. {
  7479. ProcessPropertyGetAccessor(ctx, node);
  7480. // Get the property name
  7481. asCString name(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  7482. // We need to look for get/set property accessors.
  7483. // If found, the context stores information on the get/set accessors
  7484. // until it is known which is to be used.
  7485. int r = 0;
  7486. if( node->next && node->next->tokenType == ttOpenBracket )
  7487. {
  7488. // The property accessor should take an index arg
  7489. asSExprContext dummyArg(engine);
  7490. r = FindPropertyAccessor(name, ctx, &dummyArg, node);
  7491. }
  7492. if( r == 0 )
  7493. r = FindPropertyAccessor(name, ctx, node);
  7494. if( r != 0 )
  7495. return r;
  7496. if( !ctx->type.dataType.IsPrimitive() )
  7497. Dereference(ctx, true);
  7498. if( ctx->type.dataType.IsObjectHandle() )
  7499. {
  7500. // Convert the handle to a normal object
  7501. asCDataType dt = ctx->type.dataType;
  7502. dt.MakeHandle(false);
  7503. ImplicitConversion(ctx, dt, node, asIC_IMPLICIT_CONV);
  7504. // The handle may not have been an lvalue, but the dereferenced object is
  7505. ctx->type.isLValue = true;
  7506. }
  7507. // Find the property offset and type
  7508. if( ctx->type.dataType.IsObject() )
  7509. {
  7510. bool isConst = ctx->type.dataType.IsReadOnly();
  7511. asCObjectProperty *prop = builder->GetObjectProperty(ctx->type.dataType, name.AddressOf());
  7512. if( prop )
  7513. {
  7514. // Is the property access allowed?
  7515. if( prop->isPrivate && (!outFunc || outFunc->objectType != ctx->type.dataType.GetObjectType()) )
  7516. {
  7517. asCString msg;
  7518. msg.Format(TXT_PRIVATE_PROP_ACCESS_s, name.AddressOf());
  7519. Error(msg.AddressOf(), node);
  7520. }
  7521. // Put the offset on the stack
  7522. ctx->bc.InstrSHORT_DW(asBC_ADDSi, (short)prop->byteOffset, engine->GetTypeIdFromDataType(asCDataType::CreateObject(ctx->type.dataType.GetObjectType(), false)));
  7523. if( prop->type.IsReference() )
  7524. ctx->bc.Instr(asBC_RDSPtr);
  7525. // Reference to primitive must be stored in the temp register
  7526. if( prop->type.IsPrimitive() )
  7527. {
  7528. ctx->bc.Instr(asBC_PopRPtr);
  7529. }
  7530. // Keep information about temporary variables as deferred expression
  7531. if( ctx->type.isTemporary )
  7532. {
  7533. // Add the release of this reference, as a deferred expression
  7534. asSDeferredParam deferred;
  7535. deferred.origExpr = 0;
  7536. deferred.argInOutFlags = asTM_INREF;
  7537. deferred.argNode = 0;
  7538. deferred.argType.SetVariable(ctx->type.dataType, ctx->type.stackOffset, true);
  7539. ctx->deferredParams.PushLast(deferred);
  7540. }
  7541. // Set the new type and make sure it is not treated as a variable anymore
  7542. ctx->type.dataType = prop->type;
  7543. ctx->type.dataType.MakeReference(true);
  7544. ctx->type.isVariable = false;
  7545. ctx->type.isTemporary = false;
  7546. if( ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle() )
  7547. {
  7548. // Objects that are members are not references
  7549. ctx->type.dataType.MakeReference(false);
  7550. }
  7551. ctx->type.dataType.MakeReadOnly(isConst ? true : prop->type.IsReadOnly());
  7552. }
  7553. else
  7554. {
  7555. asCString str;
  7556. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  7557. Error(str.AddressOf(), node);
  7558. return -1;
  7559. }
  7560. }
  7561. else
  7562. {
  7563. asCString str;
  7564. str.Format(TXT_s_NOT_MEMBER_OF_s, name.AddressOf(), ctx->type.dataType.Format().AddressOf());
  7565. Error(str.AddressOf(), node);
  7566. return -1;
  7567. }
  7568. }
  7569. else
  7570. {
  7571. // Make sure it is an object we are accessing
  7572. if( !ctx->type.dataType.IsObject() )
  7573. {
  7574. asCString str;
  7575. str.Format(TXT_ILLEGAL_OPERATION_ON_s, ctx->type.dataType.Format().AddressOf());
  7576. Error(str.AddressOf(), node);
  7577. return -1;
  7578. }
  7579. // Process the get property accessor
  7580. ProcessPropertyGetAccessor(ctx, node);
  7581. bool isConst = false;
  7582. if( ctx->type.dataType.IsObjectHandle() )
  7583. isConst = ctx->type.dataType.IsHandleToConst();
  7584. else
  7585. isConst = ctx->type.dataType.IsReadOnly();
  7586. asCObjectType *trueObj = ctx->type.dataType.GetObjectType();
  7587. asCTypeInfo objType = ctx->type;
  7588. // Compile function call
  7589. int r = CompileFunctionCall(node->firstChild, ctx, trueObj, isConst);
  7590. if( r < 0 ) return r;
  7591. // If the method returned a reference, then we can't release the original
  7592. // object yet, because the reference may be to a member of it
  7593. if( !objType.isTemporary ||
  7594. !(ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) ||
  7595. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not a member
  7596. {
  7597. // As the method didn't return a reference to a member
  7598. // we can safely release the original object now
  7599. ReleaseTemporaryVariable(objType, &ctx->bc);
  7600. }
  7601. }
  7602. }
  7603. else if( op == ttOpenBracket )
  7604. {
  7605. // If the property access takes an index arg, then we should use that instead of processing it now
  7606. asCString propertyName;
  7607. if( (ctx->property_get && builder->GetFunctionDescription(ctx->property_get)->GetParamCount() == 1) ||
  7608. (ctx->property_set && builder->GetFunctionDescription(ctx->property_set)->GetParamCount() == 2) )
  7609. {
  7610. // Determine the name of the property accessor
  7611. asCScriptFunction *func = 0;
  7612. if( ctx->property_get )
  7613. func = builder->GetFunctionDescription(ctx->property_get);
  7614. else
  7615. func = builder->GetFunctionDescription(ctx->property_set);
  7616. propertyName = func->GetName();
  7617. propertyName = propertyName.SubString(4);
  7618. // Set the original type of the expression so we can re-evaluate the property accessor
  7619. if( func->objectType )
  7620. {
  7621. ctx->type.dataType = asCDataType::CreateObject(func->objectType, ctx->property_const);
  7622. if( ctx->property_handle ) ctx->type.dataType.MakeHandle(true);
  7623. if( ctx->property_ref ) ctx->type.dataType.MakeReference(true);
  7624. }
  7625. ctx->property_get = ctx->property_set = 0;
  7626. if( ctx->property_arg )
  7627. {
  7628. asDELETE(ctx->property_arg, asSExprContext);
  7629. ctx->property_arg = 0;
  7630. }
  7631. }
  7632. else
  7633. {
  7634. if( !ctx->type.dataType.IsObject() )
  7635. {
  7636. asCString str;
  7637. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  7638. Error(str.AddressOf(), node);
  7639. return -1;
  7640. }
  7641. ProcessPropertyGetAccessor(ctx, node);
  7642. }
  7643. Dereference(ctx, true);
  7644. // Compile the expression
  7645. asSExprContext expr(engine);
  7646. CompileAssignment(node->firstChild, &expr);
  7647. // Check for the existence of the opIndex method
  7648. asSExprContext lctx(engine);
  7649. MergeExprBytecodeAndType(&lctx, ctx);
  7650. int r = 0;
  7651. if( propertyName == "" )
  7652. r = CompileOverloadedDualOperator2(node, "opIndex", &lctx, &expr, ctx);
  7653. if( r == 0 )
  7654. {
  7655. // Check for accessors methods for the opIndex
  7656. r = FindPropertyAccessor(propertyName == "" ? "opIndex" : propertyName.AddressOf(), &lctx, &expr, node);
  7657. if( r == 0 )
  7658. {
  7659. asCString str;
  7660. str.Format(TXT_OBJECT_DOESNT_SUPPORT_INDEX_OP, ctx->type.dataType.Format().AddressOf());
  7661. Error(str.AddressOf(), node);
  7662. return -1;
  7663. }
  7664. else if( r < 0 )
  7665. return -1;
  7666. MergeExprBytecodeAndType(ctx, &lctx);
  7667. }
  7668. }
  7669. return 0;
  7670. }
  7671. int asCCompiler::GetPrecedence(asCScriptNode *op)
  7672. {
  7673. // x * y, x / y, x % y
  7674. // x + y, x - y
  7675. // x <= y, x < y, x >= y, x > y
  7676. // x = =y, x != y, x xor y, x is y, x !is y
  7677. // x and y
  7678. // x or y
  7679. // The following are not used in this function,
  7680. // but should have lower precedence than the above
  7681. // x ? y : z
  7682. // x = y
  7683. // The expression term have the highest precedence
  7684. if( op->nodeType == snExprTerm )
  7685. return 1;
  7686. // Evaluate operators by token
  7687. int tokenType = op->tokenType;
  7688. if( tokenType == ttStar || tokenType == ttSlash || tokenType == ttPercent )
  7689. return 0;
  7690. if( tokenType == ttPlus || tokenType == ttMinus )
  7691. return -1;
  7692. if( tokenType == ttBitShiftLeft ||
  7693. tokenType == ttBitShiftRight ||
  7694. tokenType == ttBitShiftRightArith )
  7695. return -2;
  7696. if( tokenType == ttAmp )
  7697. return -3;
  7698. if( tokenType == ttBitXor )
  7699. return -4;
  7700. if( tokenType == ttBitOr )
  7701. return -5;
  7702. if( tokenType == ttLessThanOrEqual ||
  7703. tokenType == ttLessThan ||
  7704. tokenType == ttGreaterThanOrEqual ||
  7705. tokenType == ttGreaterThan )
  7706. return -6;
  7707. if( tokenType == ttEqual || tokenType == ttNotEqual || tokenType == ttXor || tokenType == ttIs || tokenType == ttNotIs )
  7708. return -7;
  7709. if( tokenType == ttAnd )
  7710. return -8;
  7711. if( tokenType == ttOr )
  7712. return -9;
  7713. // Unknown operator
  7714. asASSERT(false);
  7715. return 0;
  7716. }
  7717. asUINT asCCompiler::MatchArgument(asCArray<int> &funcs, asCArray<int> &matches, const asCTypeInfo *argType, int paramNum, bool allowObjectConstruct)
  7718. {
  7719. asUINT bestCost = asUINT(-1);
  7720. matches.SetLength(0);
  7721. for( asUINT n = 0; n < funcs.GetLength(); n++ )
  7722. {
  7723. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[n]);
  7724. // Does the function have arguments enough?
  7725. if( (int)desc->parameterTypes.GetLength() <= paramNum )
  7726. continue;
  7727. // Can we make the match by implicit conversion?
  7728. asSExprContext ti(engine);
  7729. ti.type = *argType;
  7730. if( argType->dataType.IsPrimitive() ) ti.type.dataType.MakeReference(false);
  7731. asUINT cost = ImplicitConversion(&ti, desc->parameterTypes[paramNum], 0, asIC_IMPLICIT_CONV, false, allowObjectConstruct);
  7732. // If the function parameter is an inout-reference then it must not be possible to call the
  7733. // function with an incorrect argument type, even though the type can normally be converted.
  7734. if( desc->parameterTypes[paramNum].IsReference() &&
  7735. desc->inOutFlags[paramNum] == asTM_INOUTREF &&
  7736. desc->parameterTypes[paramNum].GetTokenType() != ttQuestion )
  7737. {
  7738. if( desc->parameterTypes[paramNum].IsPrimitive() &&
  7739. desc->parameterTypes[paramNum].GetTokenType() != argType->dataType.GetTokenType() )
  7740. continue;
  7741. if( desc->parameterTypes[paramNum].IsEnumType() &&
  7742. desc->parameterTypes[paramNum].GetObjectType() != argType->dataType.GetObjectType() )
  7743. continue;
  7744. }
  7745. // How well does the argument match the function parameter?
  7746. if( desc->parameterTypes[paramNum].IsEqualExceptRef(ti.type.dataType) )
  7747. {
  7748. if( cost < bestCost )
  7749. {
  7750. matches.SetLength(0);
  7751. bestCost = cost;
  7752. }
  7753. if( cost == bestCost )
  7754. matches.PushLast(funcs[n]);
  7755. }
  7756. }
  7757. return bestCost;
  7758. }
  7759. void asCCompiler::PrepareArgument2(asSExprContext *ctx, asSExprContext *arg, asCDataType *paramType, bool isFunction, int refType, bool isMakingCopy)
  7760. {
  7761. // Reference parameters whose value won't be used don't evaluate the expression
  7762. if( paramType->IsReference() && !(refType & asTM_INREF) )
  7763. {
  7764. // Store the original bytecode so that it can be reused when processing the deferred output parameter
  7765. asSExprContext *orig = asNEW(asSExprContext)(engine);
  7766. MergeExprBytecodeAndType(orig, arg);
  7767. arg->origExpr = orig;
  7768. }
  7769. PrepareArgument(paramType, arg, arg->exprNode, isFunction, refType, isMakingCopy);
  7770. // arg still holds the original expression for output parameters
  7771. ctx->bc.AddCode(&arg->bc);
  7772. }
  7773. bool asCCompiler::CompileOverloadedDualOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  7774. {
  7775. ctx->exprNode = node;
  7776. // What type of operator is it?
  7777. int token = node->tokenType;
  7778. if( token == ttUnrecognizedToken )
  7779. {
  7780. // This happens when the compiler is inferring an assignment
  7781. // operation from another action, for example in preparing a value
  7782. // as a function argument
  7783. token = ttAssignment;
  7784. }
  7785. // boolean operators are not overloadable
  7786. if( token == ttAnd ||
  7787. token == ttOr ||
  7788. token == ttXor )
  7789. return false;
  7790. // Dual operators can also be implemented as class methods
  7791. if( token == ttEqual ||
  7792. token == ttNotEqual )
  7793. {
  7794. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7795. // Find the matching opEquals method
  7796. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  7797. if( r == 0 )
  7798. {
  7799. // Try again by switching the order of the operands
  7800. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  7801. }
  7802. if( r == 1 )
  7803. {
  7804. if( token == ttNotEqual )
  7805. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  7806. // Success, don't continue
  7807. return true;
  7808. }
  7809. else if( r < 0 )
  7810. {
  7811. // Compiler error, don't continue
  7812. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  7813. return true;
  7814. }
  7815. }
  7816. if( token == ttEqual ||
  7817. token == ttNotEqual ||
  7818. token == ttLessThan ||
  7819. token == ttLessThanOrEqual ||
  7820. token == ttGreaterThan ||
  7821. token == ttGreaterThanOrEqual )
  7822. {
  7823. bool swappedOrder = false;
  7824. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7825. // Find the matching opCmp method
  7826. int r = CompileOverloadedDualOperator2(node, "opCmp", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  7827. if( r == 0 )
  7828. {
  7829. // Try again by switching the order of the operands
  7830. swappedOrder = true;
  7831. r = CompileOverloadedDualOperator2(node, "opCmp", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttInt, false));
  7832. }
  7833. if( r == 1 )
  7834. {
  7835. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  7836. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  7837. ctx->bc.InstrW_DW(asBC_CMPIi, ctx->type.stackOffset, 0);
  7838. if( token == ttEqual )
  7839. ctx->bc.Instr(asBC_TZ);
  7840. else if( token == ttNotEqual )
  7841. ctx->bc.Instr(asBC_TNZ);
  7842. else if( (token == ttLessThan && !swappedOrder) ||
  7843. (token == ttGreaterThan && swappedOrder) )
  7844. ctx->bc.Instr(asBC_TS);
  7845. else if( (token == ttLessThanOrEqual && !swappedOrder) ||
  7846. (token == ttGreaterThanOrEqual && swappedOrder) )
  7847. ctx->bc.Instr(asBC_TNP);
  7848. else if( (token == ttGreaterThan && !swappedOrder) ||
  7849. (token == ttLessThan && swappedOrder) )
  7850. ctx->bc.Instr(asBC_TP);
  7851. else if( (token == ttGreaterThanOrEqual && !swappedOrder) ||
  7852. (token == ttLessThanOrEqual && swappedOrder) )
  7853. ctx->bc.Instr(asBC_TNS);
  7854. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  7855. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), a, true);
  7856. // Success, don't continue
  7857. return true;
  7858. }
  7859. else if( r < 0 )
  7860. {
  7861. // Compiler error, don't continue
  7862. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  7863. return true;
  7864. }
  7865. }
  7866. // The rest of the operators are not commutative, and doesn't require specific return type
  7867. const char *op = 0, *op_r = 0;
  7868. switch( token )
  7869. {
  7870. case ttPlus: op = "opAdd"; op_r = "opAdd_r"; break;
  7871. case ttMinus: op = "opSub"; op_r = "opSub_r"; break;
  7872. case ttStar: op = "opMul"; op_r = "opMul_r"; break;
  7873. case ttSlash: op = "opDiv"; op_r = "opDiv_r"; break;
  7874. case ttPercent: op = "opMod"; op_r = "opMod_r"; break;
  7875. case ttBitOr: op = "opOr"; op_r = "opOr_r"; break;
  7876. case ttAmp: op = "opAnd"; op_r = "opAnd_r"; break;
  7877. case ttBitXor: op = "opXor"; op_r = "opXor_r"; break;
  7878. case ttBitShiftLeft: op = "opShl"; op_r = "opShl_r"; break;
  7879. case ttBitShiftRight: op = "opShr"; op_r = "opShr_r"; break;
  7880. case ttBitShiftRightArith: op = "opUShr"; op_r = "opUShr_r"; break;
  7881. }
  7882. // TODO: Might be interesting to support a concatenation operator, e.g. ~
  7883. if( op && op_r )
  7884. {
  7885. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  7886. // Find the matching operator method
  7887. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  7888. if( r == 0 )
  7889. {
  7890. // Try again by switching the order of the operands, and using the reversed operator
  7891. r = CompileOverloadedDualOperator2(node, op_r, rctx, lctx, ctx);
  7892. }
  7893. if( r == 1 )
  7894. {
  7895. // Success, don't continue
  7896. return true;
  7897. }
  7898. else if( r < 0 )
  7899. {
  7900. // Compiler error, don't continue
  7901. ctx->type.SetDummy();
  7902. return true;
  7903. }
  7904. }
  7905. // Assignment operators
  7906. op = 0;
  7907. switch( token )
  7908. {
  7909. case ttAssignment: op = "opAssign"; break;
  7910. case ttAddAssign: op = "opAddAssign"; break;
  7911. case ttSubAssign: op = "opSubAssign"; break;
  7912. case ttMulAssign: op = "opMulAssign"; break;
  7913. case ttDivAssign: op = "opDivAssign"; break;
  7914. case ttModAssign: op = "opModAssign"; break;
  7915. case ttOrAssign: op = "opOrAssign"; break;
  7916. case ttAndAssign: op = "opAndAssign"; break;
  7917. case ttXorAssign: op = "opXorAssign"; break;
  7918. case ttShiftLeftAssign: op = "opShlAssign"; break;
  7919. case ttShiftRightLAssign: op = "opShrAssign"; break;
  7920. case ttShiftRightAAssign: op = "opUShrAssign"; break;
  7921. }
  7922. if( op )
  7923. {
  7924. // TODO: Shouldn't accept const lvalue with the assignment operators
  7925. // Find the matching operator method
  7926. int r = CompileOverloadedDualOperator2(node, op, lctx, rctx, ctx);
  7927. if( r == 1 )
  7928. {
  7929. // Success, don't continue
  7930. return true;
  7931. }
  7932. else if( r < 0 )
  7933. {
  7934. // Compiler error, don't continue
  7935. ctx->type.SetDummy();
  7936. return true;
  7937. }
  7938. }
  7939. // No suitable operator was found
  7940. return false;
  7941. }
  7942. // Returns negative on compile error
  7943. // zero on no matching operator
  7944. // one on matching operator
  7945. int asCCompiler::CompileOverloadedDualOperator2(asCScriptNode *node, const char *methodName, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx, bool specificReturn, const asCDataType &returnType)
  7946. {
  7947. // Find the matching method
  7948. if( lctx->type.dataType.IsObject() &&
  7949. (!lctx->type.isExplicitHandle ||
  7950. lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE) )
  7951. {
  7952. // Is the left value a const?
  7953. bool isConst = false;
  7954. if( lctx->type.dataType.IsObjectHandle() )
  7955. isConst = lctx->type.dataType.IsHandleToConst();
  7956. else
  7957. isConst = lctx->type.dataType.IsReadOnly();
  7958. asCArray<int> funcs;
  7959. asCObjectType *ot = lctx->type.dataType.GetObjectType();
  7960. for( asUINT n = 0; n < ot->methods.GetLength(); n++ )
  7961. {
  7962. asCScriptFunction *func = engine->scriptFunctions[ot->methods[n]];
  7963. if( func->name == methodName &&
  7964. (!specificReturn || func->returnType == returnType) &&
  7965. func->parameterTypes.GetLength() == 1 &&
  7966. (!isConst || func->isReadOnly) )
  7967. {
  7968. // Make sure the method is accessible by the module
  7969. if( builder->module->accessMask & func->accessMask )
  7970. {
  7971. funcs.PushLast(func->id);
  7972. }
  7973. }
  7974. }
  7975. // Which is the best matching function?
  7976. asCArray<int> ops;
  7977. MatchArgument(funcs, ops, &rctx->type, 0);
  7978. // If the object is not const, then we need to prioritize non-const methods
  7979. if( !isConst )
  7980. FilterConst(ops);
  7981. // Did we find an operator?
  7982. if( ops.GetLength() == 1 )
  7983. {
  7984. // Process the lctx expression as get accessor
  7985. ProcessPropertyGetAccessor(lctx, node);
  7986. // Merge the bytecode so that it forms lvalue.methodName(rvalue)
  7987. asCTypeInfo objType = lctx->type;
  7988. asCArray<asSExprContext *> args;
  7989. args.PushLast(rctx);
  7990. MergeExprBytecode(ctx, lctx);
  7991. ctx->type = lctx->type;
  7992. MakeFunctionCall(ctx, ops[0], objType.dataType.GetObjectType(), args, node);
  7993. // If the method returned a reference, then we can't release the original
  7994. // object yet, because the reference may be to a member of it
  7995. if( !objType.isTemporary ||
  7996. !(ctx->type.dataType.IsReference() || (ctx->type.dataType.IsObject() && !ctx->type.dataType.IsObjectHandle())) ||
  7997. ctx->type.isVariable ) // If the resulting type is a variable, then the reference is not to a member
  7998. {
  7999. // As the index operator didn't return a reference to a
  8000. // member we can release the original object now
  8001. ReleaseTemporaryVariable(objType, &ctx->bc);
  8002. }
  8003. // Found matching operator
  8004. return 1;
  8005. }
  8006. else if( ops.GetLength() > 1 )
  8007. {
  8008. Error(TXT_MORE_THAN_ONE_MATCHING_OP, node);
  8009. PrintMatchingFuncs(ops, node);
  8010. ctx->type.SetDummy();
  8011. // Compiler error
  8012. return -1;
  8013. }
  8014. }
  8015. // No matching operator
  8016. return 0;
  8017. }
  8018. void asCCompiler::MakeFunctionCall(asSExprContext *ctx, int funcId, asCObjectType *objectType, asCArray<asSExprContext*> &args, asCScriptNode * /*node*/, bool useVariable, int stackOffset, int funcPtrVar)
  8019. {
  8020. if( objectType )
  8021. {
  8022. Dereference(ctx, true);
  8023. // This following warning was removed as there may be valid reasons
  8024. // for calling non-const methods on temporary objects, and we shouldn't
  8025. // warn when there is no way of removing the warning.
  8026. /*
  8027. // Warn if the method is non-const and the object is temporary
  8028. // since the changes will be lost when the object is destroyed.
  8029. // If the object is accessed through a handle, then it is assumed
  8030. // the object is not temporary, even though the handle is.
  8031. if( ctx->type.isTemporary &&
  8032. !ctx->type.dataType.IsObjectHandle() &&
  8033. !engine->scriptFunctions[funcId]->isReadOnly )
  8034. {
  8035. Warning("A non-const method is called on temporary object. Changes to the object may be lost.", node);
  8036. Information(engine->scriptFunctions[funcId]->GetDeclaration(), node);
  8037. }
  8038. */ }
  8039. asCByteCode objBC(engine);
  8040. objBC.AddCode(&ctx->bc);
  8041. PrepareFunctionCall(funcId, &ctx->bc, args);
  8042. // Verify if any of the args variable offsets are used in the other code.
  8043. // If they are exchange the offset for a new one
  8044. asUINT n;
  8045. for( n = 0; n < args.GetLength(); n++ )
  8046. {
  8047. if( args[n]->type.isTemporary && objBC.IsVarUsed(args[n]->type.stackOffset) )
  8048. {
  8049. // Release the current temporary variable
  8050. ReleaseTemporaryVariable(args[n]->type, 0);
  8051. asCDataType dt = args[n]->type.dataType;
  8052. dt.MakeReference(false);
  8053. int l = int(reservedVariables.GetLength());
  8054. objBC.GetVarsUsed(reservedVariables);
  8055. ctx->bc.GetVarsUsed(reservedVariables);
  8056. int newOffset = AllocateVariable(dt, true, IsVariableOnHeap(args[n]->type.stackOffset));
  8057. reservedVariables.SetLength(l);
  8058. asASSERT( IsVariableOnHeap(args[n]->type.stackOffset) == IsVariableOnHeap(newOffset) );
  8059. ctx->bc.ExchangeVar(args[n]->type.stackOffset, newOffset);
  8060. args[n]->type.stackOffset = (short)newOffset;
  8061. args[n]->type.isTemporary = true;
  8062. args[n]->type.isVariable = true;
  8063. }
  8064. }
  8065. // If the function will return a value type on the stack, then we must allocate space
  8066. // for that here and push the address on the stack as a hidden argument to the function
  8067. asCScriptFunction *func = builder->GetFunctionDescription(funcId);
  8068. if( func->DoesReturnOnStack() )
  8069. {
  8070. asASSERT(!useVariable);
  8071. useVariable = true;
  8072. stackOffset = AllocateVariable(func->returnType, true);
  8073. ctx->bc.InstrSHORT(asBC_PSF, short(stackOffset));
  8074. }
  8075. ctx->bc.AddCode(&objBC);
  8076. MoveArgsToStack(funcId, &ctx->bc, args, objectType ? true : false);
  8077. PerformFunctionCall(funcId, ctx, false, &args, 0, useVariable, stackOffset, funcPtrVar);
  8078. }
  8079. int asCCompiler::CompileOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8080. {
  8081. IsVariableInitialized(&lctx->type, node);
  8082. IsVariableInitialized(&rctx->type, node);
  8083. if( lctx->type.isExplicitHandle || rctx->type.isExplicitHandle ||
  8084. node->tokenType == ttIs || node->tokenType == ttNotIs )
  8085. {
  8086. CompileOperatorOnHandles(node, lctx, rctx, ctx);
  8087. return 0;
  8088. }
  8089. else
  8090. {
  8091. // Compile an overloaded operator for the two operands
  8092. if( CompileOverloadedDualOperator(node, lctx, rctx, ctx) )
  8093. return 0;
  8094. // If both operands are objects, then we shouldn't continue
  8095. if( lctx->type.dataType.IsObject() && rctx->type.dataType.IsObject() )
  8096. {
  8097. asCString str;
  8098. str.Format(TXT_NO_MATCHING_OP_FOUND_FOR_TYPES_s_AND_s, lctx->type.dataType.Format().AddressOf(), rctx->type.dataType.Format().AddressOf());
  8099. Error(str.AddressOf(), node);
  8100. ctx->type.SetDummy();
  8101. return -1;
  8102. }
  8103. // Process the property get accessors (if any)
  8104. ProcessPropertyGetAccessor(lctx, node);
  8105. ProcessPropertyGetAccessor(rctx, node);
  8106. // Make sure we have two variables or constants
  8107. if( lctx->type.dataType.IsReference() ) ConvertToVariableNotIn(lctx, rctx);
  8108. if( rctx->type.dataType.IsReference() ) ConvertToVariableNotIn(rctx, lctx);
  8109. // Make sure lctx doesn't end up with a variable used in rctx
  8110. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  8111. {
  8112. int offset = AllocateVariableNotIn(lctx->type.dataType, true, false, rctx);
  8113. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  8114. ReleaseTemporaryVariable(offset, 0);
  8115. }
  8116. // Math operators
  8117. // + - * / % += -= *= /= %=
  8118. int op = node->tokenType;
  8119. if( op == ttPlus || op == ttAddAssign ||
  8120. op == ttMinus || op == ttSubAssign ||
  8121. op == ttStar || op == ttMulAssign ||
  8122. op == ttSlash || op == ttDivAssign ||
  8123. op == ttPercent || op == ttModAssign )
  8124. {
  8125. CompileMathOperator(node, lctx, rctx, ctx);
  8126. return 0;
  8127. }
  8128. // Bitwise operators
  8129. // << >> >>> & | ^ <<= >>= >>>= &= |= ^=
  8130. if( op == ttAmp || op == ttAndAssign ||
  8131. op == ttBitOr || op == ttOrAssign ||
  8132. op == ttBitXor || op == ttXorAssign ||
  8133. op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  8134. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  8135. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8136. {
  8137. CompileBitwiseOperator(node, lctx, rctx, ctx);
  8138. return 0;
  8139. }
  8140. // Comparison operators
  8141. // == != < > <= >=
  8142. if( op == ttEqual || op == ttNotEqual ||
  8143. op == ttLessThan || op == ttLessThanOrEqual ||
  8144. op == ttGreaterThan || op == ttGreaterThanOrEqual )
  8145. {
  8146. CompileComparisonOperator(node, lctx, rctx, ctx);
  8147. return 0;
  8148. }
  8149. // Boolean operators
  8150. // && || ^^
  8151. if( op == ttAnd || op == ttOr || op == ttXor )
  8152. {
  8153. CompileBooleanOperator(node, lctx, rctx, ctx);
  8154. return 0;
  8155. }
  8156. }
  8157. asASSERT(false);
  8158. return -1;
  8159. }
  8160. void asCCompiler::ConvertToTempVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  8161. {
  8162. int l = int(reservedVariables.GetLength());
  8163. if( exclude ) exclude->bc.GetVarsUsed(reservedVariables);
  8164. ConvertToTempVariable(ctx);
  8165. reservedVariables.SetLength(l);
  8166. }
  8167. void asCCompiler::ConvertToTempVariable(asSExprContext *ctx)
  8168. {
  8169. // This is only used for primitive types and null handles
  8170. asASSERT( ctx->type.dataType.IsPrimitive() || ctx->type.dataType.IsNullHandle() );
  8171. ConvertToVariable(ctx);
  8172. if( !ctx->type.isTemporary )
  8173. {
  8174. if( ctx->type.dataType.IsPrimitive() )
  8175. {
  8176. // Copy the variable to a temporary variable
  8177. int offset = AllocateVariable(ctx->type.dataType, true);
  8178. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8179. ctx->bc.InstrW_W(asBC_CpyVtoV4, offset, ctx->type.stackOffset);
  8180. else
  8181. ctx->bc.InstrW_W(asBC_CpyVtoV8, offset, ctx->type.stackOffset);
  8182. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8183. }
  8184. else
  8185. {
  8186. // We should never get here
  8187. asASSERT(false);
  8188. }
  8189. }
  8190. }
  8191. void asCCompiler::ConvertToVariable(asSExprContext *ctx)
  8192. {
  8193. // We should never get here while the context is still an unprocessed property accessor
  8194. asASSERT(ctx->property_get == 0 && ctx->property_set == 0);
  8195. int offset;
  8196. if( !ctx->type.isVariable &&
  8197. (ctx->type.dataType.IsObjectHandle() ||
  8198. (ctx->type.dataType.IsObject() && ctx->type.dataType.SupportHandles())) )
  8199. {
  8200. offset = AllocateVariable(ctx->type.dataType, true);
  8201. if( ctx->type.IsNullConstant() )
  8202. {
  8203. if( ctx->bc.GetLastInstr() == asBC_PshNull )
  8204. ctx->bc.Pop(AS_PTR_SIZE); // Pop the null constant pushed onto the stack
  8205. ctx->bc.InstrSHORT(asBC_ClrVPtr, (short)offset);
  8206. }
  8207. else
  8208. {
  8209. // Copy the object handle to a variable
  8210. ctx->bc.InstrSHORT(asBC_PSF, (short)offset);
  8211. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  8212. ctx->bc.Pop(AS_PTR_SIZE);
  8213. }
  8214. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  8215. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8216. ctx->type.dataType.MakeHandle(true);
  8217. }
  8218. else if( (!ctx->type.isVariable || ctx->type.dataType.IsReference()) &&
  8219. ctx->type.dataType.IsPrimitive() )
  8220. {
  8221. if( ctx->type.isConstant )
  8222. {
  8223. offset = AllocateVariable(ctx->type.dataType, true);
  8224. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  8225. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, ctx->type.byteValue);
  8226. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  8227. ctx->bc.InstrSHORT_W(asBC_SetV2, (short)offset, ctx->type.wordValue);
  8228. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 4 )
  8229. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, ctx->type.dwordValue);
  8230. else
  8231. ctx->bc.InstrSHORT_QW(asBC_SetV8, (short)offset, ctx->type.qwordValue);
  8232. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8233. return;
  8234. }
  8235. else
  8236. {
  8237. asASSERT(ctx->type.dataType.IsPrimitive());
  8238. asASSERT(ctx->type.dataType.IsReference());
  8239. ctx->type.dataType.MakeReference(false);
  8240. offset = AllocateVariable(ctx->type.dataType, true);
  8241. // Read the value from the address in the register directly into the variable
  8242. if( ctx->type.dataType.GetSizeInMemoryBytes() == 1 )
  8243. ctx->bc.InstrSHORT(asBC_RDR1, (short)offset);
  8244. else if( ctx->type.dataType.GetSizeInMemoryBytes() == 2 )
  8245. ctx->bc.InstrSHORT(asBC_RDR2, (short)offset);
  8246. else if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8247. ctx->bc.InstrSHORT(asBC_RDR4, (short)offset);
  8248. else
  8249. ctx->bc.InstrSHORT(asBC_RDR8, (short)offset);
  8250. }
  8251. ReleaseTemporaryVariable(ctx->type, &ctx->bc);
  8252. ctx->type.SetVariable(ctx->type.dataType, offset, true);
  8253. }
  8254. }
  8255. void asCCompiler::ConvertToVariableNotIn(asSExprContext *ctx, asSExprContext *exclude)
  8256. {
  8257. int l = int(reservedVariables.GetLength());
  8258. if( exclude ) exclude->bc.GetVarsUsed(reservedVariables);
  8259. ConvertToVariable(ctx);
  8260. reservedVariables.SetLength(l);
  8261. }
  8262. void asCCompiler::CompileMathOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8263. {
  8264. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  8265. // Implicitly convert the operands to a number type
  8266. asCDataType to;
  8267. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  8268. to.SetTokenType(ttDouble);
  8269. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  8270. to.SetTokenType(ttFloat);
  8271. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8272. {
  8273. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() )
  8274. to.SetTokenType(ttInt64);
  8275. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8276. to.SetTokenType(ttUInt64);
  8277. }
  8278. else
  8279. {
  8280. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() ||
  8281. lctx->type.dataType.IsEnumType() || rctx->type.dataType.IsEnumType() )
  8282. to.SetTokenType(ttInt);
  8283. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8284. to.SetTokenType(ttUInt);
  8285. }
  8286. // If doing an operation with double constant and float variable, the constant should be converted to float
  8287. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  8288. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  8289. to.SetTokenType(ttFloat);
  8290. // Do the actual conversion
  8291. int l = int(reservedVariables.GetLength());
  8292. rctx->bc.GetVarsUsed(reservedVariables);
  8293. lctx->bc.GetVarsUsed(reservedVariables);
  8294. if( lctx->type.dataType.IsReference() )
  8295. ConvertToVariable(lctx);
  8296. if( rctx->type.dataType.IsReference() )
  8297. ConvertToVariable(rctx);
  8298. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  8299. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV, true);
  8300. reservedVariables.SetLength(l);
  8301. // Verify that the conversion was successful
  8302. if( !lctx->type.dataType.IsIntegerType() &&
  8303. !lctx->type.dataType.IsUnsignedType() &&
  8304. !lctx->type.dataType.IsFloatType() &&
  8305. !lctx->type.dataType.IsDoubleType() )
  8306. {
  8307. asCString str;
  8308. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, lctx->type.dataType.Format().AddressOf());
  8309. Error(str.AddressOf(), node);
  8310. ctx->type.SetDummy();
  8311. return;
  8312. }
  8313. if( !rctx->type.dataType.IsIntegerType() &&
  8314. !rctx->type.dataType.IsUnsignedType() &&
  8315. !rctx->type.dataType.IsFloatType() &&
  8316. !rctx->type.dataType.IsDoubleType() )
  8317. {
  8318. asCString str;
  8319. str.Format(TXT_NO_CONVERSION_s_TO_MATH_TYPE, rctx->type.dataType.Format().AddressOf());
  8320. Error(str.AddressOf(), node);
  8321. ctx->type.SetDummy();
  8322. return;
  8323. }
  8324. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8325. // Verify if we are dividing with a constant zero
  8326. int op = node->tokenType;
  8327. if( rctx->type.isConstant && rctx->type.qwordValue == 0 &&
  8328. (op == ttSlash || op == ttDivAssign ||
  8329. op == ttPercent || op == ttModAssign) )
  8330. {
  8331. Error(TXT_DIVIDE_BY_ZERO, node);
  8332. }
  8333. if( !isConstant )
  8334. {
  8335. ConvertToVariableNotIn(lctx, rctx);
  8336. ConvertToVariableNotIn(rctx, lctx);
  8337. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8338. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8339. if( op == ttAddAssign || op == ttSubAssign ||
  8340. op == ttMulAssign || op == ttDivAssign ||
  8341. op == ttModAssign )
  8342. {
  8343. // Merge the operands in the different order so that they are evaluated correctly
  8344. MergeExprBytecode(ctx, rctx);
  8345. MergeExprBytecode(ctx, lctx);
  8346. }
  8347. else
  8348. {
  8349. MergeExprBytecode(ctx, lctx);
  8350. MergeExprBytecode(ctx, rctx);
  8351. }
  8352. ProcessDeferredParams(ctx);
  8353. asEBCInstr instruction = asBC_ADDi;
  8354. if( lctx->type.dataType.IsIntegerType() ||
  8355. lctx->type.dataType.IsUnsignedType() )
  8356. {
  8357. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8358. {
  8359. if( op == ttPlus || op == ttAddAssign )
  8360. instruction = asBC_ADDi;
  8361. else if( op == ttMinus || op == ttSubAssign )
  8362. instruction = asBC_SUBi;
  8363. else if( op == ttStar || op == ttMulAssign )
  8364. instruction = asBC_MULi;
  8365. else if( op == ttSlash || op == ttDivAssign )
  8366. {
  8367. if( lctx->type.dataType.IsIntegerType() )
  8368. instruction = asBC_DIVi;
  8369. else
  8370. instruction = asBC_DIVu;
  8371. }
  8372. else if( op == ttPercent || op == ttModAssign )
  8373. {
  8374. if( lctx->type.dataType.IsIntegerType() )
  8375. instruction = asBC_MODi;
  8376. else
  8377. instruction = asBC_MODu;
  8378. }
  8379. }
  8380. else
  8381. {
  8382. if( op == ttPlus || op == ttAddAssign )
  8383. instruction = asBC_ADDi64;
  8384. else if( op == ttMinus || op == ttSubAssign )
  8385. instruction = asBC_SUBi64;
  8386. else if( op == ttStar || op == ttMulAssign )
  8387. instruction = asBC_MULi64;
  8388. else if( op == ttSlash || op == ttDivAssign )
  8389. {
  8390. if( lctx->type.dataType.IsIntegerType() )
  8391. instruction = asBC_DIVi64;
  8392. else
  8393. instruction = asBC_DIVu64;
  8394. }
  8395. else if( op == ttPercent || op == ttModAssign )
  8396. {
  8397. if( lctx->type.dataType.IsIntegerType() )
  8398. instruction = asBC_MODi64;
  8399. else
  8400. instruction = asBC_MODu64;
  8401. }
  8402. }
  8403. }
  8404. else if( lctx->type.dataType.IsFloatType() )
  8405. {
  8406. if( op == ttPlus || op == ttAddAssign )
  8407. instruction = asBC_ADDf;
  8408. else if( op == ttMinus || op == ttSubAssign )
  8409. instruction = asBC_SUBf;
  8410. else if( op == ttStar || op == ttMulAssign )
  8411. instruction = asBC_MULf;
  8412. else if( op == ttSlash || op == ttDivAssign )
  8413. instruction = asBC_DIVf;
  8414. else if( op == ttPercent || op == ttModAssign )
  8415. instruction = asBC_MODf;
  8416. }
  8417. else if( lctx->type.dataType.IsDoubleType() )
  8418. {
  8419. if( op == ttPlus || op == ttAddAssign )
  8420. instruction = asBC_ADDd;
  8421. else if( op == ttMinus || op == ttSubAssign )
  8422. instruction = asBC_SUBd;
  8423. else if( op == ttStar || op == ttMulAssign )
  8424. instruction = asBC_MULd;
  8425. else if( op == ttSlash || op == ttDivAssign )
  8426. instruction = asBC_DIVd;
  8427. else if( op == ttPercent || op == ttModAssign )
  8428. instruction = asBC_MODd;
  8429. }
  8430. else
  8431. {
  8432. // Shouldn't be possible
  8433. asASSERT(false);
  8434. }
  8435. // Do the operation
  8436. int a = AllocateVariable(lctx->type.dataType, true);
  8437. int b = lctx->type.stackOffset;
  8438. int c = rctx->type.stackOffset;
  8439. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8440. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8441. }
  8442. else
  8443. {
  8444. // Both values are constants
  8445. if( lctx->type.dataType.IsIntegerType() ||
  8446. lctx->type.dataType.IsUnsignedType() )
  8447. {
  8448. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8449. {
  8450. int v = 0;
  8451. if( op == ttPlus )
  8452. v = lctx->type.intValue + rctx->type.intValue;
  8453. else if( op == ttMinus )
  8454. v = lctx->type.intValue - rctx->type.intValue;
  8455. else if( op == ttStar )
  8456. v = lctx->type.intValue * rctx->type.intValue;
  8457. else if( op == ttSlash )
  8458. {
  8459. if( rctx->type.intValue == 0 )
  8460. v = 0;
  8461. else
  8462. if( lctx->type.dataType.IsIntegerType() )
  8463. v = lctx->type.intValue / rctx->type.intValue;
  8464. else
  8465. v = lctx->type.dwordValue / rctx->type.dwordValue;
  8466. }
  8467. else if( op == ttPercent )
  8468. {
  8469. if( rctx->type.intValue == 0 )
  8470. v = 0;
  8471. else
  8472. if( lctx->type.dataType.IsIntegerType() )
  8473. v = lctx->type.intValue % rctx->type.intValue;
  8474. else
  8475. v = lctx->type.dwordValue % rctx->type.dwordValue;
  8476. }
  8477. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8478. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  8479. if( lctx->type.dataType.GetTokenType() == ttUInt && op == ttMinus && lctx->type.intValue < rctx->type.intValue )
  8480. ctx->type.dataType.SetTokenType(ttInt);
  8481. }
  8482. else
  8483. {
  8484. asQWORD v = 0;
  8485. if( op == ttPlus )
  8486. v = lctx->type.qwordValue + rctx->type.qwordValue;
  8487. else if( op == ttMinus )
  8488. v = lctx->type.qwordValue - rctx->type.qwordValue;
  8489. else if( op == ttStar )
  8490. v = lctx->type.qwordValue * rctx->type.qwordValue;
  8491. else if( op == ttSlash )
  8492. {
  8493. if( rctx->type.qwordValue == 0 )
  8494. v = 0;
  8495. else
  8496. if( lctx->type.dataType.IsIntegerType() )
  8497. v = asINT64(lctx->type.qwordValue) / asINT64(rctx->type.qwordValue);
  8498. else
  8499. v = lctx->type.qwordValue / rctx->type.qwordValue;
  8500. }
  8501. else if( op == ttPercent )
  8502. {
  8503. if( rctx->type.qwordValue == 0 )
  8504. v = 0;
  8505. else
  8506. if( lctx->type.dataType.IsIntegerType() )
  8507. v = asINT64(lctx->type.qwordValue) % asINT64(rctx->type.qwordValue);
  8508. else
  8509. v = lctx->type.qwordValue % rctx->type.qwordValue;
  8510. }
  8511. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8512. // If the right value is greater than the left value in a minus operation, then we need to convert the type to int
  8513. if( lctx->type.dataType.GetTokenType() == ttUInt64 && op == ttMinus && lctx->type.qwordValue < rctx->type.qwordValue )
  8514. ctx->type.dataType.SetTokenType(ttInt64);
  8515. }
  8516. }
  8517. else if( lctx->type.dataType.IsFloatType() )
  8518. {
  8519. float v = 0.0f;
  8520. if( op == ttPlus )
  8521. v = lctx->type.floatValue + rctx->type.floatValue;
  8522. else if( op == ttMinus )
  8523. v = lctx->type.floatValue - rctx->type.floatValue;
  8524. else if( op == ttStar )
  8525. v = lctx->type.floatValue * rctx->type.floatValue;
  8526. else if( op == ttSlash )
  8527. {
  8528. if( rctx->type.floatValue == 0 )
  8529. v = 0;
  8530. else
  8531. v = lctx->type.floatValue / rctx->type.floatValue;
  8532. }
  8533. else if( op == ttPercent )
  8534. {
  8535. if( rctx->type.floatValue == 0 )
  8536. v = 0;
  8537. else
  8538. v = fmodf(lctx->type.floatValue, rctx->type.floatValue);
  8539. }
  8540. ctx->type.SetConstantF(lctx->type.dataType, v);
  8541. }
  8542. else if( lctx->type.dataType.IsDoubleType() )
  8543. {
  8544. double v = 0.0;
  8545. if( op == ttPlus )
  8546. v = lctx->type.doubleValue + rctx->type.doubleValue;
  8547. else if( op == ttMinus )
  8548. v = lctx->type.doubleValue - rctx->type.doubleValue;
  8549. else if( op == ttStar )
  8550. v = lctx->type.doubleValue * rctx->type.doubleValue;
  8551. else if( op == ttSlash )
  8552. {
  8553. if( rctx->type.doubleValue == 0 )
  8554. v = 0;
  8555. else
  8556. v = lctx->type.doubleValue / rctx->type.doubleValue;
  8557. }
  8558. else if( op == ttPercent )
  8559. {
  8560. if( rctx->type.doubleValue == 0 )
  8561. v = 0;
  8562. else
  8563. v = fmod(lctx->type.doubleValue, rctx->type.doubleValue);
  8564. }
  8565. ctx->type.SetConstantD(lctx->type.dataType, v);
  8566. }
  8567. else
  8568. {
  8569. // Shouldn't be possible
  8570. asASSERT(false);
  8571. }
  8572. }
  8573. }
  8574. void asCCompiler::CompileBitwiseOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8575. {
  8576. // TODO: If a constant is only using 32bits, then a 32bit operation is preferred
  8577. int op = node->tokenType;
  8578. if( op == ttAmp || op == ttAndAssign ||
  8579. op == ttBitOr || op == ttOrAssign ||
  8580. op == ttBitXor || op == ttXorAssign )
  8581. {
  8582. // Convert left hand operand to integer if it's not already one
  8583. asCDataType to;
  8584. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 ||
  8585. rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8586. to.SetTokenType(ttUInt64);
  8587. else
  8588. to.SetTokenType(ttUInt);
  8589. // Do the actual conversion
  8590. int l = int(reservedVariables.GetLength());
  8591. rctx->bc.GetVarsUsed(reservedVariables);
  8592. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  8593. reservedVariables.SetLength(l);
  8594. // Verify that the conversion was successful
  8595. if( !lctx->type.dataType.IsUnsignedType() )
  8596. {
  8597. asCString str;
  8598. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8599. Error(str.AddressOf(), node);
  8600. }
  8601. // Convert right hand operand to same type as left hand operand
  8602. l = int(reservedVariables.GetLength());
  8603. lctx->bc.GetVarsUsed(reservedVariables);
  8604. ImplicitConversion(rctx, lctx->type.dataType, node, asIC_IMPLICIT_CONV, true);
  8605. reservedVariables.SetLength(l);
  8606. if( !rctx->type.dataType.IsEqualExceptRef(lctx->type.dataType) )
  8607. {
  8608. asCString str;
  8609. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), lctx->type.dataType.Format().AddressOf());
  8610. Error(str.AddressOf(), node);
  8611. }
  8612. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8613. if( !isConstant )
  8614. {
  8615. ConvertToVariableNotIn(lctx, rctx);
  8616. ConvertToVariableNotIn(rctx, lctx);
  8617. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8618. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8619. if( op == ttAndAssign || op == ttOrAssign || op == ttXorAssign )
  8620. {
  8621. // Compound assignments execute the right hand value first
  8622. MergeExprBytecode(ctx, rctx);
  8623. MergeExprBytecode(ctx, lctx);
  8624. }
  8625. else
  8626. {
  8627. MergeExprBytecode(ctx, lctx);
  8628. MergeExprBytecode(ctx, rctx);
  8629. }
  8630. ProcessDeferredParams(ctx);
  8631. asEBCInstr instruction = asBC_BAND;
  8632. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8633. {
  8634. if( op == ttAmp || op == ttAndAssign )
  8635. instruction = asBC_BAND;
  8636. else if( op == ttBitOr || op == ttOrAssign )
  8637. instruction = asBC_BOR;
  8638. else if( op == ttBitXor || op == ttXorAssign )
  8639. instruction = asBC_BXOR;
  8640. }
  8641. else
  8642. {
  8643. if( op == ttAmp || op == ttAndAssign )
  8644. instruction = asBC_BAND64;
  8645. else if( op == ttBitOr || op == ttOrAssign )
  8646. instruction = asBC_BOR64;
  8647. else if( op == ttBitXor || op == ttXorAssign )
  8648. instruction = asBC_BXOR64;
  8649. }
  8650. // Do the operation
  8651. int a = AllocateVariable(lctx->type.dataType, true);
  8652. int b = lctx->type.stackOffset;
  8653. int c = rctx->type.stackOffset;
  8654. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8655. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8656. }
  8657. else
  8658. {
  8659. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8660. {
  8661. asQWORD v = 0;
  8662. if( op == ttAmp )
  8663. v = lctx->type.qwordValue & rctx->type.qwordValue;
  8664. else if( op == ttBitOr )
  8665. v = lctx->type.qwordValue | rctx->type.qwordValue;
  8666. else if( op == ttBitXor )
  8667. v = lctx->type.qwordValue ^ rctx->type.qwordValue;
  8668. // Remember the result
  8669. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8670. }
  8671. else
  8672. {
  8673. asDWORD v = 0;
  8674. if( op == ttAmp )
  8675. v = lctx->type.dwordValue & rctx->type.dwordValue;
  8676. else if( op == ttBitOr )
  8677. v = lctx->type.dwordValue | rctx->type.dwordValue;
  8678. else if( op == ttBitXor )
  8679. v = lctx->type.dwordValue ^ rctx->type.dwordValue;
  8680. // Remember the result
  8681. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8682. }
  8683. }
  8684. }
  8685. else if( op == ttBitShiftLeft || op == ttShiftLeftAssign ||
  8686. op == ttBitShiftRight || op == ttShiftRightLAssign ||
  8687. op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8688. {
  8689. // Don't permit object to primitive conversion, since we don't know which integer type is the correct one
  8690. if( lctx->type.dataType.IsObject() )
  8691. {
  8692. asCString str;
  8693. str.Format(TXT_ILLEGAL_OPERATION_ON_s, lctx->type.dataType.Format().AddressOf());
  8694. Error(str.AddressOf(), node);
  8695. // Set an integer value and allow the compiler to continue
  8696. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttInt, true), 0);
  8697. return;
  8698. }
  8699. // Convert left hand operand to integer if it's not already one
  8700. asCDataType to = lctx->type.dataType;
  8701. if( lctx->type.dataType.IsUnsignedType() &&
  8702. lctx->type.dataType.GetSizeInMemoryBytes() < 4 )
  8703. {
  8704. to = asCDataType::CreatePrimitive(ttUInt, false);
  8705. }
  8706. else if( !lctx->type.dataType.IsUnsignedType() )
  8707. {
  8708. asCDataType to;
  8709. if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8710. to.SetTokenType(ttInt64);
  8711. else
  8712. to.SetTokenType(ttInt);
  8713. }
  8714. // Do the actual conversion
  8715. int l = int(reservedVariables.GetLength());
  8716. rctx->bc.GetVarsUsed(reservedVariables);
  8717. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV, true);
  8718. reservedVariables.SetLength(l);
  8719. // Verify that the conversion was successful
  8720. if( lctx->type.dataType != to )
  8721. {
  8722. asCString str;
  8723. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8724. Error(str.AddressOf(), node);
  8725. }
  8726. // Right operand must be 32bit uint
  8727. l = int(reservedVariables.GetLength());
  8728. lctx->bc.GetVarsUsed(reservedVariables);
  8729. ImplicitConversion(rctx, asCDataType::CreatePrimitive(ttUInt, true), node, asIC_IMPLICIT_CONV, true);
  8730. reservedVariables.SetLength(l);
  8731. if( !rctx->type.dataType.IsUnsignedType() )
  8732. {
  8733. asCString str;
  8734. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "uint");
  8735. Error(str.AddressOf(), node);
  8736. }
  8737. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8738. if( !isConstant )
  8739. {
  8740. ConvertToVariableNotIn(lctx, rctx);
  8741. ConvertToVariableNotIn(rctx, lctx);
  8742. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8743. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8744. if( op == ttShiftLeftAssign || op == ttShiftRightLAssign || op == ttShiftRightAAssign )
  8745. {
  8746. // Compound assignments execute the right hand value first
  8747. MergeExprBytecode(ctx, rctx);
  8748. MergeExprBytecode(ctx, lctx);
  8749. }
  8750. else
  8751. {
  8752. MergeExprBytecode(ctx, lctx);
  8753. MergeExprBytecode(ctx, rctx);
  8754. }
  8755. ProcessDeferredParams(ctx);
  8756. asEBCInstr instruction = asBC_BSLL;
  8757. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8758. {
  8759. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  8760. instruction = asBC_BSLL;
  8761. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  8762. instruction = asBC_BSRL;
  8763. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8764. instruction = asBC_BSRA;
  8765. }
  8766. else
  8767. {
  8768. if( op == ttBitShiftLeft || op == ttShiftLeftAssign )
  8769. instruction = asBC_BSLL64;
  8770. else if( op == ttBitShiftRight || op == ttShiftRightLAssign )
  8771. instruction = asBC_BSRL64;
  8772. else if( op == ttBitShiftRightArith || op == ttShiftRightAAssign )
  8773. instruction = asBC_BSRA64;
  8774. }
  8775. // Do the operation
  8776. int a = AllocateVariable(lctx->type.dataType, true);
  8777. int b = lctx->type.stackOffset;
  8778. int c = rctx->type.stackOffset;
  8779. ctx->bc.InstrW_W_W(instruction, a, b, c);
  8780. ctx->type.SetVariable(lctx->type.dataType, a, true);
  8781. }
  8782. else
  8783. {
  8784. if( lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8785. {
  8786. asDWORD v = 0;
  8787. if( op == ttBitShiftLeft )
  8788. v = lctx->type.dwordValue << rctx->type.dwordValue;
  8789. else if( op == ttBitShiftRight )
  8790. v = lctx->type.dwordValue >> rctx->type.dwordValue;
  8791. else if( op == ttBitShiftRightArith )
  8792. v = lctx->type.intValue >> rctx->type.dwordValue;
  8793. ctx->type.SetConstantDW(lctx->type.dataType, v);
  8794. }
  8795. else
  8796. {
  8797. asQWORD v = 0;
  8798. if( op == ttBitShiftLeft )
  8799. v = lctx->type.qwordValue << rctx->type.dwordValue;
  8800. else if( op == ttBitShiftRight )
  8801. v = lctx->type.qwordValue >> rctx->type.dwordValue;
  8802. else if( op == ttBitShiftRightArith )
  8803. v = asINT64(lctx->type.qwordValue) >> rctx->type.dwordValue;
  8804. ctx->type.SetConstantQW(lctx->type.dataType, v);
  8805. }
  8806. }
  8807. }
  8808. }
  8809. void asCCompiler::CompileComparisonOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  8810. {
  8811. // Both operands must be of the same type
  8812. // Implicitly convert the operands to a number type
  8813. asCDataType to;
  8814. if( lctx->type.dataType.IsDoubleType() || rctx->type.dataType.IsDoubleType() )
  8815. to.SetTokenType(ttDouble);
  8816. else if( lctx->type.dataType.IsFloatType() || rctx->type.dataType.IsFloatType() )
  8817. to.SetTokenType(ttFloat);
  8818. else if( lctx->type.dataType.GetSizeInMemoryDWords() == 2 || rctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8819. {
  8820. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() )
  8821. to.SetTokenType(ttInt64);
  8822. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8823. to.SetTokenType(ttUInt64);
  8824. }
  8825. else
  8826. {
  8827. if( lctx->type.dataType.IsIntegerType() || rctx->type.dataType.IsIntegerType() ||
  8828. lctx->type.dataType.IsEnumType() || rctx->type.dataType.IsEnumType() )
  8829. to.SetTokenType(ttInt);
  8830. else if( lctx->type.dataType.IsUnsignedType() || rctx->type.dataType.IsUnsignedType() )
  8831. to.SetTokenType(ttUInt);
  8832. else if( lctx->type.dataType.IsBooleanType() || rctx->type.dataType.IsBooleanType() )
  8833. to.SetTokenType(ttBool);
  8834. }
  8835. // If doing an operation with double constant and float variable, the constant should be converted to float
  8836. if( (lctx->type.isConstant && lctx->type.dataType.IsDoubleType() && !rctx->type.isConstant && rctx->type.dataType.IsFloatType()) ||
  8837. (rctx->type.isConstant && rctx->type.dataType.IsDoubleType() && !lctx->type.isConstant && lctx->type.dataType.IsFloatType()) )
  8838. to.SetTokenType(ttFloat);
  8839. // Is it an operation on signed values?
  8840. bool signMismatch = false;
  8841. if( !lctx->type.dataType.IsUnsignedType() || !rctx->type.dataType.IsUnsignedType() )
  8842. {
  8843. if( lctx->type.dataType.GetTokenType() == ttUInt64 )
  8844. {
  8845. if( !lctx->type.isConstant )
  8846. signMismatch = true;
  8847. else if( lctx->type.qwordValue & (asQWORD(1)<<63) )
  8848. signMismatch = true;
  8849. }
  8850. if( lctx->type.dataType.GetTokenType() == ttUInt )
  8851. {
  8852. if( !lctx->type.isConstant )
  8853. signMismatch = true;
  8854. else if( lctx->type.dwordValue & (asDWORD(1)<<31) )
  8855. signMismatch = true;
  8856. }
  8857. if( rctx->type.dataType.GetTokenType() == ttUInt64 )
  8858. {
  8859. if( !rctx->type.isConstant )
  8860. signMismatch = true;
  8861. else if( rctx->type.qwordValue & (asQWORD(1)<<63) )
  8862. signMismatch = true;
  8863. }
  8864. if( rctx->type.dataType.GetTokenType() == ttUInt )
  8865. {
  8866. if( !rctx->type.isConstant )
  8867. signMismatch = true;
  8868. else if( rctx->type.dwordValue & (asDWORD(1)<<31) )
  8869. signMismatch = true;
  8870. }
  8871. }
  8872. // Check for signed/unsigned mismatch
  8873. if( signMismatch )
  8874. Warning(TXT_SIGNED_UNSIGNED_MISMATCH, node);
  8875. // Do the actual conversion
  8876. int l = int(reservedVariables.GetLength());
  8877. rctx->bc.GetVarsUsed(reservedVariables);
  8878. if( lctx->type.dataType.IsReference() )
  8879. ConvertToVariable(lctx);
  8880. if( rctx->type.dataType.IsReference() )
  8881. ConvertToVariable(rctx);
  8882. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  8883. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  8884. reservedVariables.SetLength(l);
  8885. // Verify that the conversion was successful
  8886. bool ok = true;
  8887. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  8888. {
  8889. asCString str;
  8890. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8891. Error(str.AddressOf(), node);
  8892. ok = false;
  8893. }
  8894. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  8895. {
  8896. asCString str;
  8897. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  8898. Error(str.AddressOf(), node);
  8899. ok = false;
  8900. }
  8901. if( !ok )
  8902. {
  8903. // It wasn't possible to get two valid operands, so we just return
  8904. // a boolean result and let the compiler continue.
  8905. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  8906. return;
  8907. }
  8908. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  8909. int op = node->tokenType;
  8910. if( !isConstant )
  8911. {
  8912. if( to.IsBooleanType() )
  8913. {
  8914. int op = node->tokenType;
  8915. if( op == ttEqual || op == ttNotEqual )
  8916. {
  8917. // Must convert to temporary variable, because we are changing the value before comparison
  8918. ConvertToTempVariableNotIn(lctx, rctx);
  8919. ConvertToTempVariableNotIn(rctx, lctx);
  8920. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8921. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8922. // Make sure they are equal if not false
  8923. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  8924. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  8925. MergeExprBytecode(ctx, lctx);
  8926. MergeExprBytecode(ctx, rctx);
  8927. ProcessDeferredParams(ctx);
  8928. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  8929. int b = lctx->type.stackOffset;
  8930. int c = rctx->type.stackOffset;
  8931. if( op == ttEqual )
  8932. {
  8933. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  8934. ctx->bc.Instr(asBC_TZ);
  8935. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8936. }
  8937. else if( op == ttNotEqual )
  8938. {
  8939. ctx->bc.InstrW_W(asBC_CMPi,b,c);
  8940. ctx->bc.Instr(asBC_TNZ);
  8941. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8942. }
  8943. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  8944. }
  8945. else
  8946. {
  8947. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  8948. Error(TXT_ILLEGAL_OPERATION, node);
  8949. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), 0);
  8950. }
  8951. }
  8952. else
  8953. {
  8954. ConvertToVariableNotIn(lctx, rctx);
  8955. ConvertToVariableNotIn(rctx, lctx);
  8956. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  8957. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  8958. MergeExprBytecode(ctx, lctx);
  8959. MergeExprBytecode(ctx, rctx);
  8960. ProcessDeferredParams(ctx);
  8961. asEBCInstr iCmp = asBC_CMPi, iT = asBC_TZ;
  8962. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8963. iCmp = asBC_CMPi;
  8964. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  8965. iCmp = asBC_CMPu;
  8966. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8967. iCmp = asBC_CMPi64;
  8968. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  8969. iCmp = asBC_CMPu64;
  8970. else if( lctx->type.dataType.IsFloatType() )
  8971. iCmp = asBC_CMPf;
  8972. else if( lctx->type.dataType.IsDoubleType() )
  8973. iCmp = asBC_CMPd;
  8974. else
  8975. asASSERT(false);
  8976. if( op == ttEqual )
  8977. iT = asBC_TZ;
  8978. else if( op == ttNotEqual )
  8979. iT = asBC_TNZ;
  8980. else if( op == ttLessThan )
  8981. iT = asBC_TS;
  8982. else if( op == ttLessThanOrEqual )
  8983. iT = asBC_TNP;
  8984. else if( op == ttGreaterThan )
  8985. iT = asBC_TP;
  8986. else if( op == ttGreaterThanOrEqual )
  8987. iT = asBC_TNS;
  8988. int a = AllocateVariable(asCDataType::CreatePrimitive(ttBool, true), true);
  8989. int b = lctx->type.stackOffset;
  8990. int c = rctx->type.stackOffset;
  8991. ctx->bc.InstrW_W(iCmp, b, c);
  8992. ctx->bc.Instr(iT);
  8993. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  8994. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  8995. }
  8996. }
  8997. else
  8998. {
  8999. if( to.IsBooleanType() )
  9000. {
  9001. int op = node->tokenType;
  9002. if( op == ttEqual || op == ttNotEqual )
  9003. {
  9004. // Make sure they are equal if not false
  9005. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9006. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9007. asDWORD v = 0;
  9008. if( op == ttEqual )
  9009. {
  9010. v = lctx->type.intValue - rctx->type.intValue;
  9011. if( v == 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9012. }
  9013. else if( op == ttNotEqual )
  9014. {
  9015. v = lctx->type.intValue - rctx->type.intValue;
  9016. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9017. }
  9018. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), v);
  9019. }
  9020. else
  9021. {
  9022. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  9023. Error(TXT_ILLEGAL_OPERATION, node);
  9024. }
  9025. }
  9026. else
  9027. {
  9028. int i = 0;
  9029. if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9030. {
  9031. int v = lctx->type.intValue - rctx->type.intValue;
  9032. if( v < 0 ) i = -1;
  9033. if( v > 0 ) i = 1;
  9034. }
  9035. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9036. {
  9037. asDWORD v1 = lctx->type.dwordValue;
  9038. asDWORD v2 = rctx->type.dwordValue;
  9039. if( v1 < v2 ) i = -1;
  9040. if( v1 > v2 ) i = 1;
  9041. }
  9042. else if( lctx->type.dataType.IsIntegerType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9043. {
  9044. asINT64 v = asINT64(lctx->type.qwordValue) - asINT64(rctx->type.qwordValue);
  9045. if( v < 0 ) i = -1;
  9046. if( v > 0 ) i = 1;
  9047. }
  9048. else if( lctx->type.dataType.IsUnsignedType() && lctx->type.dataType.GetSizeInMemoryDWords() == 2 )
  9049. {
  9050. asQWORD v1 = lctx->type.qwordValue;
  9051. asQWORD v2 = rctx->type.qwordValue;
  9052. if( v1 < v2 ) i = -1;
  9053. if( v1 > v2 ) i = 1;
  9054. }
  9055. else if( lctx->type.dataType.IsFloatType() )
  9056. {
  9057. float v = lctx->type.floatValue - rctx->type.floatValue;
  9058. if( v < 0 ) i = -1;
  9059. if( v > 0 ) i = 1;
  9060. }
  9061. else if( lctx->type.dataType.IsDoubleType() )
  9062. {
  9063. double v = lctx->type.doubleValue - rctx->type.doubleValue;
  9064. if( v < 0 ) i = -1;
  9065. if( v > 0 ) i = 1;
  9066. }
  9067. if( op == ttEqual )
  9068. i = (i == 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9069. else if( op == ttNotEqual )
  9070. i = (i != 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9071. else if( op == ttLessThan )
  9072. i = (i < 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9073. else if( op == ttLessThanOrEqual )
  9074. i = (i <= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9075. else if( op == ttGreaterThan )
  9076. i = (i > 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9077. else if( op == ttGreaterThanOrEqual )
  9078. i = (i >= 0 ? VALUE_OF_BOOLEAN_TRUE : 0);
  9079. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), i);
  9080. }
  9081. }
  9082. }
  9083. void asCCompiler::PushVariableOnStack(asSExprContext *ctx, bool asReference)
  9084. {
  9085. // Put the result on the stack
  9086. if( asReference )
  9087. {
  9088. ctx->bc.InstrSHORT(asBC_PSF, ctx->type.stackOffset);
  9089. ctx->type.dataType.MakeReference(true);
  9090. }
  9091. else
  9092. {
  9093. if( ctx->type.dataType.GetSizeInMemoryDWords() == 1 )
  9094. ctx->bc.InstrSHORT(asBC_PshV4, ctx->type.stackOffset);
  9095. else
  9096. ctx->bc.InstrSHORT(asBC_PshV8, ctx->type.stackOffset);
  9097. }
  9098. }
  9099. void asCCompiler::CompileBooleanOperator(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9100. {
  9101. // Both operands must be booleans
  9102. asCDataType to;
  9103. to.SetTokenType(ttBool);
  9104. // Do the actual conversion
  9105. int l = int(reservedVariables.GetLength());
  9106. rctx->bc.GetVarsUsed(reservedVariables);
  9107. lctx->bc.GetVarsUsed(reservedVariables);
  9108. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  9109. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  9110. reservedVariables.SetLength(l);
  9111. // Verify that the conversion was successful
  9112. if( !lctx->type.dataType.IsBooleanType() )
  9113. {
  9114. asCString str;
  9115. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), "bool");
  9116. Error(str.AddressOf(), node);
  9117. // Force the conversion to allow compilation to proceed
  9118. lctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  9119. }
  9120. if( !rctx->type.dataType.IsBooleanType() )
  9121. {
  9122. asCString str;
  9123. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), "bool");
  9124. Error(str.AddressOf(), node);
  9125. // Force the conversion to allow compilation to proceed
  9126. rctx->type.SetConstantB(asCDataType::CreatePrimitive(ttBool, true), true);
  9127. }
  9128. bool isConstant = lctx->type.isConstant && rctx->type.isConstant;
  9129. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  9130. // What kind of operator is it?
  9131. int op = node->tokenType;
  9132. if( op == ttXor )
  9133. {
  9134. if( !isConstant )
  9135. {
  9136. // Must convert to temporary variable, because we are changing the value before comparison
  9137. ConvertToTempVariableNotIn(lctx, rctx);
  9138. ConvertToTempVariableNotIn(rctx, lctx);
  9139. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9140. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9141. // Make sure they are equal if not false
  9142. lctx->bc.InstrWORD(asBC_NOT, lctx->type.stackOffset);
  9143. rctx->bc.InstrWORD(asBC_NOT, rctx->type.stackOffset);
  9144. MergeExprBytecode(ctx, lctx);
  9145. MergeExprBytecode(ctx, rctx);
  9146. ProcessDeferredParams(ctx);
  9147. int a = AllocateVariable(ctx->type.dataType, true);
  9148. int b = lctx->type.stackOffset;
  9149. int c = rctx->type.stackOffset;
  9150. ctx->bc.InstrW_W_W(asBC_BXOR,a,b,c);
  9151. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9152. }
  9153. else
  9154. {
  9155. // Make sure they are equal if not false
  9156. #if AS_SIZEOF_BOOL == 1
  9157. if( lctx->type.byteValue != 0 ) lctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  9158. if( rctx->type.byteValue != 0 ) rctx->type.byteValue = VALUE_OF_BOOLEAN_TRUE;
  9159. asBYTE v = 0;
  9160. v = lctx->type.byteValue - rctx->type.byteValue;
  9161. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9162. ctx->type.isConstant = true;
  9163. ctx->type.byteValue = v;
  9164. #else
  9165. if( lctx->type.dwordValue != 0 ) lctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9166. if( rctx->type.dwordValue != 0 ) rctx->type.dwordValue = VALUE_OF_BOOLEAN_TRUE;
  9167. asDWORD v = 0;
  9168. v = lctx->type.intValue - rctx->type.intValue;
  9169. if( v != 0 ) v = VALUE_OF_BOOLEAN_TRUE; else v = 0;
  9170. ctx->type.isConstant = true;
  9171. ctx->type.dwordValue = v;
  9172. #endif
  9173. }
  9174. }
  9175. else if( op == ttAnd ||
  9176. op == ttOr )
  9177. {
  9178. if( !isConstant )
  9179. {
  9180. // If or-operator and first value is 1 the second value shouldn't be calculated
  9181. // if and-operator and first value is 0 the second value shouldn't be calculated
  9182. ConvertToVariable(lctx);
  9183. ReleaseTemporaryVariable(lctx->type, &lctx->bc);
  9184. MergeExprBytecode(ctx, lctx);
  9185. int offset = AllocateVariable(asCDataType::CreatePrimitive(ttBool, false), true);
  9186. int label1 = nextLabel++;
  9187. int label2 = nextLabel++;
  9188. if( op == ttAnd )
  9189. {
  9190. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  9191. ctx->bc.Instr(asBC_ClrHi);
  9192. ctx->bc.InstrDWORD(asBC_JNZ, label1);
  9193. ctx->bc.InstrW_DW(asBC_SetV4, (asWORD)offset, 0);
  9194. ctx->bc.InstrINT(asBC_JMP, label2);
  9195. }
  9196. else if( op == ttOr )
  9197. {
  9198. ctx->bc.InstrSHORT(asBC_CpyVtoR4, lctx->type.stackOffset);
  9199. ctx->bc.Instr(asBC_ClrHi);
  9200. ctx->bc.InstrDWORD(asBC_JZ, label1);
  9201. #if AS_SIZEOF_BOOL == 1
  9202. ctx->bc.InstrSHORT_B(asBC_SetV1, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  9203. #else
  9204. ctx->bc.InstrSHORT_DW(asBC_SetV4, (short)offset, VALUE_OF_BOOLEAN_TRUE);
  9205. #endif
  9206. ctx->bc.InstrINT(asBC_JMP, label2);
  9207. }
  9208. ctx->bc.Label((short)label1);
  9209. ConvertToVariable(rctx);
  9210. ReleaseTemporaryVariable(rctx->type, &rctx->bc);
  9211. rctx->bc.InstrW_W(asBC_CpyVtoV4, offset, rctx->type.stackOffset);
  9212. MergeExprBytecode(ctx, rctx);
  9213. ctx->bc.Label((short)label2);
  9214. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, false), offset, true);
  9215. }
  9216. else
  9217. {
  9218. #if AS_SIZEOF_BOOL == 1
  9219. asBYTE v = 0;
  9220. if( op == ttAnd )
  9221. v = lctx->type.byteValue && rctx->type.byteValue;
  9222. else if( op == ttOr )
  9223. v = lctx->type.byteValue || rctx->type.byteValue;
  9224. // Remember the result
  9225. ctx->type.isConstant = true;
  9226. ctx->type.byteValue = v;
  9227. #else
  9228. asDWORD v = 0;
  9229. if( op == ttAnd )
  9230. v = lctx->type.dwordValue && rctx->type.dwordValue;
  9231. else if( op == ttOr )
  9232. v = lctx->type.dwordValue || rctx->type.dwordValue;
  9233. // Remember the result
  9234. ctx->type.isConstant = true;
  9235. ctx->type.dwordValue = v;
  9236. #endif
  9237. }
  9238. }
  9239. }
  9240. void asCCompiler::CompileOperatorOnHandles(asCScriptNode *node, asSExprContext *lctx, asSExprContext *rctx, asSExprContext *ctx)
  9241. {
  9242. // Process the property accessor as get
  9243. ProcessPropertyGetAccessor(lctx, node);
  9244. ProcessPropertyGetAccessor(rctx, node);
  9245. // Make sure lctx doesn't end up with a variable used in rctx
  9246. if( lctx->type.isTemporary && rctx->bc.IsVarUsed(lctx->type.stackOffset) )
  9247. {
  9248. asCArray<int> vars;
  9249. rctx->bc.GetVarsUsed(vars);
  9250. int offset = AllocateVariable(lctx->type.dataType, true);
  9251. rctx->bc.ExchangeVar(lctx->type.stackOffset, offset);
  9252. ReleaseTemporaryVariable(offset, 0);
  9253. }
  9254. // Warn if not both operands are explicit handles
  9255. if( (node->tokenType == ttEqual || node->tokenType == ttNotEqual) &&
  9256. ((!lctx->type.isExplicitHandle && !(lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE))) ||
  9257. (!rctx->type.isExplicitHandle && !(rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_IMPLICIT_HANDLE)))) )
  9258. {
  9259. Warning(TXT_HANDLE_COMPARISON, node);
  9260. }
  9261. // If one of the operands is a value type used as handle, we should look for the opEquals method
  9262. if( ((lctx->type.dataType.GetObjectType() && (lctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE)) ||
  9263. (rctx->type.dataType.GetObjectType() && (rctx->type.dataType.GetObjectType()->flags & asOBJ_ASHANDLE))) &&
  9264. (node->tokenType == ttEqual || node->tokenType == ttIs ||
  9265. node->tokenType == ttNotEqual || node->tokenType == ttNotIs) )
  9266. {
  9267. // TODO: Should evaluate which of the two have the best match. If both have equal match, the first version should be used
  9268. // Find the matching opEquals method
  9269. int r = CompileOverloadedDualOperator2(node, "opEquals", lctx, rctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  9270. if( r == 0 )
  9271. {
  9272. // Try again by switching the order of the operands
  9273. r = CompileOverloadedDualOperator2(node, "opEquals", rctx, lctx, ctx, true, asCDataType::CreatePrimitive(ttBool, false));
  9274. }
  9275. if( r == 1 )
  9276. {
  9277. if( node->tokenType == ttNotEqual || node->tokenType == ttNotIs )
  9278. ctx->bc.InstrSHORT(asBC_NOT, ctx->type.stackOffset);
  9279. // Success, don't continue
  9280. return;
  9281. }
  9282. else if( r == 0 )
  9283. {
  9284. // Couldn't find opEquals method
  9285. Error(TXT_NO_APPROPRIATE_OPEQUALS, node);
  9286. }
  9287. // Compiler error, don't continue
  9288. ctx->type.SetConstantDW(asCDataType::CreatePrimitive(ttBool, true), true);
  9289. return;
  9290. }
  9291. // Implicitly convert null to the other type
  9292. asCDataType to;
  9293. if( lctx->type.IsNullConstant() )
  9294. to = rctx->type.dataType;
  9295. else if( rctx->type.IsNullConstant() )
  9296. to = lctx->type.dataType;
  9297. else
  9298. {
  9299. // TODO: Use the common base type
  9300. to = lctx->type.dataType;
  9301. }
  9302. // Need to pop the value if it is a null constant
  9303. if( lctx->type.IsNullConstant() )
  9304. lctx->bc.Pop(AS_PTR_SIZE);
  9305. if( rctx->type.IsNullConstant() )
  9306. rctx->bc.Pop(AS_PTR_SIZE);
  9307. // Convert both sides to explicit handles
  9308. to.MakeHandle(true);
  9309. to.MakeReference(false);
  9310. // Do the conversion
  9311. ImplicitConversion(lctx, to, node, asIC_IMPLICIT_CONV);
  9312. ImplicitConversion(rctx, to, node, asIC_IMPLICIT_CONV);
  9313. // Both operands must be of the same type
  9314. // Verify that the conversion was successful
  9315. if( !lctx->type.dataType.IsEqualExceptConst(to) )
  9316. {
  9317. asCString str;
  9318. str.Format(TXT_NO_CONVERSION_s_TO_s, lctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9319. Error(str.AddressOf(), node);
  9320. }
  9321. if( !rctx->type.dataType.IsEqualExceptConst(to) )
  9322. {
  9323. asCString str;
  9324. str.Format(TXT_NO_CONVERSION_s_TO_s, rctx->type.dataType.Format().AddressOf(), to.Format().AddressOf());
  9325. Error(str.AddressOf(), node);
  9326. }
  9327. ctx->type.Set(asCDataType::CreatePrimitive(ttBool, true));
  9328. int op = node->tokenType;
  9329. if( op == ttEqual || op == ttNotEqual || op == ttIs || op == ttNotIs )
  9330. {
  9331. // If the object handle already is in a variable we must manually pop it from the stack
  9332. if( lctx->type.isVariable )
  9333. lctx->bc.Pop(AS_PTR_SIZE);
  9334. if( rctx->type.isVariable )
  9335. rctx->bc.Pop(AS_PTR_SIZE);
  9336. // TODO: optimize: Treat the object handles as two integers, i.e. don't do REFCPY
  9337. ConvertToVariableNotIn(lctx, rctx);
  9338. ConvertToVariable(rctx);
  9339. MergeExprBytecode(ctx, lctx);
  9340. MergeExprBytecode(ctx, rctx);
  9341. int a = AllocateVariable(ctx->type.dataType, true);
  9342. int b = lctx->type.stackOffset;
  9343. int c = rctx->type.stackOffset;
  9344. ctx->bc.InstrW_W(asBC_CmpPtr, b, c);
  9345. if( op == ttEqual || op == ttIs )
  9346. ctx->bc.Instr(asBC_TZ);
  9347. else if( op == ttNotEqual || op == ttNotIs )
  9348. ctx->bc.Instr(asBC_TNZ);
  9349. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)a);
  9350. ctx->type.SetVariable(asCDataType::CreatePrimitive(ttBool, true), a, true);
  9351. ReleaseTemporaryVariable(lctx->type, &ctx->bc);
  9352. ReleaseTemporaryVariable(rctx->type, &ctx->bc);
  9353. ProcessDeferredParams(ctx);
  9354. }
  9355. else
  9356. {
  9357. // TODO: Use TXT_ILLEGAL_OPERATION_ON
  9358. Error(TXT_ILLEGAL_OPERATION, node);
  9359. }
  9360. }
  9361. void asCCompiler::PerformFunctionCall(int funcId, asSExprContext *ctx, bool isConstructor, asCArray<asSExprContext*> *args, asCObjectType *objType, bool useVariable, int varOffset, int funcPtrVar)
  9362. {
  9363. asCScriptFunction *descr = builder->GetFunctionDescription(funcId);
  9364. // A shared object may not call non-shared functions
  9365. if( outFunc->IsShared() && !descr->IsShared() )
  9366. {
  9367. asCString msg;
  9368. msg.Format(TXT_SHARED_CANNOT_CALL_NON_SHARED_FUNC_s, descr->GetDeclarationStr().AddressOf());
  9369. Error(msg.AddressOf(), ctx->exprNode);
  9370. }
  9371. // Check if the function is private
  9372. if( descr->isPrivate && descr->GetObjectType() != outFunc->GetObjectType() )
  9373. {
  9374. asCString msg;
  9375. msg.Format(TXT_PRIVATE_METHOD_CALL_s, descr->GetDeclarationStr().AddressOf());
  9376. Error(msg.AddressOf(), ctx->exprNode);
  9377. }
  9378. int argSize = descr->GetSpaceNeededForArguments();
  9379. if( descr->objectType && descr->returnType.IsReference() &&
  9380. !ctx->type.isVariable && (ctx->type.dataType.IsObjectHandle() || ctx->type.dataType.SupportHandles()) &&
  9381. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_SCOPED) &&
  9382. !(ctx->type.dataType.GetObjectType()->GetFlags() & asOBJ_ASHANDLE) )
  9383. {
  9384. // The class method we're calling is returning a reference, which may be to a member of the object.
  9385. // In order to guarantee the lifetime of the reference, we must hold a local reference to the object.
  9386. // TODO: optimize: This can be avoided for local variables (non-handles) as they have a well defined life time
  9387. int tempRef = AllocateVariable(ctx->type.dataType, true);
  9388. ctx->bc.InstrSHORT(asBC_PSF, (short)tempRef);
  9389. ctx->bc.InstrPTR(asBC_REFCPY, ctx->type.dataType.GetObjectType());
  9390. // Add the release of this reference, as a deferred expression
  9391. asSDeferredParam deferred;
  9392. deferred.origExpr = 0;
  9393. deferred.argInOutFlags = asTM_INREF;
  9394. deferred.argNode = 0;
  9395. deferred.argType.SetVariable(ctx->type.dataType, tempRef, true);
  9396. ctx->deferredParams.PushLast(deferred);
  9397. // Forget the current type
  9398. ctx->type.SetDummy();
  9399. }
  9400. if( isConstructor )
  9401. {
  9402. // Sometimes the value types are allocated on the heap,
  9403. // which is when this way of constructing them is used.
  9404. asASSERT(useVariable == false);
  9405. ctx->bc.Alloc(asBC_ALLOC, objType, descr->id, argSize+AS_PTR_SIZE);
  9406. // The instruction has already moved the returned object to the variable
  9407. ctx->type.Set(asCDataType::CreatePrimitive(ttVoid, false));
  9408. ctx->type.isLValue = false;
  9409. // Clean up arguments
  9410. if( args )
  9411. AfterFunctionCall(funcId, *args, ctx, false);
  9412. ProcessDeferredParams(ctx);
  9413. return;
  9414. }
  9415. else
  9416. {
  9417. if( descr->objectType )
  9418. argSize += AS_PTR_SIZE;
  9419. // If the function returns an object by value the address of the location
  9420. // where the value should be stored is passed as an argument too
  9421. if( descr->DoesReturnOnStack() )
  9422. {
  9423. argSize += AS_PTR_SIZE;
  9424. }
  9425. // TODO: optimize: If it is known that a class method cannot be overridden the call
  9426. // should be made with asBC_CALL as it is faster. Examples where this
  9427. // is known is for example finalled methods where the class doesn't derive
  9428. // from any other, or even non-finalled methods but where it is known
  9429. // at compile time the true type of the object. The first should be
  9430. // quite easy to determine, but the latter will be quite complex and possibly
  9431. // not worth it.
  9432. if( descr->funcType == asFUNC_IMPORTED )
  9433. ctx->bc.Call(asBC_CALLBND , descr->id, argSize);
  9434. // TODO: Maybe we need two different byte codes
  9435. else if( descr->funcType == asFUNC_INTERFACE || descr->funcType == asFUNC_VIRTUAL )
  9436. ctx->bc.Call(asBC_CALLINTF, descr->id, argSize);
  9437. else if( descr->funcType == asFUNC_SCRIPT )
  9438. ctx->bc.Call(asBC_CALL , descr->id, argSize);
  9439. else if( descr->funcType == asFUNC_SYSTEM )
  9440. ctx->bc.Call(asBC_CALLSYS , descr->id, argSize);
  9441. else if( descr->funcType == asFUNC_FUNCDEF )
  9442. ctx->bc.CallPtr(asBC_CallPtr, funcPtrVar, argSize);
  9443. }
  9444. if( descr->returnType.IsObject() && !descr->returnType.IsReference() )
  9445. {
  9446. int returnOffset = 0;
  9447. if( descr->DoesReturnOnStack() )
  9448. {
  9449. asASSERT( useVariable );
  9450. // The variable was allocated before the function was called
  9451. returnOffset = varOffset;
  9452. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  9453. // The variable was initialized by the function, so we need to mark it as initialized here
  9454. ctx->bc.ObjInfo(varOffset, asOBJ_INIT);
  9455. }
  9456. else
  9457. {
  9458. if( useVariable )
  9459. {
  9460. // Use the given variable
  9461. returnOffset = varOffset;
  9462. ctx->type.SetVariable(descr->returnType, returnOffset, false);
  9463. }
  9464. else
  9465. {
  9466. // Allocate a temporary variable for the returned object
  9467. // The returned object will actually be allocated on the heap, so
  9468. // we must force the allocation of the variable to do the same
  9469. returnOffset = AllocateVariable(descr->returnType, true, true);
  9470. ctx->type.SetVariable(descr->returnType, returnOffset, true);
  9471. }
  9472. // Move the pointer from the object register to the temporary variable
  9473. ctx->bc.InstrSHORT(asBC_STOREOBJ, (short)returnOffset);
  9474. }
  9475. ctx->type.dataType.MakeReference(IsVariableOnHeap(returnOffset));
  9476. ctx->type.isLValue = false; // It is a reference, but not an lvalue
  9477. // Clean up arguments
  9478. if( args )
  9479. AfterFunctionCall(funcId, *args, ctx, false);
  9480. ProcessDeferredParams(ctx);
  9481. ctx->bc.InstrSHORT(asBC_PSF, (short)returnOffset);
  9482. }
  9483. else if( descr->returnType.IsReference() )
  9484. {
  9485. asASSERT(useVariable == false);
  9486. // We cannot clean up the arguments yet, because the
  9487. // reference might be pointing to one of them.
  9488. if( args )
  9489. AfterFunctionCall(funcId, *args, ctx, true);
  9490. // Do not process the output parameters yet, because it
  9491. // might invalidate the returned reference
  9492. // If the context holds a variable that needs cleanup
  9493. // store it as a deferred parameter so it will be cleaned up
  9494. // afterwards.
  9495. if( ctx->type.isTemporary )
  9496. {
  9497. asSDeferredParam defer;
  9498. defer.argNode = 0;
  9499. defer.argType = ctx->type;
  9500. defer.argInOutFlags = asTM_INOUTREF;
  9501. defer.origExpr = 0;
  9502. ctx->deferredParams.PushLast(defer);
  9503. }
  9504. ctx->type.Set(descr->returnType);
  9505. if( !descr->returnType.IsPrimitive() )
  9506. {
  9507. ctx->bc.Instr(asBC_PshRPtr);
  9508. if( descr->returnType.IsObject() &&
  9509. !descr->returnType.IsObjectHandle() )
  9510. {
  9511. // We are getting the pointer to the object
  9512. // not a pointer to a object variable
  9513. ctx->type.dataType.MakeReference(false);
  9514. }
  9515. }
  9516. // A returned reference can be used as lvalue
  9517. ctx->type.isLValue = true;
  9518. }
  9519. else
  9520. {
  9521. asASSERT(useVariable == false);
  9522. if( descr->returnType.GetSizeInMemoryBytes() )
  9523. {
  9524. // Allocate a temporary variable to hold the value, but make sure
  9525. // the temporary variable isn't used in any of the deferred arguments
  9526. int l = int(reservedVariables.GetLength());
  9527. for( asUINT n = 0; args && n < args->GetLength(); n++ )
  9528. {
  9529. asSExprContext *expr = (*args)[n]->origExpr;
  9530. if( expr )
  9531. expr->bc.GetVarsUsed(reservedVariables);
  9532. }
  9533. int offset = AllocateVariable(descr->returnType, true);
  9534. reservedVariables.SetLength(l);
  9535. ctx->type.SetVariable(descr->returnType, offset, true);
  9536. // Move the value from the return register to the variable
  9537. if( descr->returnType.GetSizeOnStackDWords() == 1 )
  9538. ctx->bc.InstrSHORT(asBC_CpyRtoV4, (short)offset);
  9539. else if( descr->returnType.GetSizeOnStackDWords() == 2 )
  9540. ctx->bc.InstrSHORT(asBC_CpyRtoV8, (short)offset);
  9541. }
  9542. else
  9543. ctx->type.Set(descr->returnType);
  9544. ctx->type.isLValue = false;
  9545. // Clean up arguments
  9546. if( args )
  9547. AfterFunctionCall(funcId, *args, ctx, false);
  9548. ProcessDeferredParams(ctx);
  9549. }
  9550. }
  9551. // This only merges the bytecode, but doesn't modify the type of the final context
  9552. void asCCompiler::MergeExprBytecode(asSExprContext *before, asSExprContext *after)
  9553. {
  9554. before->bc.AddCode(&after->bc);
  9555. for( asUINT n = 0; n < after->deferredParams.GetLength(); n++ )
  9556. {
  9557. before->deferredParams.PushLast(after->deferredParams[n]);
  9558. after->deferredParams[n].origExpr = 0;
  9559. }
  9560. after->deferredParams.SetLength(0);
  9561. }
  9562. // This merges both bytecode and the type of the final context
  9563. void asCCompiler::MergeExprBytecodeAndType(asSExprContext *before, asSExprContext *after)
  9564. {
  9565. MergeExprBytecode(before, after);
  9566. before->type = after->type;
  9567. before->property_get = after->property_get;
  9568. before->property_set = after->property_set;
  9569. before->property_const = after->property_const;
  9570. before->property_handle = after->property_handle;
  9571. before->property_ref = after->property_ref;
  9572. before->property_arg = after->property_arg;
  9573. before->exprNode = after->exprNode;
  9574. after->property_arg = 0;
  9575. // Do not copy the origExpr member
  9576. }
  9577. void asCCompiler::FilterConst(asCArray<int> &funcs)
  9578. {
  9579. if( funcs.GetLength() == 0 ) return;
  9580. // This is only done for object methods
  9581. asCScriptFunction *desc = builder->GetFunctionDescription(funcs[0]);
  9582. if( desc->objectType == 0 ) return;
  9583. // Check if there are any non-const matches
  9584. asUINT n;
  9585. bool foundNonConst = false;
  9586. for( n = 0; n < funcs.GetLength(); n++ )
  9587. {
  9588. desc = builder->GetFunctionDescription(funcs[n]);
  9589. if( !desc->isReadOnly )
  9590. {
  9591. foundNonConst = true;
  9592. break;
  9593. }
  9594. }
  9595. if( foundNonConst )
  9596. {
  9597. // Remove all const methods
  9598. for( n = 0; n < funcs.GetLength(); n++ )
  9599. {
  9600. desc = builder->GetFunctionDescription(funcs[n]);
  9601. if( desc->isReadOnly )
  9602. {
  9603. if( n == funcs.GetLength() - 1 )
  9604. funcs.PopLast();
  9605. else
  9606. funcs[n] = funcs.PopLast();
  9607. n--;
  9608. }
  9609. }
  9610. }
  9611. }
  9612. END_AS_NAMESPACE
  9613. #endif // AS_NO_COMPILER