gdscript_parser.cpp 199 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867
  1. /**************************************************************************/
  2. /* gdscript_parser.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gdscript_parser.h"
  31. #include "gdscript.h"
  32. #include "gdscript_tokenizer_buffer.h"
  33. #include "core/config/project_settings.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/resource_loader.h"
  36. #include "core/math/math_defs.h"
  37. #include "scene/main/multiplayer_api.h"
  38. #ifdef DEBUG_ENABLED
  39. #include "core/os/os.h"
  40. #include "core/string/string_builder.h"
  41. #include "servers/text_server.h"
  42. #endif
  43. #ifdef TOOLS_ENABLED
  44. #include "editor/editor_settings.h"
  45. #endif
  46. // This function is used to determine that a type is "built-in" as opposed to native
  47. // and custom classes. So `Variant::NIL` and `Variant::OBJECT` are excluded:
  48. // `Variant::NIL` - `null` is literal, not a type.
  49. // `Variant::OBJECT` - `Object` should be treated as a class, not as a built-in type.
  50. static HashMap<StringName, Variant::Type> builtin_types;
  51. Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) {
  52. if (unlikely(builtin_types.is_empty())) {
  53. for (int i = 0; i < Variant::VARIANT_MAX; i++) {
  54. Variant::Type type = (Variant::Type)i;
  55. if (type != Variant::NIL && type != Variant::OBJECT) {
  56. builtin_types[Variant::get_type_name(type)] = type;
  57. }
  58. }
  59. }
  60. if (builtin_types.has(p_type)) {
  61. return builtin_types[p_type];
  62. }
  63. return Variant::VARIANT_MAX;
  64. }
  65. #ifdef TOOLS_ENABLED
  66. HashMap<String, String> GDScriptParser::theme_color_names;
  67. #endif
  68. HashMap<StringName, GDScriptParser::AnnotationInfo> GDScriptParser::valid_annotations;
  69. void GDScriptParser::cleanup() {
  70. builtin_types.clear();
  71. valid_annotations.clear();
  72. }
  73. void GDScriptParser::get_annotation_list(List<MethodInfo> *r_annotations) const {
  74. for (const KeyValue<StringName, AnnotationInfo> &E : valid_annotations) {
  75. r_annotations->push_back(E.value.info);
  76. }
  77. }
  78. bool GDScriptParser::annotation_exists(const String &p_annotation_name) const {
  79. return valid_annotations.has(p_annotation_name);
  80. }
  81. GDScriptParser::GDScriptParser() {
  82. // Register valid annotations.
  83. if (unlikely(valid_annotations.is_empty())) {
  84. register_annotation(MethodInfo("@tool"), AnnotationInfo::SCRIPT, &GDScriptParser::tool_annotation);
  85. register_annotation(MethodInfo("@icon", PropertyInfo(Variant::STRING, "icon_path")), AnnotationInfo::SCRIPT, &GDScriptParser::icon_annotation);
  86. register_annotation(MethodInfo("@static_unload"), AnnotationInfo::SCRIPT, &GDScriptParser::static_unload_annotation);
  87. register_annotation(MethodInfo("@onready"), AnnotationInfo::VARIABLE, &GDScriptParser::onready_annotation);
  88. // Export annotations.
  89. register_annotation(MethodInfo("@export"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NONE, Variant::NIL>);
  90. register_annotation(MethodInfo("@export_enum", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_ENUM, Variant::NIL>, varray(), true);
  91. register_annotation(MethodInfo("@export_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE, Variant::STRING>, varray(""), true);
  92. register_annotation(MethodInfo("@export_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_DIR, Variant::STRING>);
  93. register_annotation(MethodInfo("@export_global_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_FILE, Variant::STRING>, varray(""), true);
  94. register_annotation(MethodInfo("@export_global_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_DIR, Variant::STRING>);
  95. register_annotation(MethodInfo("@export_multiline"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>);
  96. register_annotation(MethodInfo("@export_placeholder", PropertyInfo(Variant::STRING, "placeholder")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>);
  97. register_annotation(MethodInfo("@export_range", PropertyInfo(Variant::FLOAT, "min"), PropertyInfo(Variant::FLOAT, "max"), PropertyInfo(Variant::FLOAT, "step"), PropertyInfo(Variant::STRING, "extra_hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_RANGE, Variant::FLOAT>, varray(1.0, ""), true);
  98. register_annotation(MethodInfo("@export_exp_easing", PropertyInfo(Variant::STRING, "hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, varray(""), true);
  99. register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>);
  100. register_annotation(MethodInfo("@export_node_path", PropertyInfo(Variant::STRING, "type")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NODE_PATH_VALID_TYPES, Variant::NODE_PATH>, varray(""), true);
  101. register_annotation(MethodInfo("@export_flags", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FLAGS, Variant::INT>, varray(), true);
  102. register_annotation(MethodInfo("@export_flags_2d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_RENDER, Variant::INT>);
  103. register_annotation(MethodInfo("@export_flags_2d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_PHYSICS, Variant::INT>);
  104. register_annotation(MethodInfo("@export_flags_2d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_NAVIGATION, Variant::INT>);
  105. register_annotation(MethodInfo("@export_flags_3d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_RENDER, Variant::INT>);
  106. register_annotation(MethodInfo("@export_flags_3d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_PHYSICS, Variant::INT>);
  107. register_annotation(MethodInfo("@export_flags_3d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_NAVIGATION, Variant::INT>);
  108. register_annotation(MethodInfo("@export_flags_avoidance"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_AVOIDANCE, Variant::INT>);
  109. register_annotation(MethodInfo("@export_storage"), AnnotationInfo::VARIABLE, &GDScriptParser::export_storage_annotation);
  110. register_annotation(MethodInfo("@export_custom", PropertyInfo(Variant::INT, "hint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CLASS_IS_ENUM, "PropertyHint"), PropertyInfo(Variant::STRING, "hint_string"), PropertyInfo(Variant::INT, "usage", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CLASS_IS_BITFIELD, "PropertyUsageFlags")), AnnotationInfo::VARIABLE, &GDScriptParser::export_custom_annotation, varray(PROPERTY_USAGE_DEFAULT));
  111. // Export grouping annotations.
  112. register_annotation(MethodInfo("@export_category", PropertyInfo(Variant::STRING, "name")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_CATEGORY>);
  113. register_annotation(MethodInfo("@export_group", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_GROUP>, varray(""));
  114. register_annotation(MethodInfo("@export_subgroup", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_SUBGROUP>, varray(""));
  115. // Warning annotations.
  116. register_annotation(MethodInfo("@warning_ignore", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STATEMENT, &GDScriptParser::warning_annotations, varray(), true);
  117. // Networking.
  118. register_annotation(MethodInfo("@rpc", PropertyInfo(Variant::STRING, "mode"), PropertyInfo(Variant::STRING, "sync"), PropertyInfo(Variant::STRING, "transfer_mode"), PropertyInfo(Variant::INT, "transfer_channel")), AnnotationInfo::FUNCTION, &GDScriptParser::rpc_annotation, varray("authority", "call_remote", "unreliable", 0));
  119. }
  120. #ifdef DEBUG_ENABLED
  121. is_ignoring_warnings = !(bool)GLOBAL_GET("debug/gdscript/warnings/enable");
  122. #endif
  123. #ifdef TOOLS_ENABLED
  124. if (unlikely(theme_color_names.is_empty())) {
  125. // Vectors.
  126. theme_color_names.insert("x", "axis_x_color");
  127. theme_color_names.insert("y", "axis_y_color");
  128. theme_color_names.insert("z", "axis_z_color");
  129. theme_color_names.insert("w", "axis_w_color");
  130. // Color.
  131. theme_color_names.insert("r", "axis_x_color");
  132. theme_color_names.insert("r8", "axis_x_color");
  133. theme_color_names.insert("g", "axis_y_color");
  134. theme_color_names.insert("g8", "axis_y_color");
  135. theme_color_names.insert("b", "axis_z_color");
  136. theme_color_names.insert("b8", "axis_z_color");
  137. theme_color_names.insert("a", "axis_w_color");
  138. theme_color_names.insert("a8", "axis_w_color");
  139. }
  140. #endif
  141. }
  142. GDScriptParser::~GDScriptParser() {
  143. while (list != nullptr) {
  144. Node *element = list;
  145. list = list->next;
  146. memdelete(element);
  147. }
  148. }
  149. void GDScriptParser::clear() {
  150. GDScriptParser tmp;
  151. tmp = *this;
  152. *this = GDScriptParser();
  153. }
  154. void GDScriptParser::push_error(const String &p_message, const Node *p_origin) {
  155. // TODO: Improve error reporting by pointing at source code.
  156. // TODO: Errors might point at more than one place at once (e.g. show previous declaration).
  157. panic_mode = true;
  158. // TODO: Improve positional information.
  159. if (p_origin == nullptr) {
  160. errors.push_back({ p_message, previous.start_line, previous.start_column });
  161. } else {
  162. errors.push_back({ p_message, p_origin->start_line, p_origin->leftmost_column });
  163. }
  164. }
  165. #ifdef DEBUG_ENABLED
  166. void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const Vector<String> &p_symbols) {
  167. ERR_FAIL_NULL(p_source);
  168. ERR_FAIL_INDEX(p_code, GDScriptWarning::WARNING_MAX);
  169. if (is_ignoring_warnings) {
  170. return;
  171. }
  172. if (GLOBAL_GET("debug/gdscript/warnings/exclude_addons").booleanize() && script_path.begins_with("res://addons/")) {
  173. return;
  174. }
  175. GDScriptWarning::WarnLevel warn_level = (GDScriptWarning::WarnLevel)(int)GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(p_code));
  176. if (warn_level == GDScriptWarning::IGNORE) {
  177. return;
  178. }
  179. PendingWarning pw;
  180. pw.source = p_source;
  181. pw.code = p_code;
  182. pw.treated_as_error = warn_level == GDScriptWarning::ERROR;
  183. pw.symbols = p_symbols;
  184. pending_warnings.push_back(pw);
  185. }
  186. void GDScriptParser::apply_pending_warnings() {
  187. for (const PendingWarning &pw : pending_warnings) {
  188. if (warning_ignored_lines[pw.code].has(pw.source->start_line)) {
  189. continue;
  190. }
  191. GDScriptWarning warning;
  192. warning.code = pw.code;
  193. warning.symbols = pw.symbols;
  194. warning.start_line = pw.source->start_line;
  195. warning.end_line = pw.source->end_line;
  196. warning.leftmost_column = pw.source->leftmost_column;
  197. warning.rightmost_column = pw.source->rightmost_column;
  198. if (pw.treated_as_error) {
  199. push_error(warning.get_message() + String(" (Warning treated as error.)"), pw.source);
  200. continue;
  201. }
  202. List<GDScriptWarning>::Element *before = nullptr;
  203. for (List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) {
  204. if (E->get().start_line > warning.start_line) {
  205. break;
  206. }
  207. before = E;
  208. }
  209. if (before) {
  210. warnings.insert_after(before, warning);
  211. } else {
  212. warnings.push_front(warning);
  213. }
  214. }
  215. pending_warnings.clear();
  216. }
  217. #endif
  218. void GDScriptParser::override_completion_context(const Node *p_for_node, CompletionType p_type, Node *p_node, int p_argument) {
  219. if (!for_completion) {
  220. return;
  221. }
  222. if (completion_context.node != p_for_node) {
  223. return;
  224. }
  225. CompletionContext context;
  226. context.type = p_type;
  227. context.current_class = current_class;
  228. context.current_function = current_function;
  229. context.current_suite = current_suite;
  230. context.current_line = tokenizer->get_cursor_line();
  231. context.current_argument = p_argument;
  232. context.node = p_node;
  233. context.parser = this;
  234. completion_context = context;
  235. }
  236. void GDScriptParser::make_completion_context(CompletionType p_type, Node *p_node, int p_argument) {
  237. if (!for_completion) {
  238. return;
  239. }
  240. if (previous.cursor_place != GDScriptTokenizerText::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizerText::CURSOR_END && current.cursor_place == GDScriptTokenizerText::CURSOR_NONE) {
  241. return;
  242. }
  243. CompletionContext context;
  244. context.type = p_type;
  245. context.current_class = current_class;
  246. context.current_function = current_function;
  247. context.current_suite = current_suite;
  248. context.current_line = tokenizer->get_cursor_line();
  249. context.current_argument = p_argument;
  250. context.node = p_node;
  251. context.parser = this;
  252. completion_context = context;
  253. }
  254. void GDScriptParser::make_completion_context(CompletionType p_type, Variant::Type p_builtin_type) {
  255. if (!for_completion) {
  256. return;
  257. }
  258. if (previous.cursor_place != GDScriptTokenizerText::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizerText::CURSOR_END && current.cursor_place == GDScriptTokenizerText::CURSOR_NONE) {
  259. return;
  260. }
  261. CompletionContext context;
  262. context.type = p_type;
  263. context.current_class = current_class;
  264. context.current_function = current_function;
  265. context.current_suite = current_suite;
  266. context.current_line = tokenizer->get_cursor_line();
  267. context.builtin_type = p_builtin_type;
  268. context.parser = this;
  269. completion_context = context;
  270. }
  271. void GDScriptParser::push_completion_call(Node *p_call) {
  272. if (!for_completion) {
  273. return;
  274. }
  275. CompletionCall call;
  276. call.call = p_call;
  277. call.argument = 0;
  278. completion_call_stack.push_back(call);
  279. if (previous.cursor_place == GDScriptTokenizerText::CURSOR_MIDDLE || previous.cursor_place == GDScriptTokenizerText::CURSOR_END || current.cursor_place == GDScriptTokenizerText::CURSOR_BEGINNING) {
  280. completion_call = call;
  281. }
  282. }
  283. void GDScriptParser::pop_completion_call() {
  284. if (!for_completion) {
  285. return;
  286. }
  287. ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to pop empty completion call stack");
  288. completion_call_stack.pop_back();
  289. }
  290. void GDScriptParser::set_last_completion_call_arg(int p_argument) {
  291. if (!for_completion || passed_cursor) {
  292. return;
  293. }
  294. ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to set argument on empty completion call stack");
  295. completion_call_stack.back()->get().argument = p_argument;
  296. }
  297. Error GDScriptParser::parse(const String &p_source_code, const String &p_script_path, bool p_for_completion, bool p_parse_body) {
  298. clear();
  299. String source = p_source_code;
  300. int cursor_line = -1;
  301. int cursor_column = -1;
  302. for_completion = p_for_completion;
  303. parse_body = p_parse_body;
  304. int tab_size = 4;
  305. #ifdef TOOLS_ENABLED
  306. if (EditorSettings::get_singleton()) {
  307. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  308. }
  309. #endif // TOOLS_ENABLED
  310. if (p_for_completion) {
  311. // Remove cursor sentinel char.
  312. const Vector<String> lines = p_source_code.split("\n");
  313. cursor_line = 1;
  314. cursor_column = 1;
  315. for (int i = 0; i < lines.size(); i++) {
  316. bool found = false;
  317. const String &line = lines[i];
  318. for (int j = 0; j < line.size(); j++) {
  319. if (line[j] == char32_t(0xFFFF)) {
  320. found = true;
  321. break;
  322. } else if (line[j] == '\t') {
  323. cursor_column += tab_size - 1;
  324. }
  325. cursor_column++;
  326. }
  327. if (found) {
  328. break;
  329. }
  330. cursor_line++;
  331. cursor_column = 1;
  332. }
  333. source = source.replace_first(String::chr(0xFFFF), String());
  334. }
  335. GDScriptTokenizerText *text_tokenizer = memnew(GDScriptTokenizerText);
  336. text_tokenizer->set_source_code(source);
  337. tokenizer = text_tokenizer;
  338. tokenizer->set_cursor_position(cursor_line, cursor_column);
  339. script_path = p_script_path.simplify_path();
  340. current = tokenizer->scan();
  341. // Avoid error or newline as the first token.
  342. // The latter can mess with the parser when opening files filled exclusively with comments and newlines.
  343. while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
  344. if (current.type == GDScriptTokenizer::Token::ERROR) {
  345. push_error(current.literal);
  346. }
  347. current = tokenizer->scan();
  348. }
  349. #ifdef DEBUG_ENABLED
  350. // Warn about parsing an empty script file:
  351. if (current.type == GDScriptTokenizer::Token::TK_EOF) {
  352. // Create a dummy Node for the warning, pointing to the very beginning of the file
  353. Node *nd = alloc_node<PassNode>();
  354. nd->start_line = 1;
  355. nd->start_column = 0;
  356. nd->end_line = 1;
  357. nd->leftmost_column = 0;
  358. nd->rightmost_column = 0;
  359. push_warning(nd, GDScriptWarning::EMPTY_FILE);
  360. }
  361. #endif
  362. push_multiline(false); // Keep one for the whole parsing.
  363. parse_program();
  364. pop_multiline();
  365. memdelete(text_tokenizer);
  366. tokenizer = nullptr;
  367. #ifdef DEBUG_ENABLED
  368. if (multiline_stack.size() > 0) {
  369. ERR_PRINT("Parser bug: Imbalanced multiline stack.");
  370. }
  371. #endif
  372. if (errors.is_empty()) {
  373. return OK;
  374. } else {
  375. return ERR_PARSE_ERROR;
  376. }
  377. }
  378. Error GDScriptParser::parse_binary(const Vector<uint8_t> &p_binary, const String &p_script_path) {
  379. GDScriptTokenizerBuffer *buffer_tokenizer = memnew(GDScriptTokenizerBuffer);
  380. Error err = buffer_tokenizer->set_code_buffer(p_binary);
  381. if (err) {
  382. memdelete(buffer_tokenizer);
  383. return err;
  384. }
  385. tokenizer = buffer_tokenizer;
  386. script_path = p_script_path.simplify_path();
  387. current = tokenizer->scan();
  388. // Avoid error or newline as the first token.
  389. // The latter can mess with the parser when opening files filled exclusively with comments and newlines.
  390. while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
  391. if (current.type == GDScriptTokenizer::Token::ERROR) {
  392. push_error(current.literal);
  393. }
  394. current = tokenizer->scan();
  395. }
  396. push_multiline(false); // Keep one for the whole parsing.
  397. parse_program();
  398. pop_multiline();
  399. memdelete(buffer_tokenizer);
  400. tokenizer = nullptr;
  401. if (errors.is_empty()) {
  402. return OK;
  403. } else {
  404. return ERR_PARSE_ERROR;
  405. }
  406. }
  407. GDScriptTokenizer::Token GDScriptParser::advance() {
  408. lambda_ended = false; // Empty marker since we're past the end in any case.
  409. if (current.type == GDScriptTokenizer::Token::TK_EOF) {
  410. ERR_FAIL_COND_V_MSG(current.type == GDScriptTokenizer::Token::TK_EOF, current, "GDScript parser bug: Trying to advance past the end of stream.");
  411. }
  412. if (for_completion && !completion_call_stack.is_empty()) {
  413. if (completion_call.call == nullptr && tokenizer->is_past_cursor()) {
  414. completion_call = completion_call_stack.back()->get();
  415. passed_cursor = true;
  416. }
  417. }
  418. previous = current;
  419. current = tokenizer->scan();
  420. while (current.type == GDScriptTokenizer::Token::ERROR) {
  421. push_error(current.literal);
  422. current = tokenizer->scan();
  423. }
  424. if (previous.type != GDScriptTokenizer::Token::DEDENT) { // `DEDENT` belongs to the next non-empty line.
  425. for (Node *n : nodes_in_progress) {
  426. update_extents(n);
  427. }
  428. }
  429. return previous;
  430. }
  431. bool GDScriptParser::match(GDScriptTokenizer::Token::Type p_token_type) {
  432. if (!check(p_token_type)) {
  433. return false;
  434. }
  435. advance();
  436. return true;
  437. }
  438. bool GDScriptParser::check(GDScriptTokenizer::Token::Type p_token_type) const {
  439. if (p_token_type == GDScriptTokenizer::Token::IDENTIFIER) {
  440. return current.is_identifier();
  441. }
  442. return current.type == p_token_type;
  443. }
  444. bool GDScriptParser::consume(GDScriptTokenizer::Token::Type p_token_type, const String &p_error_message) {
  445. if (match(p_token_type)) {
  446. return true;
  447. }
  448. push_error(p_error_message);
  449. return false;
  450. }
  451. bool GDScriptParser::is_at_end() const {
  452. return check(GDScriptTokenizer::Token::TK_EOF);
  453. }
  454. void GDScriptParser::synchronize() {
  455. panic_mode = false;
  456. while (!is_at_end()) {
  457. if (previous.type == GDScriptTokenizer::Token::NEWLINE || previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  458. return;
  459. }
  460. switch (current.type) {
  461. case GDScriptTokenizer::Token::CLASS:
  462. case GDScriptTokenizer::Token::FUNC:
  463. case GDScriptTokenizer::Token::STATIC:
  464. case GDScriptTokenizer::Token::VAR:
  465. case GDScriptTokenizer::Token::CONST:
  466. case GDScriptTokenizer::Token::SIGNAL:
  467. //case GDScriptTokenizer::Token::IF: // Can also be inside expressions.
  468. case GDScriptTokenizer::Token::FOR:
  469. case GDScriptTokenizer::Token::WHILE:
  470. case GDScriptTokenizer::Token::MATCH:
  471. case GDScriptTokenizer::Token::RETURN:
  472. case GDScriptTokenizer::Token::ANNOTATION:
  473. return;
  474. default:
  475. // Do nothing.
  476. break;
  477. }
  478. advance();
  479. }
  480. }
  481. void GDScriptParser::push_multiline(bool p_state) {
  482. multiline_stack.push_back(p_state);
  483. tokenizer->set_multiline_mode(p_state);
  484. if (p_state) {
  485. // Consume potential whitespace tokens already waiting in line.
  486. while (current.type == GDScriptTokenizer::Token::NEWLINE || current.type == GDScriptTokenizer::Token::INDENT || current.type == GDScriptTokenizer::Token::DEDENT) {
  487. current = tokenizer->scan(); // Don't call advance() here, as we don't want to change the previous token.
  488. }
  489. }
  490. }
  491. void GDScriptParser::pop_multiline() {
  492. ERR_FAIL_COND_MSG(multiline_stack.is_empty(), "Parser bug: trying to pop from multiline stack without available value.");
  493. multiline_stack.pop_back();
  494. tokenizer->set_multiline_mode(multiline_stack.size() > 0 ? multiline_stack.back()->get() : false);
  495. }
  496. bool GDScriptParser::is_statement_end_token() const {
  497. return check(GDScriptTokenizer::Token::NEWLINE) || check(GDScriptTokenizer::Token::SEMICOLON) || check(GDScriptTokenizer::Token::TK_EOF);
  498. }
  499. bool GDScriptParser::is_statement_end() const {
  500. return lambda_ended || in_lambda || is_statement_end_token();
  501. }
  502. void GDScriptParser::end_statement(const String &p_context) {
  503. bool found = false;
  504. while (is_statement_end() && !is_at_end()) {
  505. // Remove sequential newlines/semicolons.
  506. if (is_statement_end_token()) {
  507. // Only consume if this is an actual token.
  508. advance();
  509. } else if (lambda_ended) {
  510. lambda_ended = false; // Consume this "token".
  511. found = true;
  512. break;
  513. } else {
  514. if (!found) {
  515. lambda_ended = true; // Mark the lambda as done since we found something else to end the statement.
  516. found = true;
  517. }
  518. break;
  519. }
  520. found = true;
  521. }
  522. if (!found && !is_at_end()) {
  523. push_error(vformat(R"(Expected end of statement after %s, found "%s" instead.)", p_context, current.get_name()));
  524. }
  525. }
  526. void GDScriptParser::parse_program() {
  527. head = alloc_node<ClassNode>();
  528. head->start_line = 1;
  529. head->end_line = 1;
  530. head->fqcn = GDScript::canonicalize_path(script_path);
  531. current_class = head;
  532. bool can_have_class_or_extends = true;
  533. #define PUSH_PENDING_ANNOTATIONS_TO_HEAD \
  534. if (!annotation_stack.is_empty()) { \
  535. for (AnnotationNode * annot : annotation_stack) { \
  536. head->annotations.push_back(annot); \
  537. } \
  538. annotation_stack.clear(); \
  539. }
  540. while (!check(GDScriptTokenizer::Token::TK_EOF)) {
  541. if (match(GDScriptTokenizer::Token::ANNOTATION)) {
  542. AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STANDALONE);
  543. if (annotation != nullptr) {
  544. if (annotation->applies_to(AnnotationInfo::CLASS)) {
  545. // We do not know in advance what the annotation will be applied to: the `head` class or the subsequent inner class.
  546. // If we encounter `class_name`, `extends` or pure `SCRIPT` annotation, then it's `head`, otherwise it's an inner class.
  547. annotation_stack.push_back(annotation);
  548. } else if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
  549. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  550. if (annotation->name == SNAME("@tool") || annotation->name == SNAME("@icon")) {
  551. // Some annotations need to be resolved in the parser.
  552. annotation->apply(this, head, nullptr); // `head->outer == nullptr`.
  553. } else {
  554. head->annotations.push_back(annotation);
  555. }
  556. } else if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  557. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  558. push_error(R"(Expected newline after a standalone annotation.)");
  559. }
  560. if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
  561. head->add_member_group(annotation);
  562. // This annotation must appear after script-level annotations and `class_name`/`extends`,
  563. // so we stop looking for script-level stuff.
  564. can_have_class_or_extends = false;
  565. break;
  566. } else {
  567. // For potential non-group standalone annotations.
  568. push_error(R"(Unexpected standalone annotation.)");
  569. }
  570. } else {
  571. annotation_stack.push_back(annotation);
  572. // This annotation must appear after script-level annotations and `class_name`/`extends`,
  573. // so we stop looking for script-level stuff.
  574. can_have_class_or_extends = false;
  575. break;
  576. }
  577. }
  578. } else if (check(GDScriptTokenizer::Token::LITERAL) && current.literal.get_type() == Variant::STRING) {
  579. // Allow strings in class body as multiline comments.
  580. advance();
  581. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  582. push_error("Expected newline after comment string.");
  583. }
  584. } else {
  585. break;
  586. }
  587. }
  588. while (can_have_class_or_extends) {
  589. // Order here doesn't matter, but there should be only one of each at most.
  590. switch (current.type) {
  591. case GDScriptTokenizer::Token::CLASS_NAME:
  592. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  593. if (head->start_line == 1) {
  594. reset_extents(head, current);
  595. }
  596. advance();
  597. if (head->identifier != nullptr) {
  598. push_error(R"("class_name" can only be used once.)");
  599. } else {
  600. parse_class_name();
  601. }
  602. break;
  603. case GDScriptTokenizer::Token::EXTENDS:
  604. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  605. if (head->start_line == 1) {
  606. reset_extents(head, current);
  607. }
  608. advance();
  609. if (head->extends_used) {
  610. push_error(R"("extends" can only be used once.)");
  611. } else {
  612. parse_extends();
  613. end_statement("superclass");
  614. }
  615. break;
  616. case GDScriptTokenizer::Token::TK_EOF:
  617. PUSH_PENDING_ANNOTATIONS_TO_HEAD;
  618. can_have_class_or_extends = false;
  619. break;
  620. case GDScriptTokenizer::Token::LITERAL:
  621. if (current.literal.get_type() == Variant::STRING) {
  622. // Allow strings in class body as multiline comments.
  623. advance();
  624. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  625. push_error("Expected newline after comment string.");
  626. }
  627. break;
  628. }
  629. [[fallthrough]];
  630. default:
  631. // No tokens are allowed between script annotations and class/extends.
  632. can_have_class_or_extends = false;
  633. break;
  634. }
  635. if (panic_mode) {
  636. synchronize();
  637. }
  638. }
  639. // When the only thing needed is the class name and the icon, we don't need to parse the hole file.
  640. // It really speed up the call to GDScriptLanguage::get_global_class_name especially for large script.
  641. if (!parse_body) {
  642. return;
  643. }
  644. #undef PUSH_PENDING_ANNOTATIONS_TO_HEAD
  645. parse_class_body(true);
  646. complete_extents(head);
  647. #ifdef TOOLS_ENABLED
  648. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  649. int line = MIN(max_script_doc_line, head->end_line);
  650. while (line > 0) {
  651. if (comments.has(line) && comments[line].new_line && comments[line].comment.begins_with("##")) {
  652. head->doc_data = parse_class_doc_comment(line);
  653. break;
  654. }
  655. line--;
  656. }
  657. #endif // TOOLS_ENABLED
  658. if (!check(GDScriptTokenizer::Token::TK_EOF)) {
  659. push_error("Expected end of file.");
  660. }
  661. clear_unused_annotations();
  662. }
  663. Ref<GDScriptParserRef> GDScriptParser::get_depended_parser_for(const String &p_path) {
  664. Ref<GDScriptParserRef> ref;
  665. if (depended_parsers.has(p_path)) {
  666. ref = depended_parsers[p_path];
  667. } else {
  668. Error err = OK;
  669. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, script_path);
  670. if (ref.is_valid()) {
  671. depended_parsers[p_path] = ref;
  672. }
  673. }
  674. return ref;
  675. }
  676. const HashMap<String, Ref<GDScriptParserRef>> &GDScriptParser::get_depended_parsers() {
  677. return depended_parsers;
  678. }
  679. GDScriptParser::ClassNode *GDScriptParser::find_class(const String &p_qualified_name) const {
  680. String first = p_qualified_name.get_slice("::", 0);
  681. Vector<String> class_names;
  682. GDScriptParser::ClassNode *result = nullptr;
  683. // Empty initial name means start at the head.
  684. if (first.is_empty() || (head->identifier && first == head->identifier->name)) {
  685. class_names = p_qualified_name.split("::");
  686. result = head;
  687. } else if (p_qualified_name.begins_with(script_path)) {
  688. // Script path could have a class path separator("::") in it.
  689. class_names = p_qualified_name.trim_prefix(script_path).split("::");
  690. result = head;
  691. } else if (head->has_member(first)) {
  692. class_names = p_qualified_name.split("::");
  693. GDScriptParser::ClassNode::Member member = head->get_member(first);
  694. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  695. result = member.m_class;
  696. }
  697. }
  698. // Starts at index 1 because index 0 was handled above.
  699. for (int i = 1; result != nullptr && i < class_names.size(); i++) {
  700. const String &current_name = class_names[i];
  701. GDScriptParser::ClassNode *next = nullptr;
  702. if (result->has_member(current_name)) {
  703. GDScriptParser::ClassNode::Member member = result->get_member(current_name);
  704. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  705. next = member.m_class;
  706. }
  707. }
  708. result = next;
  709. }
  710. return result;
  711. }
  712. bool GDScriptParser::has_class(const GDScriptParser::ClassNode *p_class) const {
  713. if (head->fqcn.is_empty() && p_class->fqcn.get_slice("::", 0).is_empty()) {
  714. return p_class == head;
  715. } else if (p_class->fqcn.begins_with(head->fqcn)) {
  716. return find_class(p_class->fqcn.trim_prefix(head->fqcn)) == p_class;
  717. }
  718. return false;
  719. }
  720. GDScriptParser::ClassNode *GDScriptParser::parse_class(bool p_is_static) {
  721. ClassNode *n_class = alloc_node<ClassNode>();
  722. ClassNode *previous_class = current_class;
  723. current_class = n_class;
  724. n_class->outer = previous_class;
  725. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the class name after "class".)")) {
  726. n_class->identifier = parse_identifier();
  727. if (n_class->outer) {
  728. String fqcn = n_class->outer->fqcn;
  729. if (fqcn.is_empty()) {
  730. fqcn = GDScript::canonicalize_path(script_path);
  731. }
  732. n_class->fqcn = fqcn + "::" + n_class->identifier->name;
  733. } else {
  734. n_class->fqcn = n_class->identifier->name;
  735. }
  736. }
  737. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  738. parse_extends();
  739. }
  740. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after class declaration.)");
  741. bool multiline = match(GDScriptTokenizer::Token::NEWLINE);
  742. if (multiline && !consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block after class declaration.)")) {
  743. current_class = previous_class;
  744. complete_extents(n_class);
  745. return n_class;
  746. }
  747. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  748. if (n_class->extends_used) {
  749. push_error(R"(Cannot use "extends" more than once in the same class.)");
  750. }
  751. parse_extends();
  752. end_statement("superclass");
  753. }
  754. parse_class_body(multiline);
  755. complete_extents(n_class);
  756. if (multiline) {
  757. consume(GDScriptTokenizer::Token::DEDENT, R"(Missing unindent at the end of the class body.)");
  758. }
  759. current_class = previous_class;
  760. return n_class;
  761. }
  762. void GDScriptParser::parse_class_name() {
  763. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the global class name after "class_name".)")) {
  764. current_class->identifier = parse_identifier();
  765. current_class->fqcn = String(current_class->identifier->name);
  766. }
  767. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  768. // Allow extends on the same line.
  769. parse_extends();
  770. end_statement("superclass");
  771. } else {
  772. end_statement("class_name statement");
  773. }
  774. }
  775. void GDScriptParser::parse_extends() {
  776. current_class->extends_used = true;
  777. int chain_index = 0;
  778. if (match(GDScriptTokenizer::Token::LITERAL)) {
  779. if (previous.literal.get_type() != Variant::STRING) {
  780. push_error(vformat(R"(Only strings or identifiers can be used after "extends", found "%s" instead.)", Variant::get_type_name(previous.literal.get_type())));
  781. }
  782. current_class->extends_path = previous.literal;
  783. if (!match(GDScriptTokenizer::Token::PERIOD)) {
  784. return;
  785. }
  786. }
  787. make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
  788. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after "extends".)")) {
  789. return;
  790. }
  791. current_class->extends.push_back(parse_identifier());
  792. while (match(GDScriptTokenizer::Token::PERIOD)) {
  793. make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
  794. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after ".".)")) {
  795. return;
  796. }
  797. current_class->extends.push_back(parse_identifier());
  798. }
  799. }
  800. template <typename T>
  801. void GDScriptParser::parse_class_member(T *(GDScriptParser::*p_parse_function)(bool), AnnotationInfo::TargetKind p_target, const String &p_member_kind, bool p_is_static) {
  802. advance();
  803. // Consume annotations.
  804. List<AnnotationNode *> annotations;
  805. while (!annotation_stack.is_empty()) {
  806. AnnotationNode *last_annotation = annotation_stack.back()->get();
  807. if (last_annotation->applies_to(p_target)) {
  808. annotations.push_front(last_annotation);
  809. annotation_stack.pop_back();
  810. } else {
  811. push_error(vformat(R"(Annotation "%s" cannot be applied to a %s.)", last_annotation->name, p_member_kind));
  812. clear_unused_annotations();
  813. }
  814. }
  815. T *member = (this->*p_parse_function)(p_is_static);
  816. if (member == nullptr) {
  817. return;
  818. }
  819. #ifdef TOOLS_ENABLED
  820. int doc_comment_line = member->start_line - 1;
  821. #endif // TOOLS_ENABLED
  822. for (AnnotationNode *&annotation : annotations) {
  823. member->annotations.push_back(annotation);
  824. #ifdef TOOLS_ENABLED
  825. if (annotation->start_line <= doc_comment_line) {
  826. doc_comment_line = annotation->start_line - 1;
  827. }
  828. #endif // TOOLS_ENABLED
  829. }
  830. #ifdef TOOLS_ENABLED
  831. if constexpr (std::is_same_v<T, ClassNode>) {
  832. if (has_comment(member->start_line, true)) {
  833. // Inline doc comment.
  834. member->doc_data = parse_class_doc_comment(member->start_line, true);
  835. } else if (has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  836. // Normal doc comment. Don't check `min_member_doc_line` because a class ends parsing after its members.
  837. // This may not work correctly for cases like `var a; class B`, but it doesn't matter in practice.
  838. member->doc_data = parse_class_doc_comment(doc_comment_line);
  839. }
  840. } else {
  841. if (has_comment(member->start_line, true)) {
  842. // Inline doc comment.
  843. member->doc_data = parse_doc_comment(member->start_line, true);
  844. } else if (doc_comment_line >= min_member_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  845. // Normal doc comment.
  846. member->doc_data = parse_doc_comment(doc_comment_line);
  847. }
  848. }
  849. min_member_doc_line = member->end_line + 1; // Prevent multiple members from using the same doc comment.
  850. #endif // TOOLS_ENABLED
  851. if (member->identifier != nullptr) {
  852. if (!((String)member->identifier->name).is_empty()) { // Enums may be unnamed.
  853. if (current_class->members_indices.has(member->identifier->name)) {
  854. push_error(vformat(R"(%s "%s" has the same name as a previously declared %s.)", p_member_kind.capitalize(), member->identifier->name, current_class->get_member(member->identifier->name).get_type_name()), member->identifier);
  855. } else {
  856. current_class->add_member(member);
  857. }
  858. } else {
  859. current_class->add_member(member);
  860. }
  861. }
  862. }
  863. void GDScriptParser::parse_class_body(bool p_is_multiline) {
  864. bool class_end = false;
  865. bool next_is_static = false;
  866. while (!class_end && !is_at_end()) {
  867. GDScriptTokenizer::Token token = current;
  868. switch (token.type) {
  869. case GDScriptTokenizer::Token::VAR:
  870. parse_class_member(&GDScriptParser::parse_variable, AnnotationInfo::VARIABLE, "variable", next_is_static);
  871. if (next_is_static) {
  872. current_class->has_static_data = true;
  873. }
  874. break;
  875. case GDScriptTokenizer::Token::CONST:
  876. parse_class_member(&GDScriptParser::parse_constant, AnnotationInfo::CONSTANT, "constant");
  877. break;
  878. case GDScriptTokenizer::Token::SIGNAL:
  879. parse_class_member(&GDScriptParser::parse_signal, AnnotationInfo::SIGNAL, "signal");
  880. break;
  881. case GDScriptTokenizer::Token::FUNC:
  882. parse_class_member(&GDScriptParser::parse_function, AnnotationInfo::FUNCTION, "function", next_is_static);
  883. break;
  884. case GDScriptTokenizer::Token::CLASS:
  885. parse_class_member(&GDScriptParser::parse_class, AnnotationInfo::CLASS, "class");
  886. break;
  887. case GDScriptTokenizer::Token::ENUM:
  888. parse_class_member(&GDScriptParser::parse_enum, AnnotationInfo::NONE, "enum");
  889. break;
  890. case GDScriptTokenizer::Token::STATIC: {
  891. advance();
  892. next_is_static = true;
  893. if (!check(GDScriptTokenizer::Token::FUNC) && !check(GDScriptTokenizer::Token::VAR)) {
  894. push_error(R"(Expected "func" or "var" after "static".)");
  895. }
  896. } break;
  897. case GDScriptTokenizer::Token::ANNOTATION: {
  898. advance();
  899. // Check for class-level and standalone annotations.
  900. AnnotationNode *annotation = parse_annotation(AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STANDALONE);
  901. if (annotation != nullptr) {
  902. if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  903. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  904. push_error(R"(Expected newline after a standalone annotation.)");
  905. }
  906. if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
  907. current_class->add_member_group(annotation);
  908. } else {
  909. // For potential non-group standalone annotations.
  910. push_error(R"(Unexpected standalone annotation.)");
  911. }
  912. } else { // `AnnotationInfo::CLASS_LEVEL`.
  913. annotation_stack.push_back(annotation);
  914. }
  915. }
  916. break;
  917. }
  918. case GDScriptTokenizer::Token::PASS:
  919. advance();
  920. end_statement(R"("pass")");
  921. break;
  922. case GDScriptTokenizer::Token::DEDENT:
  923. class_end = true;
  924. break;
  925. case GDScriptTokenizer::Token::LITERAL:
  926. if (current.literal.get_type() == Variant::STRING) {
  927. // Allow strings in class body as multiline comments.
  928. advance();
  929. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  930. push_error("Expected newline after comment string.");
  931. }
  932. break;
  933. }
  934. [[fallthrough]];
  935. default:
  936. // Display a completion with identifiers.
  937. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  938. push_error(vformat(R"(Unexpected "%s" in class body.)", current.get_name()));
  939. advance();
  940. break;
  941. }
  942. if (token.type != GDScriptTokenizer::Token::STATIC) {
  943. next_is_static = false;
  944. }
  945. if (panic_mode) {
  946. synchronize();
  947. }
  948. if (!p_is_multiline) {
  949. class_end = true;
  950. }
  951. }
  952. }
  953. GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_static) {
  954. return parse_variable(p_is_static, true);
  955. }
  956. GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_static, bool p_allow_property) {
  957. VariableNode *variable = alloc_node<VariableNode>();
  958. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected variable name after "var".)")) {
  959. complete_extents(variable);
  960. return nullptr;
  961. }
  962. variable->identifier = parse_identifier();
  963. variable->export_info.name = variable->identifier->name;
  964. variable->is_static = p_is_static;
  965. if (match(GDScriptTokenizer::Token::COLON)) {
  966. if (check(GDScriptTokenizer::Token::NEWLINE)) {
  967. if (p_allow_property) {
  968. advance();
  969. return parse_property(variable, true);
  970. } else {
  971. push_error(R"(Expected type after ":")");
  972. complete_extents(variable);
  973. return nullptr;
  974. }
  975. } else if (check((GDScriptTokenizer::Token::EQUAL))) {
  976. // Infer type.
  977. variable->infer_datatype = true;
  978. } else {
  979. if (p_allow_property) {
  980. make_completion_context(COMPLETION_PROPERTY_DECLARATION_OR_TYPE, variable);
  981. if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
  982. // Check if get or set.
  983. if (current.get_identifier() == "get" || current.get_identifier() == "set") {
  984. return parse_property(variable, false);
  985. }
  986. }
  987. }
  988. // Parse type.
  989. variable->datatype_specifier = parse_type();
  990. }
  991. }
  992. if (match(GDScriptTokenizer::Token::EQUAL)) {
  993. // Initializer.
  994. variable->initializer = parse_expression(false);
  995. if (variable->initializer == nullptr) {
  996. push_error(R"(Expected expression for variable initial value after "=".)");
  997. }
  998. variable->assignments++;
  999. }
  1000. if (p_allow_property && match(GDScriptTokenizer::Token::COLON)) {
  1001. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1002. return parse_property(variable, true);
  1003. } else {
  1004. return parse_property(variable, false);
  1005. }
  1006. }
  1007. complete_extents(variable);
  1008. end_statement("variable declaration");
  1009. return variable;
  1010. }
  1011. GDScriptParser::VariableNode *GDScriptParser::parse_property(VariableNode *p_variable, bool p_need_indent) {
  1012. if (p_need_indent) {
  1013. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block for property after ":".)")) {
  1014. complete_extents(p_variable);
  1015. return nullptr;
  1016. }
  1017. }
  1018. VariableNode *property = p_variable;
  1019. make_completion_context(COMPLETION_PROPERTY_DECLARATION, property);
  1020. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected "get" or "set" for property declaration.)")) {
  1021. complete_extents(p_variable);
  1022. return nullptr;
  1023. }
  1024. IdentifierNode *function = parse_identifier();
  1025. if (check(GDScriptTokenizer::Token::EQUAL)) {
  1026. p_variable->property = VariableNode::PROP_SETGET;
  1027. } else {
  1028. p_variable->property = VariableNode::PROP_INLINE;
  1029. if (!p_need_indent) {
  1030. push_error("Property with inline code must go to an indented block.");
  1031. }
  1032. }
  1033. bool getter_used = false;
  1034. bool setter_used = false;
  1035. // Run with a loop because order doesn't matter.
  1036. for (int i = 0; i < 2; i++) {
  1037. if (function->name == SNAME("set")) {
  1038. if (setter_used) {
  1039. push_error(R"(Properties can only have one setter.)");
  1040. } else {
  1041. parse_property_setter(property);
  1042. setter_used = true;
  1043. }
  1044. } else if (function->name == SNAME("get")) {
  1045. if (getter_used) {
  1046. push_error(R"(Properties can only have one getter.)");
  1047. } else {
  1048. parse_property_getter(property);
  1049. getter_used = true;
  1050. }
  1051. } else {
  1052. // TODO: Update message to only have the missing one if it's the case.
  1053. push_error(R"(Expected "get" or "set" for property declaration.)");
  1054. }
  1055. if (i == 0 && p_variable->property == VariableNode::PROP_SETGET) {
  1056. if (match(GDScriptTokenizer::Token::COMMA)) {
  1057. // Consume potential newline.
  1058. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1059. if (!p_need_indent) {
  1060. push_error(R"(Inline setter/getter setting cannot span across multiple lines (use "\\"" if needed).)");
  1061. }
  1062. }
  1063. } else {
  1064. break;
  1065. }
  1066. }
  1067. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  1068. break;
  1069. }
  1070. function = parse_identifier();
  1071. }
  1072. complete_extents(p_variable);
  1073. if (p_variable->property == VariableNode::PROP_SETGET) {
  1074. end_statement("property declaration");
  1075. }
  1076. if (p_need_indent) {
  1077. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected end of indented block for property.)");
  1078. }
  1079. return property;
  1080. }
  1081. void GDScriptParser::parse_property_setter(VariableNode *p_variable) {
  1082. switch (p_variable->property) {
  1083. case VariableNode::PROP_INLINE: {
  1084. FunctionNode *function = alloc_node<FunctionNode>();
  1085. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1086. complete_extents(identifier);
  1087. identifier->name = "@" + p_variable->identifier->name + "_setter";
  1088. function->identifier = identifier;
  1089. function->is_static = p_variable->is_static;
  1090. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "set".)");
  1091. ParameterNode *parameter = alloc_node<ParameterNode>();
  1092. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name after "(".)")) {
  1093. reset_extents(parameter, previous);
  1094. p_variable->setter_parameter = parse_identifier();
  1095. parameter->identifier = p_variable->setter_parameter;
  1096. function->parameters_indices[parameter->identifier->name] = 0;
  1097. function->parameters.push_back(parameter);
  1098. }
  1099. complete_extents(parameter);
  1100. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after parameter name.)*");
  1101. consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after ")".)*");
  1102. FunctionNode *previous_function = current_function;
  1103. current_function = function;
  1104. if (p_variable->setter_parameter != nullptr) {
  1105. SuiteNode *body = alloc_node<SuiteNode>();
  1106. body->add_local(parameter, function);
  1107. function->body = parse_suite("setter declaration", body);
  1108. p_variable->setter = function;
  1109. }
  1110. current_function = previous_function;
  1111. complete_extents(function);
  1112. break;
  1113. }
  1114. case VariableNode::PROP_SETGET:
  1115. consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "set")");
  1116. make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
  1117. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected setter function name after "=".)")) {
  1118. p_variable->setter_pointer = parse_identifier();
  1119. }
  1120. break;
  1121. case VariableNode::PROP_NONE:
  1122. break; // Unreachable.
  1123. }
  1124. }
  1125. void GDScriptParser::parse_property_getter(VariableNode *p_variable) {
  1126. switch (p_variable->property) {
  1127. case VariableNode::PROP_INLINE: {
  1128. FunctionNode *function = alloc_node<FunctionNode>();
  1129. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1130. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after "get(".)*");
  1131. consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after "get()".)*");
  1132. } else {
  1133. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" or "(" after "get".)");
  1134. }
  1135. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1136. complete_extents(identifier);
  1137. identifier->name = "@" + p_variable->identifier->name + "_getter";
  1138. function->identifier = identifier;
  1139. function->is_static = p_variable->is_static;
  1140. FunctionNode *previous_function = current_function;
  1141. current_function = function;
  1142. SuiteNode *body = alloc_node<SuiteNode>();
  1143. function->body = parse_suite("getter declaration", body);
  1144. p_variable->getter = function;
  1145. current_function = previous_function;
  1146. complete_extents(function);
  1147. break;
  1148. }
  1149. case VariableNode::PROP_SETGET:
  1150. consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "get")");
  1151. make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
  1152. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected getter function name after "=".)")) {
  1153. p_variable->getter_pointer = parse_identifier();
  1154. }
  1155. break;
  1156. case VariableNode::PROP_NONE:
  1157. break; // Unreachable.
  1158. }
  1159. }
  1160. GDScriptParser::ConstantNode *GDScriptParser::parse_constant(bool p_is_static) {
  1161. ConstantNode *constant = alloc_node<ConstantNode>();
  1162. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected constant name after "const".)")) {
  1163. complete_extents(constant);
  1164. return nullptr;
  1165. }
  1166. constant->identifier = parse_identifier();
  1167. if (match(GDScriptTokenizer::Token::COLON)) {
  1168. if (check((GDScriptTokenizer::Token::EQUAL))) {
  1169. // Infer type.
  1170. constant->infer_datatype = true;
  1171. } else {
  1172. // Parse type.
  1173. constant->datatype_specifier = parse_type();
  1174. }
  1175. }
  1176. if (consume(GDScriptTokenizer::Token::EQUAL, R"(Expected initializer after constant name.)")) {
  1177. // Initializer.
  1178. constant->initializer = parse_expression(false);
  1179. if (constant->initializer == nullptr) {
  1180. push_error(R"(Expected initializer expression for constant.)");
  1181. complete_extents(constant);
  1182. return nullptr;
  1183. }
  1184. } else {
  1185. complete_extents(constant);
  1186. return nullptr;
  1187. }
  1188. complete_extents(constant);
  1189. end_statement("constant declaration");
  1190. return constant;
  1191. }
  1192. GDScriptParser::ParameterNode *GDScriptParser::parse_parameter() {
  1193. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name.)")) {
  1194. return nullptr;
  1195. }
  1196. ParameterNode *parameter = alloc_node<ParameterNode>();
  1197. parameter->identifier = parse_identifier();
  1198. if (match(GDScriptTokenizer::Token::COLON)) {
  1199. if (check((GDScriptTokenizer::Token::EQUAL))) {
  1200. // Infer type.
  1201. parameter->infer_datatype = true;
  1202. } else {
  1203. // Parse type.
  1204. make_completion_context(COMPLETION_TYPE_NAME, parameter);
  1205. parameter->datatype_specifier = parse_type();
  1206. }
  1207. }
  1208. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1209. // Default value.
  1210. parameter->initializer = parse_expression(false);
  1211. }
  1212. complete_extents(parameter);
  1213. return parameter;
  1214. }
  1215. GDScriptParser::SignalNode *GDScriptParser::parse_signal(bool p_is_static) {
  1216. SignalNode *signal = alloc_node<SignalNode>();
  1217. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected signal name after "signal".)")) {
  1218. complete_extents(signal);
  1219. return nullptr;
  1220. }
  1221. signal->identifier = parse_identifier();
  1222. if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1223. push_multiline(true);
  1224. advance();
  1225. do {
  1226. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1227. // Allow for trailing comma.
  1228. break;
  1229. }
  1230. ParameterNode *parameter = parse_parameter();
  1231. if (parameter == nullptr) {
  1232. push_error("Expected signal parameter name.");
  1233. break;
  1234. }
  1235. if (parameter->initializer != nullptr) {
  1236. push_error(R"(Signal parameters cannot have a default value.)");
  1237. }
  1238. if (signal->parameters_indices.has(parameter->identifier->name)) {
  1239. push_error(vformat(R"(Parameter with name "%s" was already declared for this signal.)", parameter->identifier->name));
  1240. } else {
  1241. signal->parameters_indices[parameter->identifier->name] = signal->parameters.size();
  1242. signal->parameters.push_back(parameter);
  1243. }
  1244. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1245. pop_multiline();
  1246. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after signal parameters.)*");
  1247. }
  1248. complete_extents(signal);
  1249. end_statement("signal declaration");
  1250. return signal;
  1251. }
  1252. GDScriptParser::EnumNode *GDScriptParser::parse_enum(bool p_is_static) {
  1253. EnumNode *enum_node = alloc_node<EnumNode>();
  1254. bool named = false;
  1255. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  1256. enum_node->identifier = parse_identifier();
  1257. named = true;
  1258. }
  1259. push_multiline(true);
  1260. consume(GDScriptTokenizer::Token::BRACE_OPEN, vformat(R"(Expected "{" after %s.)", named ? "enum name" : R"("enum")"));
  1261. #ifdef TOOLS_ENABLED
  1262. int min_enum_value_doc_line = previous.end_line + 1;
  1263. #endif
  1264. HashMap<StringName, int> elements;
  1265. #ifdef DEBUG_ENABLED
  1266. List<MethodInfo> gdscript_funcs;
  1267. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  1268. #endif
  1269. do {
  1270. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  1271. break; // Allow trailing comma.
  1272. }
  1273. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for enum key.)")) {
  1274. GDScriptParser::IdentifierNode *identifier = parse_identifier();
  1275. EnumNode::Value item;
  1276. item.identifier = identifier;
  1277. item.parent_enum = enum_node;
  1278. item.line = previous.start_line;
  1279. item.leftmost_column = previous.leftmost_column;
  1280. item.rightmost_column = previous.rightmost_column;
  1281. if (elements.has(item.identifier->name)) {
  1282. push_error(vformat(R"(Name "%s" was already in this enum (at line %d).)", item.identifier->name, elements[item.identifier->name]), item.identifier);
  1283. } else if (!named) {
  1284. if (current_class->members_indices.has(item.identifier->name)) {
  1285. push_error(vformat(R"(Name "%s" is already used as a class %s.)", item.identifier->name, current_class->get_member(item.identifier->name).get_type_name()));
  1286. }
  1287. }
  1288. elements[item.identifier->name] = item.line;
  1289. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1290. ExpressionNode *value = parse_expression(false);
  1291. if (value == nullptr) {
  1292. push_error(R"(Expected expression value after "=".)");
  1293. }
  1294. item.custom_value = value;
  1295. }
  1296. item.index = enum_node->values.size();
  1297. enum_node->values.push_back(item);
  1298. if (!named) {
  1299. // Add as member of current class.
  1300. current_class->add_member(item);
  1301. }
  1302. }
  1303. } while (match(GDScriptTokenizer::Token::COMMA));
  1304. #ifdef TOOLS_ENABLED
  1305. // Enum values documentation.
  1306. for (int i = 0; i < enum_node->values.size(); i++) {
  1307. int enum_value_line = enum_node->values[i].line;
  1308. int doc_comment_line = enum_value_line - 1;
  1309. MemberDocData doc_data;
  1310. if (has_comment(enum_value_line, true)) {
  1311. // Inline doc comment.
  1312. if (i == enum_node->values.size() - 1 || enum_node->values[i + 1].line > enum_value_line) {
  1313. doc_data = parse_doc_comment(enum_value_line, true);
  1314. }
  1315. } else if (doc_comment_line >= min_enum_value_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
  1316. // Normal doc comment.
  1317. doc_data = parse_doc_comment(doc_comment_line);
  1318. }
  1319. if (named) {
  1320. enum_node->values.write[i].doc_data = doc_data;
  1321. } else {
  1322. current_class->set_enum_value_doc_data(enum_node->values[i].identifier->name, doc_data);
  1323. }
  1324. min_enum_value_doc_line = enum_value_line + 1; // Prevent multiple enum values from using the same doc comment.
  1325. }
  1326. #endif // TOOLS_ENABLED
  1327. pop_multiline();
  1328. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" for enum.)");
  1329. complete_extents(enum_node);
  1330. end_statement("enum");
  1331. return enum_node;
  1332. }
  1333. void GDScriptParser::parse_function_signature(FunctionNode *p_function, SuiteNode *p_body, const String &p_type) {
  1334. if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
  1335. bool default_used = false;
  1336. do {
  1337. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1338. // Allow for trailing comma.
  1339. break;
  1340. }
  1341. ParameterNode *parameter = parse_parameter();
  1342. if (parameter == nullptr) {
  1343. break;
  1344. }
  1345. if (parameter->initializer != nullptr) {
  1346. default_used = true;
  1347. } else {
  1348. if (default_used) {
  1349. push_error("Cannot have mandatory parameters after optional parameters.");
  1350. continue;
  1351. }
  1352. }
  1353. if (p_function->parameters_indices.has(parameter->identifier->name)) {
  1354. push_error(vformat(R"(Parameter with name "%s" was already declared for this %s.)", parameter->identifier->name, p_type));
  1355. } else {
  1356. p_function->parameters_indices[parameter->identifier->name] = p_function->parameters.size();
  1357. p_function->parameters.push_back(parameter);
  1358. p_body->add_local(parameter, current_function);
  1359. }
  1360. } while (match(GDScriptTokenizer::Token::COMMA));
  1361. }
  1362. pop_multiline();
  1363. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, vformat(R"*(Expected closing ")" after %s parameters.)*", p_type));
  1364. if (match(GDScriptTokenizer::Token::FORWARD_ARROW)) {
  1365. make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, p_function);
  1366. p_function->return_type = parse_type(true);
  1367. if (p_function->return_type == nullptr) {
  1368. push_error(R"(Expected return type or "void" after "->".)");
  1369. }
  1370. }
  1371. if (!p_function->source_lambda && p_function->identifier && p_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init) {
  1372. if (!p_function->is_static) {
  1373. push_error(R"(Static constructor must be declared static.)");
  1374. }
  1375. if (p_function->parameters.size() != 0) {
  1376. push_error(R"(Static constructor cannot have parameters.)");
  1377. }
  1378. current_class->has_static_data = true;
  1379. }
  1380. // TODO: Improve token consumption so it synchronizes to a statement boundary. This way we can get into the function body with unrecognized tokens.
  1381. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after %s declaration.)", p_type));
  1382. }
  1383. GDScriptParser::FunctionNode *GDScriptParser::parse_function(bool p_is_static) {
  1384. FunctionNode *function = alloc_node<FunctionNode>();
  1385. make_completion_context(COMPLETION_OVERRIDE_METHOD, function);
  1386. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) {
  1387. complete_extents(function);
  1388. return nullptr;
  1389. }
  1390. FunctionNode *previous_function = current_function;
  1391. current_function = function;
  1392. function->identifier = parse_identifier();
  1393. function->is_static = p_is_static;
  1394. SuiteNode *body = alloc_node<SuiteNode>();
  1395. SuiteNode *previous_suite = current_suite;
  1396. current_suite = body;
  1397. push_multiline(true);
  1398. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)");
  1399. parse_function_signature(function, body, "function");
  1400. current_suite = previous_suite;
  1401. function->body = parse_suite("function declaration", body);
  1402. current_function = previous_function;
  1403. complete_extents(function);
  1404. return function;
  1405. }
  1406. GDScriptParser::AnnotationNode *GDScriptParser::parse_annotation(uint32_t p_valid_targets) {
  1407. AnnotationNode *annotation = alloc_node<AnnotationNode>();
  1408. annotation->name = previous.literal;
  1409. make_completion_context(COMPLETION_ANNOTATION, annotation);
  1410. bool valid = true;
  1411. if (!valid_annotations.has(annotation->name)) {
  1412. push_error(vformat(R"(Unrecognized annotation: "%s".)", annotation->name));
  1413. valid = false;
  1414. }
  1415. annotation->info = &valid_annotations[annotation->name];
  1416. if (!annotation->applies_to(p_valid_targets)) {
  1417. if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
  1418. push_error(vformat(R"(Annotation "%s" must be at the top of the script, before "extends" and "class_name".)", annotation->name));
  1419. } else {
  1420. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name));
  1421. }
  1422. valid = false;
  1423. }
  1424. if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1425. push_multiline(true);
  1426. advance();
  1427. // Arguments.
  1428. push_completion_call(annotation);
  1429. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, 0);
  1430. int argument_index = 0;
  1431. do {
  1432. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1433. // Allow for trailing comma.
  1434. break;
  1435. }
  1436. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index);
  1437. set_last_completion_call_arg(argument_index++);
  1438. ExpressionNode *argument = parse_expression(false);
  1439. if (argument == nullptr) {
  1440. push_error("Expected expression as the annotation argument.");
  1441. valid = false;
  1442. continue;
  1443. }
  1444. annotation->arguments.push_back(argument);
  1445. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1446. pop_multiline();
  1447. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after annotation arguments.)*");
  1448. pop_completion_call();
  1449. }
  1450. complete_extents(annotation);
  1451. match(GDScriptTokenizer::Token::NEWLINE); // Newline after annotation is optional.
  1452. if (valid) {
  1453. valid = validate_annotation_arguments(annotation);
  1454. }
  1455. return valid ? annotation : nullptr;
  1456. }
  1457. void GDScriptParser::clear_unused_annotations() {
  1458. for (const AnnotationNode *annotation : annotation_stack) {
  1459. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  1460. }
  1461. annotation_stack.clear();
  1462. }
  1463. bool GDScriptParser::register_annotation(const MethodInfo &p_info, uint32_t p_target_kinds, AnnotationAction p_apply, const Vector<Variant> &p_default_arguments, bool p_is_vararg) {
  1464. ERR_FAIL_COND_V_MSG(valid_annotations.has(p_info.name), false, vformat(R"(Annotation "%s" already registered.)", p_info.name));
  1465. AnnotationInfo new_annotation;
  1466. new_annotation.info = p_info;
  1467. new_annotation.info.default_arguments = p_default_arguments;
  1468. if (p_is_vararg) {
  1469. new_annotation.info.flags |= METHOD_FLAG_VARARG;
  1470. }
  1471. new_annotation.apply = p_apply;
  1472. new_annotation.target_kind = p_target_kinds;
  1473. valid_annotations[p_info.name] = new_annotation;
  1474. return true;
  1475. }
  1476. GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite, bool p_for_lambda) {
  1477. SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>();
  1478. suite->parent_block = current_suite;
  1479. suite->parent_function = current_function;
  1480. current_suite = suite;
  1481. if (!p_for_lambda && suite->parent_block != nullptr && suite->parent_block->is_in_loop) {
  1482. // Do not reset to false if true is set before calling parse_suite().
  1483. suite->is_in_loop = true;
  1484. }
  1485. bool multiline = false;
  1486. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1487. multiline = true;
  1488. }
  1489. if (multiline) {
  1490. if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
  1491. current_suite = suite->parent_block;
  1492. complete_extents(suite);
  1493. return suite;
  1494. }
  1495. }
  1496. reset_extents(suite, current);
  1497. int error_count = 0;
  1498. do {
  1499. if (is_at_end() || (!multiline && previous.type == GDScriptTokenizer::Token::SEMICOLON && check(GDScriptTokenizer::Token::NEWLINE))) {
  1500. break;
  1501. }
  1502. Node *statement = parse_statement();
  1503. if (statement == nullptr) {
  1504. if (error_count++ > 100) {
  1505. push_error("Too many statement errors.", suite);
  1506. break;
  1507. }
  1508. continue;
  1509. }
  1510. suite->statements.push_back(statement);
  1511. // Register locals.
  1512. switch (statement->type) {
  1513. case Node::VARIABLE: {
  1514. VariableNode *variable = static_cast<VariableNode *>(statement);
  1515. const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
  1516. if (local.type != SuiteNode::Local::UNDEFINED) {
  1517. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name), variable->identifier);
  1518. }
  1519. current_suite->add_local(variable, current_function);
  1520. break;
  1521. }
  1522. case Node::CONSTANT: {
  1523. ConstantNode *constant = static_cast<ConstantNode *>(statement);
  1524. const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
  1525. if (local.type != SuiteNode::Local::UNDEFINED) {
  1526. String name;
  1527. if (local.type == SuiteNode::Local::CONSTANT) {
  1528. name = "constant";
  1529. } else {
  1530. name = "variable";
  1531. }
  1532. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name), constant->identifier);
  1533. }
  1534. current_suite->add_local(constant, current_function);
  1535. break;
  1536. }
  1537. default:
  1538. break;
  1539. }
  1540. } while ((multiline || previous.type == GDScriptTokenizer::Token::SEMICOLON) && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end());
  1541. complete_extents(suite);
  1542. if (multiline) {
  1543. if (!lambda_ended) {
  1544. consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
  1545. } else {
  1546. match(GDScriptTokenizer::Token::DEDENT);
  1547. }
  1548. } else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  1549. consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context));
  1550. }
  1551. if (p_for_lambda) {
  1552. lambda_ended = true;
  1553. }
  1554. current_suite = suite->parent_block;
  1555. return suite;
  1556. }
  1557. GDScriptParser::Node *GDScriptParser::parse_statement() {
  1558. Node *result = nullptr;
  1559. #ifdef DEBUG_ENABLED
  1560. bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
  1561. #endif
  1562. List<AnnotationNode *> annotations;
  1563. if (current.type != GDScriptTokenizer::Token::ANNOTATION) {
  1564. while (!annotation_stack.is_empty()) {
  1565. AnnotationNode *last_annotation = annotation_stack.back()->get();
  1566. if (last_annotation->applies_to(AnnotationInfo::STATEMENT)) {
  1567. annotations.push_front(last_annotation);
  1568. annotation_stack.pop_back();
  1569. } else {
  1570. push_error(vformat(R"(Annotation "%s" cannot be applied to a statement.)", last_annotation->name));
  1571. clear_unused_annotations();
  1572. }
  1573. }
  1574. }
  1575. switch (current.type) {
  1576. case GDScriptTokenizer::Token::PASS:
  1577. advance();
  1578. result = alloc_node<PassNode>();
  1579. complete_extents(result);
  1580. end_statement(R"("pass")");
  1581. break;
  1582. case GDScriptTokenizer::Token::VAR:
  1583. advance();
  1584. result = parse_variable(false, false);
  1585. break;
  1586. case GDScriptTokenizer::Token::CONST:
  1587. advance();
  1588. result = parse_constant(false);
  1589. break;
  1590. case GDScriptTokenizer::Token::IF:
  1591. advance();
  1592. result = parse_if();
  1593. break;
  1594. case GDScriptTokenizer::Token::FOR:
  1595. advance();
  1596. result = parse_for();
  1597. break;
  1598. case GDScriptTokenizer::Token::WHILE:
  1599. advance();
  1600. result = parse_while();
  1601. break;
  1602. case GDScriptTokenizer::Token::MATCH:
  1603. advance();
  1604. result = parse_match();
  1605. break;
  1606. case GDScriptTokenizer::Token::BREAK:
  1607. advance();
  1608. result = parse_break();
  1609. break;
  1610. case GDScriptTokenizer::Token::CONTINUE:
  1611. advance();
  1612. result = parse_continue();
  1613. break;
  1614. case GDScriptTokenizer::Token::RETURN: {
  1615. advance();
  1616. ReturnNode *n_return = alloc_node<ReturnNode>();
  1617. if (!is_statement_end()) {
  1618. if (current_function && (current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init || current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init)) {
  1619. push_error(R"(Constructor cannot return a value.)");
  1620. }
  1621. n_return->return_value = parse_expression(false);
  1622. } else if (in_lambda && !is_statement_end_token()) {
  1623. // Try to parse it anyway as this might not be the statement end in a lambda.
  1624. // If this fails the expression will be nullptr, but that's the same as no return, so it's fine.
  1625. n_return->return_value = parse_expression(false);
  1626. }
  1627. complete_extents(n_return);
  1628. result = n_return;
  1629. current_suite->has_return = true;
  1630. end_statement("return statement");
  1631. break;
  1632. }
  1633. case GDScriptTokenizer::Token::BREAKPOINT:
  1634. advance();
  1635. result = alloc_node<BreakpointNode>();
  1636. complete_extents(result);
  1637. end_statement(R"("breakpoint")");
  1638. break;
  1639. case GDScriptTokenizer::Token::ASSERT:
  1640. advance();
  1641. result = parse_assert();
  1642. break;
  1643. case GDScriptTokenizer::Token::ANNOTATION: {
  1644. advance();
  1645. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  1646. if (annotation != nullptr) {
  1647. annotation_stack.push_back(annotation);
  1648. }
  1649. break;
  1650. }
  1651. default: {
  1652. // Expression statement.
  1653. ExpressionNode *expression = parse_expression(true); // Allow assignment here.
  1654. bool has_ended_lambda = false;
  1655. if (expression == nullptr) {
  1656. if (in_lambda) {
  1657. // If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is.
  1658. lambda_ended = true;
  1659. has_ended_lambda = true;
  1660. } else {
  1661. advance();
  1662. push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
  1663. }
  1664. } else {
  1665. end_statement("expression");
  1666. }
  1667. lambda_ended = lambda_ended || has_ended_lambda;
  1668. result = expression;
  1669. #ifdef DEBUG_ENABLED
  1670. if (expression != nullptr) {
  1671. switch (expression->type) {
  1672. case Node::ASSIGNMENT:
  1673. case Node::AWAIT:
  1674. case Node::CALL:
  1675. // Fine.
  1676. break;
  1677. case Node::PRELOAD:
  1678. // `preload` is a function-like keyword.
  1679. push_warning(expression, GDScriptWarning::RETURN_VALUE_DISCARDED, "preload");
  1680. break;
  1681. case Node::LAMBDA:
  1682. // Standalone lambdas can't be used, so make this an error.
  1683. push_error("Standalone lambdas cannot be accessed. Consider assigning it to a variable.", expression);
  1684. break;
  1685. case Node::LITERAL:
  1686. // Allow strings as multiline comments.
  1687. if (static_cast<GDScriptParser::LiteralNode *>(expression)->value.get_type() != Variant::STRING) {
  1688. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1689. }
  1690. break;
  1691. case Node::TERNARY_OPERATOR:
  1692. push_warning(expression, GDScriptWarning::STANDALONE_TERNARY);
  1693. break;
  1694. default:
  1695. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1696. }
  1697. }
  1698. #endif
  1699. break;
  1700. }
  1701. }
  1702. if (result != nullptr && !annotations.is_empty()) {
  1703. for (AnnotationNode *&annotation : annotations) {
  1704. result->annotations.push_back(annotation);
  1705. }
  1706. }
  1707. #ifdef DEBUG_ENABLED
  1708. if (unreachable && result != nullptr) {
  1709. current_suite->has_unreachable_code = true;
  1710. if (current_function) {
  1711. push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>");
  1712. } else {
  1713. // TODO: Properties setters and getters with unreachable code are not being warned
  1714. }
  1715. }
  1716. #endif
  1717. if (panic_mode) {
  1718. synchronize();
  1719. }
  1720. return result;
  1721. }
  1722. GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
  1723. // TODO: Add assert message.
  1724. AssertNode *assert = alloc_node<AssertNode>();
  1725. push_multiline(true);
  1726. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
  1727. assert->condition = parse_expression(false);
  1728. if (assert->condition == nullptr) {
  1729. push_error("Expected expression to assert.");
  1730. pop_multiline();
  1731. complete_extents(assert);
  1732. return nullptr;
  1733. }
  1734. if (match(GDScriptTokenizer::Token::COMMA) && !check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1735. assert->message = parse_expression(false);
  1736. if (assert->message == nullptr) {
  1737. push_error(R"(Expected error message for assert after ",".)");
  1738. pop_multiline();
  1739. complete_extents(assert);
  1740. return nullptr;
  1741. }
  1742. match(GDScriptTokenizer::Token::COMMA);
  1743. }
  1744. pop_multiline();
  1745. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
  1746. complete_extents(assert);
  1747. end_statement(R"("assert")");
  1748. return assert;
  1749. }
  1750. GDScriptParser::BreakNode *GDScriptParser::parse_break() {
  1751. if (!can_break) {
  1752. push_error(R"(Cannot use "break" outside of a loop.)");
  1753. }
  1754. BreakNode *break_node = alloc_node<BreakNode>();
  1755. complete_extents(break_node);
  1756. end_statement(R"("break")");
  1757. return break_node;
  1758. }
  1759. GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
  1760. if (!can_continue) {
  1761. push_error(R"(Cannot use "continue" outside of a loop.)");
  1762. }
  1763. current_suite->has_continue = true;
  1764. ContinueNode *cont = alloc_node<ContinueNode>();
  1765. complete_extents(cont);
  1766. end_statement(R"("continue")");
  1767. return cont;
  1768. }
  1769. GDScriptParser::ForNode *GDScriptParser::parse_for() {
  1770. ForNode *n_for = alloc_node<ForNode>();
  1771. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
  1772. n_for->variable = parse_identifier();
  1773. }
  1774. if (match(GDScriptTokenizer::Token::COLON)) {
  1775. n_for->datatype_specifier = parse_type();
  1776. if (n_for->datatype_specifier == nullptr) {
  1777. push_error(R"(Expected type specifier after ":".)");
  1778. }
  1779. }
  1780. if (n_for->datatype_specifier == nullptr) {
  1781. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" or ":" after "for" variable name.)");
  1782. } else {
  1783. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "for" variable type specifier.)");
  1784. }
  1785. n_for->list = parse_expression(false);
  1786. if (!n_for->list) {
  1787. push_error(R"(Expected iterable after "in".)");
  1788. }
  1789. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
  1790. // Save break/continue state.
  1791. bool could_break = can_break;
  1792. bool could_continue = can_continue;
  1793. // Allow break/continue.
  1794. can_break = true;
  1795. can_continue = true;
  1796. SuiteNode *suite = alloc_node<SuiteNode>();
  1797. if (n_for->variable) {
  1798. const SuiteNode::Local &local = current_suite->get_local(n_for->variable->name);
  1799. if (local.type != SuiteNode::Local::UNDEFINED) {
  1800. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), n_for->variable->name), n_for->variable);
  1801. }
  1802. suite->add_local(SuiteNode::Local(n_for->variable, current_function));
  1803. }
  1804. suite->is_in_loop = true;
  1805. n_for->loop = parse_suite(R"("for" block)", suite);
  1806. complete_extents(n_for);
  1807. // Reset break/continue state.
  1808. can_break = could_break;
  1809. can_continue = could_continue;
  1810. return n_for;
  1811. }
  1812. GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
  1813. IfNode *n_if = alloc_node<IfNode>();
  1814. n_if->condition = parse_expression(false);
  1815. if (n_if->condition == nullptr) {
  1816. push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
  1817. }
  1818. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
  1819. n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
  1820. n_if->true_block->parent_if = n_if;
  1821. if (n_if->true_block->has_continue) {
  1822. current_suite->has_continue = true;
  1823. }
  1824. if (match(GDScriptTokenizer::Token::ELIF)) {
  1825. SuiteNode *else_block = alloc_node<SuiteNode>();
  1826. else_block->parent_function = current_function;
  1827. else_block->parent_block = current_suite;
  1828. SuiteNode *previous_suite = current_suite;
  1829. current_suite = else_block;
  1830. IfNode *elif = parse_if("elif");
  1831. else_block->statements.push_back(elif);
  1832. complete_extents(else_block);
  1833. n_if->false_block = else_block;
  1834. current_suite = previous_suite;
  1835. } else if (match(GDScriptTokenizer::Token::ELSE)) {
  1836. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
  1837. n_if->false_block = parse_suite(R"("else" block)");
  1838. }
  1839. complete_extents(n_if);
  1840. if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
  1841. current_suite->has_return = true;
  1842. }
  1843. if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
  1844. current_suite->has_continue = true;
  1845. }
  1846. return n_if;
  1847. }
  1848. GDScriptParser::MatchNode *GDScriptParser::parse_match() {
  1849. MatchNode *match_node = alloc_node<MatchNode>();
  1850. match_node->test = parse_expression(false);
  1851. if (match_node->test == nullptr) {
  1852. push_error(R"(Expected expression to test after "match".)");
  1853. }
  1854. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
  1855. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
  1856. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
  1857. complete_extents(match_node);
  1858. return match_node;
  1859. }
  1860. bool all_have_return = true;
  1861. bool have_wildcard = false;
  1862. List<AnnotationNode *> match_branch_annotation_stack;
  1863. while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
  1864. if (match(GDScriptTokenizer::Token::PASS)) {
  1865. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected newline after "pass".)");
  1866. continue;
  1867. }
  1868. if (match(GDScriptTokenizer::Token::ANNOTATION)) {
  1869. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  1870. if (annotation == nullptr) {
  1871. continue;
  1872. }
  1873. if (annotation->name != SNAME("@warning_ignore")) {
  1874. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name), annotation);
  1875. continue;
  1876. }
  1877. match_branch_annotation_stack.push_back(annotation);
  1878. continue;
  1879. }
  1880. MatchBranchNode *branch = parse_match_branch();
  1881. if (branch == nullptr) {
  1882. advance();
  1883. continue;
  1884. }
  1885. for (AnnotationNode *annotation : match_branch_annotation_stack) {
  1886. branch->annotations.push_back(annotation);
  1887. }
  1888. match_branch_annotation_stack.clear();
  1889. #ifdef DEBUG_ENABLED
  1890. if (have_wildcard && !branch->patterns.is_empty()) {
  1891. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  1892. }
  1893. #endif
  1894. have_wildcard = have_wildcard || branch->has_wildcard;
  1895. all_have_return = all_have_return && branch->block->has_return;
  1896. match_node->branches.push_back(branch);
  1897. }
  1898. complete_extents(match_node);
  1899. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  1900. if (all_have_return && have_wildcard) {
  1901. current_suite->has_return = true;
  1902. }
  1903. for (const AnnotationNode *annotation : match_branch_annotation_stack) {
  1904. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  1905. }
  1906. match_branch_annotation_stack.clear();
  1907. return match_node;
  1908. }
  1909. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  1910. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  1911. reset_extents(branch, current);
  1912. bool has_bind = false;
  1913. do {
  1914. PatternNode *pattern = parse_match_pattern();
  1915. if (pattern == nullptr) {
  1916. continue;
  1917. }
  1918. if (pattern->binds.size() > 0) {
  1919. has_bind = true;
  1920. }
  1921. if (branch->patterns.size() > 0 && has_bind) {
  1922. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  1923. }
  1924. if (pattern->pattern_type == PatternNode::PT_REST) {
  1925. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  1926. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  1927. branch->has_wildcard = true;
  1928. }
  1929. branch->patterns.push_back(pattern);
  1930. } while (match(GDScriptTokenizer::Token::COMMA));
  1931. if (branch->patterns.is_empty()) {
  1932. push_error(R"(No pattern found for "match" branch.)");
  1933. }
  1934. bool has_guard = false;
  1935. if (match(GDScriptTokenizer::Token::WHEN)) {
  1936. // Pattern guard.
  1937. // Create block for guard because it also needs to access the bound variables from patterns, and we don't want to add them to the outer scope.
  1938. branch->guard_body = alloc_node<SuiteNode>();
  1939. if (branch->patterns.size() > 0) {
  1940. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  1941. SuiteNode::Local local(E.value, current_function);
  1942. local.type = SuiteNode::Local::PATTERN_BIND;
  1943. branch->guard_body->add_local(local);
  1944. }
  1945. }
  1946. SuiteNode *parent_block = current_suite;
  1947. branch->guard_body->parent_block = parent_block;
  1948. current_suite = branch->guard_body;
  1949. ExpressionNode *guard = parse_expression(false);
  1950. if (guard == nullptr) {
  1951. push_error(R"(Expected expression for pattern guard after "when".)");
  1952. } else {
  1953. branch->guard_body->statements.append(guard);
  1954. }
  1955. current_suite = parent_block;
  1956. complete_extents(branch->guard_body);
  1957. has_guard = true;
  1958. branch->has_wildcard = false; // If it has a guard, the wildcard might still not match.
  1959. }
  1960. if (!consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":"%s after "match" %s.)", has_guard ? "" : R"( or "when")", has_guard ? "pattern guard" : "patterns"))) {
  1961. complete_extents(branch);
  1962. return nullptr;
  1963. }
  1964. SuiteNode *suite = alloc_node<SuiteNode>();
  1965. if (branch->patterns.size() > 0) {
  1966. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  1967. SuiteNode::Local local(E.value, current_function);
  1968. local.type = SuiteNode::Local::PATTERN_BIND;
  1969. suite->add_local(local);
  1970. }
  1971. }
  1972. branch->block = parse_suite("match pattern block", suite);
  1973. complete_extents(branch);
  1974. return branch;
  1975. }
  1976. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  1977. PatternNode *pattern = alloc_node<PatternNode>();
  1978. reset_extents(pattern, current);
  1979. switch (current.type) {
  1980. case GDScriptTokenizer::Token::VAR: {
  1981. // Bind.
  1982. advance();
  1983. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  1984. complete_extents(pattern);
  1985. return nullptr;
  1986. }
  1987. pattern->pattern_type = PatternNode::PT_BIND;
  1988. pattern->bind = parse_identifier();
  1989. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  1990. if (p_root_pattern != nullptr) {
  1991. if (p_root_pattern->has_bind(pattern->bind->name)) {
  1992. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  1993. complete_extents(pattern);
  1994. return nullptr;
  1995. }
  1996. }
  1997. if (current_suite->has_local(pattern->bind->name)) {
  1998. push_error(vformat(R"(There's already a %s named "%s" in this scope.)", current_suite->get_local(pattern->bind->name).get_name(), pattern->bind->name));
  1999. complete_extents(pattern);
  2000. return nullptr;
  2001. }
  2002. root_pattern->binds[pattern->bind->name] = pattern->bind;
  2003. } break;
  2004. case GDScriptTokenizer::Token::UNDERSCORE:
  2005. // Wildcard.
  2006. advance();
  2007. pattern->pattern_type = PatternNode::PT_WILDCARD;
  2008. break;
  2009. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  2010. // Rest.
  2011. advance();
  2012. pattern->pattern_type = PatternNode::PT_REST;
  2013. break;
  2014. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  2015. // Array.
  2016. push_multiline(true);
  2017. advance();
  2018. pattern->pattern_type = PatternNode::PT_ARRAY;
  2019. do {
  2020. if (is_at_end() || check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2021. break;
  2022. }
  2023. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  2024. if (sub_pattern == nullptr) {
  2025. continue;
  2026. }
  2027. if (pattern->rest_used) {
  2028. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  2029. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  2030. pattern->rest_used = true;
  2031. }
  2032. pattern->array.push_back(sub_pattern);
  2033. } while (match(GDScriptTokenizer::Token::COMMA));
  2034. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  2035. pop_multiline();
  2036. break;
  2037. }
  2038. case GDScriptTokenizer::Token::BRACE_OPEN: {
  2039. // Dictionary.
  2040. push_multiline(true);
  2041. advance();
  2042. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  2043. do {
  2044. if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
  2045. break;
  2046. }
  2047. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  2048. // Rest.
  2049. if (pattern->rest_used) {
  2050. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  2051. } else {
  2052. PatternNode *sub_pattern = alloc_node<PatternNode>();
  2053. complete_extents(sub_pattern);
  2054. sub_pattern->pattern_type = PatternNode::PT_REST;
  2055. pattern->dictionary.push_back({ nullptr, sub_pattern });
  2056. pattern->rest_used = true;
  2057. }
  2058. } else {
  2059. ExpressionNode *key = parse_expression(false);
  2060. if (key == nullptr) {
  2061. push_error(R"(Expected expression as key for dictionary pattern.)");
  2062. }
  2063. if (match(GDScriptTokenizer::Token::COLON)) {
  2064. // Value pattern.
  2065. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  2066. if (sub_pattern == nullptr) {
  2067. continue;
  2068. }
  2069. if (pattern->rest_used) {
  2070. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  2071. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  2072. push_error(R"(The ".." pattern cannot be used as a value.)");
  2073. } else {
  2074. pattern->dictionary.push_back({ key, sub_pattern });
  2075. }
  2076. } else {
  2077. // Key match only.
  2078. pattern->dictionary.push_back({ key, nullptr });
  2079. }
  2080. }
  2081. } while (match(GDScriptTokenizer::Token::COMMA));
  2082. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  2083. pop_multiline();
  2084. break;
  2085. }
  2086. default: {
  2087. // Expression.
  2088. ExpressionNode *expression = parse_expression(false);
  2089. if (expression == nullptr) {
  2090. push_error(R"(Expected expression for match pattern.)");
  2091. complete_extents(pattern);
  2092. return nullptr;
  2093. } else {
  2094. if (expression->type == GDScriptParser::Node::LITERAL) {
  2095. pattern->pattern_type = PatternNode::PT_LITERAL;
  2096. } else {
  2097. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  2098. }
  2099. pattern->expression = expression;
  2100. }
  2101. break;
  2102. }
  2103. }
  2104. complete_extents(pattern);
  2105. return pattern;
  2106. }
  2107. bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
  2108. return binds.has(p_name);
  2109. }
  2110. GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
  2111. return binds[p_name];
  2112. }
  2113. GDScriptParser::WhileNode *GDScriptParser::parse_while() {
  2114. WhileNode *n_while = alloc_node<WhileNode>();
  2115. n_while->condition = parse_expression(false);
  2116. if (n_while->condition == nullptr) {
  2117. push_error(R"(Expected conditional expression after "while".)");
  2118. }
  2119. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
  2120. // Save break/continue state.
  2121. bool could_break = can_break;
  2122. bool could_continue = can_continue;
  2123. // Allow break/continue.
  2124. can_break = true;
  2125. can_continue = true;
  2126. SuiteNode *suite = alloc_node<SuiteNode>();
  2127. suite->is_in_loop = true;
  2128. n_while->loop = parse_suite(R"("while" block)", suite);
  2129. complete_extents(n_while);
  2130. // Reset break/continue state.
  2131. can_break = could_break;
  2132. can_continue = could_continue;
  2133. return n_while;
  2134. }
  2135. GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
  2136. // Switch multiline mode on for grouping tokens.
  2137. // Do this early to avoid the tokenizer generating whitespace tokens.
  2138. switch (current.type) {
  2139. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  2140. case GDScriptTokenizer::Token::BRACE_OPEN:
  2141. case GDScriptTokenizer::Token::BRACKET_OPEN:
  2142. push_multiline(true);
  2143. break;
  2144. default:
  2145. break; // Nothing to do.
  2146. }
  2147. // Completion can appear whenever an expression is expected.
  2148. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  2149. GDScriptTokenizer::Token token = current;
  2150. GDScriptTokenizer::Token::Type token_type = token.type;
  2151. if (token.is_identifier()) {
  2152. // Allow keywords that can be treated as identifiers.
  2153. token_type = GDScriptTokenizer::Token::IDENTIFIER;
  2154. }
  2155. ParseFunction prefix_rule = get_rule(token_type)->prefix;
  2156. if (prefix_rule == nullptr) {
  2157. // Expected expression. Let the caller give the proper error message.
  2158. return nullptr;
  2159. }
  2160. advance(); // Only consume the token if there's a valid rule.
  2161. ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
  2162. while (p_precedence <= get_rule(current.type)->precedence) {
  2163. if (previous_operand == nullptr || (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) || lambda_ended) {
  2164. return previous_operand;
  2165. }
  2166. // Also switch multiline mode on here for infix operators.
  2167. switch (current.type) {
  2168. // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
  2169. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  2170. case GDScriptTokenizer::Token::BRACKET_OPEN:
  2171. push_multiline(true);
  2172. break;
  2173. default:
  2174. break; // Nothing to do.
  2175. }
  2176. token = advance();
  2177. ParseFunction infix_rule = get_rule(token.type)->infix;
  2178. previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
  2179. }
  2180. return previous_operand;
  2181. }
  2182. GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
  2183. return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
  2184. }
  2185. GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
  2186. IdentifierNode *identifier = static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
  2187. #ifdef DEBUG_ENABLED
  2188. // Check for spoofing here (if available in TextServer) since this isn't called inside expressions. This is only relevant for declarations.
  2189. if (identifier && TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier->name)) {
  2190. push_warning(identifier, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier->name.operator String());
  2191. }
  2192. #endif
  2193. return identifier;
  2194. }
  2195. GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2196. if (!previous.is_identifier()) {
  2197. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing identifier node without identifier token.");
  2198. }
  2199. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  2200. complete_extents(identifier);
  2201. identifier->name = previous.get_identifier();
  2202. if (identifier->name.operator String().is_empty()) {
  2203. print_line("Empty identifier found.");
  2204. }
  2205. identifier->suite = current_suite;
  2206. if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
  2207. const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
  2208. identifier->source_function = declaration.source_function;
  2209. switch (declaration.type) {
  2210. case SuiteNode::Local::CONSTANT:
  2211. identifier->source = IdentifierNode::LOCAL_CONSTANT;
  2212. identifier->constant_source = declaration.constant;
  2213. declaration.constant->usages++;
  2214. break;
  2215. case SuiteNode::Local::VARIABLE:
  2216. identifier->source = IdentifierNode::LOCAL_VARIABLE;
  2217. identifier->variable_source = declaration.variable;
  2218. declaration.variable->usages++;
  2219. break;
  2220. case SuiteNode::Local::PARAMETER:
  2221. identifier->source = IdentifierNode::FUNCTION_PARAMETER;
  2222. identifier->parameter_source = declaration.parameter;
  2223. declaration.parameter->usages++;
  2224. break;
  2225. case SuiteNode::Local::FOR_VARIABLE:
  2226. identifier->source = IdentifierNode::LOCAL_ITERATOR;
  2227. identifier->bind_source = declaration.bind;
  2228. declaration.bind->usages++;
  2229. break;
  2230. case SuiteNode::Local::PATTERN_BIND:
  2231. identifier->source = IdentifierNode::LOCAL_BIND;
  2232. identifier->bind_source = declaration.bind;
  2233. declaration.bind->usages++;
  2234. break;
  2235. case SuiteNode::Local::UNDEFINED:
  2236. ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
  2237. }
  2238. }
  2239. return identifier;
  2240. }
  2241. GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
  2242. return static_cast<LiteralNode *>(parse_literal(nullptr, false));
  2243. }
  2244. GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2245. if (previous.type != GDScriptTokenizer::Token::LITERAL) {
  2246. push_error("Parser bug: parsing literal node without literal token.");
  2247. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  2248. }
  2249. LiteralNode *literal = alloc_node<LiteralNode>();
  2250. literal->value = previous.literal;
  2251. reset_extents(literal, p_previous_operand);
  2252. update_extents(literal);
  2253. make_completion_context(COMPLETION_NONE, literal, -1);
  2254. complete_extents(literal);
  2255. return literal;
  2256. }
  2257. GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2258. if (current_function && current_function->is_static) {
  2259. push_error(R"(Cannot use "self" inside a static function.)");
  2260. }
  2261. SelfNode *self = alloc_node<SelfNode>();
  2262. complete_extents(self);
  2263. self->current_class = current_class;
  2264. return self;
  2265. }
  2266. GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2267. GDScriptTokenizer::Token::Type op_type = previous.type;
  2268. LiteralNode *constant = alloc_node<LiteralNode>();
  2269. complete_extents(constant);
  2270. switch (op_type) {
  2271. case GDScriptTokenizer::Token::CONST_PI:
  2272. constant->value = Math_PI;
  2273. break;
  2274. case GDScriptTokenizer::Token::CONST_TAU:
  2275. constant->value = Math_TAU;
  2276. break;
  2277. case GDScriptTokenizer::Token::CONST_INF:
  2278. constant->value = INFINITY;
  2279. break;
  2280. case GDScriptTokenizer::Token::CONST_NAN:
  2281. constant->value = NAN;
  2282. break;
  2283. default:
  2284. return nullptr; // Unreachable.
  2285. }
  2286. return constant;
  2287. }
  2288. GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2289. GDScriptTokenizer::Token::Type op_type = previous.type;
  2290. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2291. switch (op_type) {
  2292. case GDScriptTokenizer::Token::MINUS:
  2293. operation->operation = UnaryOpNode::OP_NEGATIVE;
  2294. operation->variant_op = Variant::OP_NEGATE;
  2295. operation->operand = parse_precedence(PREC_SIGN, false);
  2296. if (operation->operand == nullptr) {
  2297. push_error(R"(Expected expression after "-" operator.)");
  2298. }
  2299. break;
  2300. case GDScriptTokenizer::Token::PLUS:
  2301. operation->operation = UnaryOpNode::OP_POSITIVE;
  2302. operation->variant_op = Variant::OP_POSITIVE;
  2303. operation->operand = parse_precedence(PREC_SIGN, false);
  2304. if (operation->operand == nullptr) {
  2305. push_error(R"(Expected expression after "+" operator.)");
  2306. }
  2307. break;
  2308. case GDScriptTokenizer::Token::TILDE:
  2309. operation->operation = UnaryOpNode::OP_COMPLEMENT;
  2310. operation->variant_op = Variant::OP_BIT_NEGATE;
  2311. operation->operand = parse_precedence(PREC_BIT_NOT, false);
  2312. if (operation->operand == nullptr) {
  2313. push_error(R"(Expected expression after "~" operator.)");
  2314. }
  2315. break;
  2316. case GDScriptTokenizer::Token::NOT:
  2317. case GDScriptTokenizer::Token::BANG:
  2318. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2319. operation->variant_op = Variant::OP_NOT;
  2320. operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
  2321. if (operation->operand == nullptr) {
  2322. push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
  2323. }
  2324. break;
  2325. default:
  2326. complete_extents(operation);
  2327. return nullptr; // Unreachable.
  2328. }
  2329. complete_extents(operation);
  2330. return operation;
  2331. }
  2332. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_not_in_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2333. // check that NOT is followed by IN by consuming it before calling parse_binary_operator which will only receive a plain IN
  2334. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2335. reset_extents(operation, p_previous_operand);
  2336. update_extents(operation);
  2337. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "not" in content-test operator.)");
  2338. ExpressionNode *in_operation = parse_binary_operator(p_previous_operand, p_can_assign);
  2339. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2340. operation->variant_op = Variant::OP_NOT;
  2341. operation->operand = in_operation;
  2342. complete_extents(operation);
  2343. return operation;
  2344. }
  2345. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2346. GDScriptTokenizer::Token op = previous;
  2347. BinaryOpNode *operation = alloc_node<BinaryOpNode>();
  2348. reset_extents(operation, p_previous_operand);
  2349. update_extents(operation);
  2350. Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
  2351. operation->left_operand = p_previous_operand;
  2352. operation->right_operand = parse_precedence(precedence, false);
  2353. complete_extents(operation);
  2354. if (operation->right_operand == nullptr) {
  2355. push_error(vformat(R"(Expected expression after "%s" operator.)", op.get_name()));
  2356. }
  2357. // TODO: Also for unary, ternary, and assignment.
  2358. switch (op.type) {
  2359. case GDScriptTokenizer::Token::PLUS:
  2360. operation->operation = BinaryOpNode::OP_ADDITION;
  2361. operation->variant_op = Variant::OP_ADD;
  2362. break;
  2363. case GDScriptTokenizer::Token::MINUS:
  2364. operation->operation = BinaryOpNode::OP_SUBTRACTION;
  2365. operation->variant_op = Variant::OP_SUBTRACT;
  2366. break;
  2367. case GDScriptTokenizer::Token::STAR:
  2368. operation->operation = BinaryOpNode::OP_MULTIPLICATION;
  2369. operation->variant_op = Variant::OP_MULTIPLY;
  2370. break;
  2371. case GDScriptTokenizer::Token::SLASH:
  2372. operation->operation = BinaryOpNode::OP_DIVISION;
  2373. operation->variant_op = Variant::OP_DIVIDE;
  2374. break;
  2375. case GDScriptTokenizer::Token::PERCENT:
  2376. operation->operation = BinaryOpNode::OP_MODULO;
  2377. operation->variant_op = Variant::OP_MODULE;
  2378. break;
  2379. case GDScriptTokenizer::Token::STAR_STAR:
  2380. operation->operation = BinaryOpNode::OP_POWER;
  2381. operation->variant_op = Variant::OP_POWER;
  2382. break;
  2383. case GDScriptTokenizer::Token::LESS_LESS:
  2384. operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
  2385. operation->variant_op = Variant::OP_SHIFT_LEFT;
  2386. break;
  2387. case GDScriptTokenizer::Token::GREATER_GREATER:
  2388. operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
  2389. operation->variant_op = Variant::OP_SHIFT_RIGHT;
  2390. break;
  2391. case GDScriptTokenizer::Token::AMPERSAND:
  2392. operation->operation = BinaryOpNode::OP_BIT_AND;
  2393. operation->variant_op = Variant::OP_BIT_AND;
  2394. break;
  2395. case GDScriptTokenizer::Token::PIPE:
  2396. operation->operation = BinaryOpNode::OP_BIT_OR;
  2397. operation->variant_op = Variant::OP_BIT_OR;
  2398. break;
  2399. case GDScriptTokenizer::Token::CARET:
  2400. operation->operation = BinaryOpNode::OP_BIT_XOR;
  2401. operation->variant_op = Variant::OP_BIT_XOR;
  2402. break;
  2403. case GDScriptTokenizer::Token::AND:
  2404. case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
  2405. operation->operation = BinaryOpNode::OP_LOGIC_AND;
  2406. operation->variant_op = Variant::OP_AND;
  2407. break;
  2408. case GDScriptTokenizer::Token::OR:
  2409. case GDScriptTokenizer::Token::PIPE_PIPE:
  2410. operation->operation = BinaryOpNode::OP_LOGIC_OR;
  2411. operation->variant_op = Variant::OP_OR;
  2412. break;
  2413. case GDScriptTokenizer::Token::IN:
  2414. operation->operation = BinaryOpNode::OP_CONTENT_TEST;
  2415. operation->variant_op = Variant::OP_IN;
  2416. break;
  2417. case GDScriptTokenizer::Token::EQUAL_EQUAL:
  2418. operation->operation = BinaryOpNode::OP_COMP_EQUAL;
  2419. operation->variant_op = Variant::OP_EQUAL;
  2420. break;
  2421. case GDScriptTokenizer::Token::BANG_EQUAL:
  2422. operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
  2423. operation->variant_op = Variant::OP_NOT_EQUAL;
  2424. break;
  2425. case GDScriptTokenizer::Token::LESS:
  2426. operation->operation = BinaryOpNode::OP_COMP_LESS;
  2427. operation->variant_op = Variant::OP_LESS;
  2428. break;
  2429. case GDScriptTokenizer::Token::LESS_EQUAL:
  2430. operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
  2431. operation->variant_op = Variant::OP_LESS_EQUAL;
  2432. break;
  2433. case GDScriptTokenizer::Token::GREATER:
  2434. operation->operation = BinaryOpNode::OP_COMP_GREATER;
  2435. operation->variant_op = Variant::OP_GREATER;
  2436. break;
  2437. case GDScriptTokenizer::Token::GREATER_EQUAL:
  2438. operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
  2439. operation->variant_op = Variant::OP_GREATER_EQUAL;
  2440. break;
  2441. default:
  2442. return nullptr; // Unreachable.
  2443. }
  2444. return operation;
  2445. }
  2446. GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2447. // Only one ternary operation exists, so no abstraction here.
  2448. TernaryOpNode *operation = alloc_node<TernaryOpNode>();
  2449. reset_extents(operation, p_previous_operand);
  2450. update_extents(operation);
  2451. operation->true_expr = p_previous_operand;
  2452. operation->condition = parse_precedence(PREC_TERNARY, false);
  2453. if (operation->condition == nullptr) {
  2454. push_error(R"(Expected expression as ternary condition after "if".)");
  2455. }
  2456. consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
  2457. operation->false_expr = parse_precedence(PREC_TERNARY, false);
  2458. if (operation->false_expr == nullptr) {
  2459. push_error(R"(Expected expression after "else".)");
  2460. }
  2461. complete_extents(operation);
  2462. return operation;
  2463. }
  2464. GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2465. if (!p_can_assign) {
  2466. push_error("Assignment is not allowed inside an expression.");
  2467. return parse_expression(false); // Return the following expression.
  2468. }
  2469. if (p_previous_operand == nullptr) {
  2470. return parse_expression(false); // Return the following expression.
  2471. }
  2472. switch (p_previous_operand->type) {
  2473. case Node::IDENTIFIER: {
  2474. #ifdef DEBUG_ENABLED
  2475. // Get source to store assignment count.
  2476. // Also remove one usage since assignment isn't usage.
  2477. IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
  2478. switch (id->source) {
  2479. case IdentifierNode::LOCAL_VARIABLE:
  2480. id->variable_source->usages--;
  2481. break;
  2482. case IdentifierNode::LOCAL_CONSTANT:
  2483. id->constant_source->usages--;
  2484. break;
  2485. case IdentifierNode::FUNCTION_PARAMETER:
  2486. id->parameter_source->usages--;
  2487. break;
  2488. case IdentifierNode::LOCAL_ITERATOR:
  2489. case IdentifierNode::LOCAL_BIND:
  2490. id->bind_source->usages--;
  2491. break;
  2492. default:
  2493. break;
  2494. }
  2495. #endif
  2496. } break;
  2497. case Node::SUBSCRIPT:
  2498. // Okay.
  2499. break;
  2500. default:
  2501. push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
  2502. return parse_expression(false); // Return the following expression.
  2503. }
  2504. AssignmentNode *assignment = alloc_node<AssignmentNode>();
  2505. reset_extents(assignment, p_previous_operand);
  2506. update_extents(assignment);
  2507. make_completion_context(COMPLETION_ASSIGN, assignment);
  2508. switch (previous.type) {
  2509. case GDScriptTokenizer::Token::EQUAL:
  2510. assignment->operation = AssignmentNode::OP_NONE;
  2511. assignment->variant_op = Variant::OP_MAX;
  2512. break;
  2513. case GDScriptTokenizer::Token::PLUS_EQUAL:
  2514. assignment->operation = AssignmentNode::OP_ADDITION;
  2515. assignment->variant_op = Variant::OP_ADD;
  2516. break;
  2517. case GDScriptTokenizer::Token::MINUS_EQUAL:
  2518. assignment->operation = AssignmentNode::OP_SUBTRACTION;
  2519. assignment->variant_op = Variant::OP_SUBTRACT;
  2520. break;
  2521. case GDScriptTokenizer::Token::STAR_EQUAL:
  2522. assignment->operation = AssignmentNode::OP_MULTIPLICATION;
  2523. assignment->variant_op = Variant::OP_MULTIPLY;
  2524. break;
  2525. case GDScriptTokenizer::Token::STAR_STAR_EQUAL:
  2526. assignment->operation = AssignmentNode::OP_POWER;
  2527. assignment->variant_op = Variant::OP_POWER;
  2528. break;
  2529. case GDScriptTokenizer::Token::SLASH_EQUAL:
  2530. assignment->operation = AssignmentNode::OP_DIVISION;
  2531. assignment->variant_op = Variant::OP_DIVIDE;
  2532. break;
  2533. case GDScriptTokenizer::Token::PERCENT_EQUAL:
  2534. assignment->operation = AssignmentNode::OP_MODULO;
  2535. assignment->variant_op = Variant::OP_MODULE;
  2536. break;
  2537. case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
  2538. assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
  2539. assignment->variant_op = Variant::OP_SHIFT_LEFT;
  2540. break;
  2541. case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
  2542. assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
  2543. assignment->variant_op = Variant::OP_SHIFT_RIGHT;
  2544. break;
  2545. case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
  2546. assignment->operation = AssignmentNode::OP_BIT_AND;
  2547. assignment->variant_op = Variant::OP_BIT_AND;
  2548. break;
  2549. case GDScriptTokenizer::Token::PIPE_EQUAL:
  2550. assignment->operation = AssignmentNode::OP_BIT_OR;
  2551. assignment->variant_op = Variant::OP_BIT_OR;
  2552. break;
  2553. case GDScriptTokenizer::Token::CARET_EQUAL:
  2554. assignment->operation = AssignmentNode::OP_BIT_XOR;
  2555. assignment->variant_op = Variant::OP_BIT_XOR;
  2556. break;
  2557. default:
  2558. break; // Unreachable.
  2559. }
  2560. assignment->assignee = p_previous_operand;
  2561. assignment->assigned_value = parse_expression(false);
  2562. if (assignment->assigned_value == nullptr) {
  2563. push_error(R"(Expected an expression after "=".)");
  2564. }
  2565. complete_extents(assignment);
  2566. return assignment;
  2567. }
  2568. GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2569. AwaitNode *await = alloc_node<AwaitNode>();
  2570. ExpressionNode *element = parse_precedence(PREC_AWAIT, false);
  2571. if (element == nullptr) {
  2572. push_error(R"(Expected signal or coroutine after "await".)");
  2573. }
  2574. await->to_await = element;
  2575. complete_extents(await);
  2576. if (current_function) { // Might be null in a getter or setter.
  2577. current_function->is_coroutine = true;
  2578. }
  2579. return await;
  2580. }
  2581. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2582. ArrayNode *array = alloc_node<ArrayNode>();
  2583. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2584. do {
  2585. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2586. // Allow for trailing comma.
  2587. break;
  2588. }
  2589. ExpressionNode *element = parse_expression(false);
  2590. if (element == nullptr) {
  2591. push_error(R"(Expected expression as array element.)");
  2592. } else {
  2593. array->elements.push_back(element);
  2594. }
  2595. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2596. }
  2597. pop_multiline();
  2598. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  2599. complete_extents(array);
  2600. return array;
  2601. }
  2602. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2603. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2604. bool decided_style = false;
  2605. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2606. do {
  2607. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2608. // Allow for trailing comma.
  2609. break;
  2610. }
  2611. // Key.
  2612. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2613. if (key == nullptr) {
  2614. push_error(R"(Expected expression as dictionary key.)");
  2615. }
  2616. if (!decided_style) {
  2617. switch (current.type) {
  2618. case GDScriptTokenizer::Token::COLON:
  2619. dictionary->style = DictionaryNode::PYTHON_DICT;
  2620. break;
  2621. case GDScriptTokenizer::Token::EQUAL:
  2622. dictionary->style = DictionaryNode::LUA_TABLE;
  2623. break;
  2624. default:
  2625. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2626. break;
  2627. }
  2628. decided_style = true;
  2629. }
  2630. switch (dictionary->style) {
  2631. case DictionaryNode::LUA_TABLE:
  2632. if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
  2633. push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
  2634. advance();
  2635. break;
  2636. }
  2637. if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
  2638. push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
  2639. advance();
  2640. break;
  2641. }
  2642. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2643. if (match(GDScriptTokenizer::Token::COLON)) {
  2644. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2645. advance(); // Consume wrong separator anyway.
  2646. } else {
  2647. push_error(R"(Expected "=" after dictionary key.)");
  2648. }
  2649. }
  2650. if (key != nullptr) {
  2651. key->is_constant = true;
  2652. if (key->type == Node::IDENTIFIER) {
  2653. key->reduced_value = static_cast<IdentifierNode *>(key)->name;
  2654. } else if (key->type == Node::LITERAL) {
  2655. key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
  2656. }
  2657. }
  2658. break;
  2659. case DictionaryNode::PYTHON_DICT:
  2660. if (!match(GDScriptTokenizer::Token::COLON)) {
  2661. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2662. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2663. advance(); // Consume wrong separator anyway.
  2664. } else {
  2665. push_error(R"(Expected ":" after dictionary key.)");
  2666. }
  2667. }
  2668. break;
  2669. }
  2670. // Value.
  2671. ExpressionNode *value = parse_expression(false);
  2672. if (value == nullptr) {
  2673. push_error(R"(Expected expression as dictionary value.)");
  2674. }
  2675. if (key != nullptr && value != nullptr) {
  2676. dictionary->elements.push_back({ key, value });
  2677. }
  2678. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2679. }
  2680. pop_multiline();
  2681. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2682. complete_extents(dictionary);
  2683. return dictionary;
  2684. }
  2685. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2686. ExpressionNode *grouped = parse_expression(false);
  2687. pop_multiline();
  2688. if (grouped == nullptr) {
  2689. push_error(R"(Expected grouping expression.)");
  2690. } else {
  2691. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2692. }
  2693. return grouped;
  2694. }
  2695. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2696. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2697. reset_extents(attribute, p_previous_operand);
  2698. update_extents(attribute);
  2699. if (for_completion) {
  2700. bool is_builtin = false;
  2701. if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
  2702. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2703. Variant::Type builtin_type = get_builtin_type(id->name);
  2704. if (builtin_type < Variant::VARIANT_MAX) {
  2705. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT_OR_STATIC_METHOD, builtin_type);
  2706. is_builtin = true;
  2707. }
  2708. }
  2709. if (!is_builtin) {
  2710. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1);
  2711. }
  2712. }
  2713. attribute->base = p_previous_operand;
  2714. if (current.is_node_name()) {
  2715. current.type = GDScriptTokenizer::Token::IDENTIFIER;
  2716. }
  2717. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2718. complete_extents(attribute);
  2719. return attribute;
  2720. }
  2721. attribute->is_attribute = true;
  2722. attribute->attribute = parse_identifier();
  2723. complete_extents(attribute);
  2724. return attribute;
  2725. }
  2726. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2727. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2728. reset_extents(subscript, p_previous_operand);
  2729. update_extents(subscript);
  2730. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2731. subscript->base = p_previous_operand;
  2732. subscript->index = parse_expression(false);
  2733. #ifdef TOOLS_ENABLED
  2734. if (subscript->index != nullptr && subscript->index->type == Node::LITERAL) {
  2735. override_completion_context(subscript->index, COMPLETION_SUBSCRIPT, subscript);
  2736. }
  2737. #endif
  2738. if (subscript->index == nullptr) {
  2739. push_error(R"(Expected expression after "[".)");
  2740. }
  2741. pop_multiline();
  2742. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2743. complete_extents(subscript);
  2744. return subscript;
  2745. }
  2746. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2747. CastNode *cast = alloc_node<CastNode>();
  2748. reset_extents(cast, p_previous_operand);
  2749. update_extents(cast);
  2750. cast->operand = p_previous_operand;
  2751. cast->cast_type = parse_type();
  2752. complete_extents(cast);
  2753. if (cast->cast_type == nullptr) {
  2754. push_error(R"(Expected type specifier after "as".)");
  2755. return p_previous_operand;
  2756. }
  2757. return cast;
  2758. }
  2759. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2760. CallNode *call = alloc_node<CallNode>();
  2761. reset_extents(call, p_previous_operand);
  2762. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  2763. // Super call.
  2764. call->is_super = true;
  2765. push_multiline(true);
  2766. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  2767. // Implicit call to the parent method of the same name.
  2768. if (current_function == nullptr) {
  2769. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  2770. pop_multiline();
  2771. complete_extents(call);
  2772. return nullptr;
  2773. }
  2774. if (current_function->identifier) {
  2775. call->function_name = current_function->identifier->name;
  2776. } else {
  2777. call->function_name = SNAME("<anonymous>");
  2778. }
  2779. } else {
  2780. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  2781. make_completion_context(COMPLETION_SUPER_METHOD, call, true);
  2782. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  2783. pop_multiline();
  2784. complete_extents(call);
  2785. return nullptr;
  2786. }
  2787. IdentifierNode *identifier = parse_identifier();
  2788. call->callee = identifier;
  2789. call->function_name = identifier->name;
  2790. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)");
  2791. }
  2792. } else {
  2793. call->callee = p_previous_operand;
  2794. if (call->callee == nullptr) {
  2795. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2796. } else if (call->callee->type == Node::IDENTIFIER) {
  2797. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  2798. make_completion_context(COMPLETION_METHOD, call->callee);
  2799. } else if (call->callee->type == Node::SUBSCRIPT) {
  2800. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  2801. if (attribute->is_attribute) {
  2802. if (attribute->attribute) {
  2803. call->function_name = attribute->attribute->name;
  2804. }
  2805. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  2806. } else {
  2807. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  2808. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2809. }
  2810. } else {
  2811. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2812. }
  2813. }
  2814. // Arguments.
  2815. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  2816. if (call->function_name == SNAME("load")) {
  2817. ct = COMPLETION_RESOURCE_PATH;
  2818. }
  2819. push_completion_call(call);
  2820. int argument_index = 0;
  2821. do {
  2822. make_completion_context(ct, call, argument_index);
  2823. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  2824. // Allow for trailing comma.
  2825. break;
  2826. }
  2827. ExpressionNode *argument = parse_expression(false);
  2828. if (argument == nullptr) {
  2829. push_error(R"(Expected expression as the function argument.)");
  2830. } else {
  2831. call->arguments.push_back(argument);
  2832. if (argument->type == Node::LITERAL) {
  2833. override_completion_context(argument, ct, call, argument_index);
  2834. }
  2835. }
  2836. ct = COMPLETION_CALL_ARGUMENTS;
  2837. argument_index++;
  2838. } while (match(GDScriptTokenizer::Token::COMMA));
  2839. pop_completion_call();
  2840. pop_multiline();
  2841. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  2842. complete_extents(call);
  2843. return call;
  2844. }
  2845. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2846. // We want code completion after a DOLLAR even if the current code is invalid.
  2847. make_completion_context(COMPLETION_GET_NODE, nullptr, -1);
  2848. if (!current.is_node_name() && !check(GDScriptTokenizer::Token::LITERAL) && !check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  2849. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  2850. return nullptr;
  2851. }
  2852. if (check(GDScriptTokenizer::Token::LITERAL)) {
  2853. if (current.literal.get_type() != Variant::STRING) {
  2854. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  2855. return nullptr;
  2856. }
  2857. }
  2858. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2859. // Store the last item in the path so the parser knows what to expect.
  2860. // Allow allows more specific error messages.
  2861. enum PathState {
  2862. PATH_STATE_START,
  2863. PATH_STATE_SLASH,
  2864. PATH_STATE_PERCENT,
  2865. PATH_STATE_NODE_NAME,
  2866. } path_state = PATH_STATE_START;
  2867. if (previous.type == GDScriptTokenizer::Token::DOLLAR) {
  2868. // Detect initial slash, which will be handled in the loop if it matches.
  2869. match(GDScriptTokenizer::Token::SLASH);
  2870. } else {
  2871. get_node->use_dollar = false;
  2872. }
  2873. int context_argument = 0;
  2874. do {
  2875. if (previous.type == GDScriptTokenizer::Token::PERCENT) {
  2876. if (path_state != PATH_STATE_START && path_state != PATH_STATE_SLASH) {
  2877. push_error(R"("%" is only valid in the beginning of a node name (either after "$" or after "/"))");
  2878. complete_extents(get_node);
  2879. return nullptr;
  2880. }
  2881. get_node->full_path += "%";
  2882. path_state = PATH_STATE_PERCENT;
  2883. } else if (previous.type == GDScriptTokenizer::Token::SLASH) {
  2884. if (path_state != PATH_STATE_START && path_state != PATH_STATE_NODE_NAME) {
  2885. push_error(R"("/" is only valid at the beginning of the path or after a node name.)");
  2886. complete_extents(get_node);
  2887. return nullptr;
  2888. }
  2889. get_node->full_path += "/";
  2890. path_state = PATH_STATE_SLASH;
  2891. }
  2892. make_completion_context(COMPLETION_GET_NODE, get_node, context_argument++);
  2893. if (match(GDScriptTokenizer::Token::LITERAL)) {
  2894. if (previous.literal.get_type() != Variant::STRING) {
  2895. String previous_token;
  2896. switch (path_state) {
  2897. case PATH_STATE_START:
  2898. previous_token = "$";
  2899. break;
  2900. case PATH_STATE_PERCENT:
  2901. previous_token = "%";
  2902. break;
  2903. case PATH_STATE_SLASH:
  2904. previous_token = "/";
  2905. break;
  2906. default:
  2907. break;
  2908. }
  2909. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous_token));
  2910. complete_extents(get_node);
  2911. return nullptr;
  2912. }
  2913. get_node->full_path += previous.literal.operator String();
  2914. path_state = PATH_STATE_NODE_NAME;
  2915. } else if (current.is_node_name()) {
  2916. advance();
  2917. String identifier = previous.get_identifier();
  2918. #ifdef DEBUG_ENABLED
  2919. // Check spoofing.
  2920. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier)) {
  2921. push_warning(get_node, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier);
  2922. }
  2923. #endif
  2924. get_node->full_path += identifier;
  2925. path_state = PATH_STATE_NODE_NAME;
  2926. } else if (!check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  2927. push_error(vformat(R"(Unexpected "%s" in node path.)", current.get_name()));
  2928. complete_extents(get_node);
  2929. return nullptr;
  2930. }
  2931. } while (match(GDScriptTokenizer::Token::SLASH) || match(GDScriptTokenizer::Token::PERCENT));
  2932. complete_extents(get_node);
  2933. return get_node;
  2934. }
  2935. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2936. PreloadNode *preload = alloc_node<PreloadNode>();
  2937. preload->resolved_path = "<missing path>";
  2938. push_multiline(true);
  2939. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  2940. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  2941. push_completion_call(preload);
  2942. preload->path = parse_expression(false);
  2943. if (preload->path == nullptr) {
  2944. push_error(R"(Expected resource path after "(".)");
  2945. }
  2946. pop_completion_call();
  2947. pop_multiline();
  2948. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  2949. complete_extents(preload);
  2950. return preload;
  2951. }
  2952. GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2953. LambdaNode *lambda = alloc_node<LambdaNode>();
  2954. lambda->parent_function = current_function;
  2955. lambda->parent_lambda = current_lambda;
  2956. FunctionNode *function = alloc_node<FunctionNode>();
  2957. function->source_lambda = lambda;
  2958. function->is_static = current_function != nullptr ? current_function->is_static : false;
  2959. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2960. function->identifier = parse_identifier();
  2961. }
  2962. bool multiline_context = multiline_stack.back()->get();
  2963. // Reset the multiline stack since we don't want the multiline mode one in the lambda body.
  2964. push_multiline(false);
  2965. if (multiline_context) {
  2966. tokenizer->push_expression_indented_block();
  2967. }
  2968. push_multiline(true); // For the parameters.
  2969. if (function->identifier) {
  2970. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
  2971. } else {
  2972. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
  2973. }
  2974. FunctionNode *previous_function = current_function;
  2975. current_function = function;
  2976. LambdaNode *previous_lambda = current_lambda;
  2977. current_lambda = lambda;
  2978. SuiteNode *body = alloc_node<SuiteNode>();
  2979. body->parent_function = current_function;
  2980. body->parent_block = current_suite;
  2981. SuiteNode *previous_suite = current_suite;
  2982. current_suite = body;
  2983. parse_function_signature(function, body, "lambda");
  2984. current_suite = previous_suite;
  2985. bool previous_in_lambda = in_lambda;
  2986. in_lambda = true;
  2987. // Save break/continue state.
  2988. bool could_break = can_break;
  2989. bool could_continue = can_continue;
  2990. // Disallow break/continue.
  2991. can_break = false;
  2992. can_continue = false;
  2993. function->body = parse_suite("lambda declaration", body, true);
  2994. complete_extents(function);
  2995. complete_extents(lambda);
  2996. pop_multiline();
  2997. if (multiline_context) {
  2998. // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
  2999. while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
  3000. current = tokenizer->scan(); // Not advance() since we don't want to change the previous token.
  3001. }
  3002. tokenizer->pop_expression_indented_block();
  3003. }
  3004. current_function = previous_function;
  3005. current_lambda = previous_lambda;
  3006. in_lambda = previous_in_lambda;
  3007. lambda->function = function;
  3008. // Reset break/continue state.
  3009. can_break = could_break;
  3010. can_continue = could_continue;
  3011. return lambda;
  3012. }
  3013. GDScriptParser::ExpressionNode *GDScriptParser::parse_type_test(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3014. // x is not int
  3015. // ^ ^^^ ExpressionNode, TypeNode
  3016. // ^^^^^^^^^^^^ TypeTestNode
  3017. // ^^^^^^^^^^^^ UnaryOpNode
  3018. UnaryOpNode *not_node = nullptr;
  3019. if (match(GDScriptTokenizer::Token::NOT)) {
  3020. not_node = alloc_node<UnaryOpNode>();
  3021. not_node->operation = UnaryOpNode::OP_LOGIC_NOT;
  3022. not_node->variant_op = Variant::OP_NOT;
  3023. reset_extents(not_node, p_previous_operand);
  3024. update_extents(not_node);
  3025. }
  3026. TypeTestNode *type_test = alloc_node<TypeTestNode>();
  3027. reset_extents(type_test, p_previous_operand);
  3028. update_extents(type_test);
  3029. type_test->operand = p_previous_operand;
  3030. type_test->test_type = parse_type();
  3031. complete_extents(type_test);
  3032. if (not_node != nullptr) {
  3033. not_node->operand = type_test;
  3034. complete_extents(not_node);
  3035. }
  3036. if (type_test->test_type == nullptr) {
  3037. if (not_node == nullptr) {
  3038. push_error(R"(Expected type specifier after "is".)");
  3039. } else {
  3040. push_error(R"(Expected type specifier after "is not".)");
  3041. }
  3042. }
  3043. if (not_node != nullptr) {
  3044. return not_node;
  3045. }
  3046. return type_test;
  3047. }
  3048. GDScriptParser::ExpressionNode *GDScriptParser::parse_yield(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3049. push_error(R"("yield" was removed in Godot 4. Use "await" instead.)");
  3050. return nullptr;
  3051. }
  3052. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  3053. // Just for better error messages.
  3054. GDScriptTokenizer::Token::Type invalid = previous.type;
  3055. switch (invalid) {
  3056. case GDScriptTokenizer::Token::QUESTION_MARK:
  3057. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  3058. break;
  3059. default:
  3060. return nullptr; // Unreachable.
  3061. }
  3062. // Return the previous expression.
  3063. return p_previous_operand;
  3064. }
  3065. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  3066. TypeNode *type = alloc_node<TypeNode>();
  3067. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  3068. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  3069. if (match(GDScriptTokenizer::Token::VOID)) {
  3070. if (p_allow_void) {
  3071. complete_extents(type);
  3072. TypeNode *void_type = type;
  3073. return void_type;
  3074. } else {
  3075. push_error(R"("void" is only allowed for a function return type.)");
  3076. }
  3077. }
  3078. // Leave error message to the caller who knows the context.
  3079. complete_extents(type);
  3080. return nullptr;
  3081. }
  3082. IdentifierNode *type_element = parse_identifier();
  3083. type->type_chain.push_back(type_element);
  3084. if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
  3085. // Typed collection (like Array[int]).
  3086. bool first_pass = true;
  3087. do {
  3088. TypeNode *container_type = parse_type(false); // Don't allow void for element type.
  3089. if (container_type == nullptr) {
  3090. push_error(vformat(R"(Expected type for collection after "%s".)", first_pass ? "[" : ","));
  3091. complete_extents(type);
  3092. type = nullptr;
  3093. break;
  3094. } else if (container_type->container_types.size() > 0) {
  3095. push_error("Nested typed collections are not supported.");
  3096. } else {
  3097. type->container_types.append(container_type);
  3098. }
  3099. first_pass = false;
  3100. } while (match(GDScriptTokenizer::Token::COMMA));
  3101. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
  3102. if (type != nullptr) {
  3103. complete_extents(type);
  3104. }
  3105. return type;
  3106. }
  3107. int chain_index = 1;
  3108. while (match(GDScriptTokenizer::Token::PERIOD)) {
  3109. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  3110. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  3111. type_element = parse_identifier();
  3112. type->type_chain.push_back(type_element);
  3113. }
  3114. }
  3115. complete_extents(type);
  3116. return type;
  3117. }
  3118. #ifdef TOOLS_ENABLED
  3119. enum DocLineState {
  3120. DOC_LINE_NORMAL,
  3121. DOC_LINE_IN_CODE,
  3122. DOC_LINE_IN_CODEBLOCK,
  3123. DOC_LINE_IN_KBD,
  3124. };
  3125. static String _process_doc_line(const String &p_line, const String &p_text, const String &p_space_prefix, DocLineState &r_state) {
  3126. String line = p_line;
  3127. if (r_state == DOC_LINE_NORMAL) {
  3128. line = line.strip_edges(true, false);
  3129. } else {
  3130. line = line.trim_prefix(p_space_prefix);
  3131. }
  3132. String line_join;
  3133. if (!p_text.is_empty()) {
  3134. if (r_state == DOC_LINE_NORMAL) {
  3135. if (p_text.ends_with("[/codeblock]")) {
  3136. line_join = "\n";
  3137. } else if (!p_text.ends_with("[br]")) {
  3138. line_join = " ";
  3139. }
  3140. } else {
  3141. line_join = "\n";
  3142. }
  3143. }
  3144. String result;
  3145. int from = 0;
  3146. int buffer_start = 0;
  3147. const int len = line.length();
  3148. bool process = true;
  3149. while (process) {
  3150. switch (r_state) {
  3151. case DOC_LINE_NORMAL: {
  3152. int lb_pos = line.find_char('[', from);
  3153. if (lb_pos < 0) {
  3154. process = false;
  3155. break;
  3156. }
  3157. int rb_pos = line.find_char(']', lb_pos + 1);
  3158. if (rb_pos < 0) {
  3159. process = false;
  3160. break;
  3161. }
  3162. from = rb_pos + 1;
  3163. String tag = line.substr(lb_pos + 1, rb_pos - lb_pos - 1);
  3164. if (tag == "code" || tag.begins_with("code ")) {
  3165. r_state = DOC_LINE_IN_CODE;
  3166. } else if (tag == "codeblock" || tag.begins_with("codeblock ")) {
  3167. if (lb_pos == 0) {
  3168. line_join = "\n";
  3169. } else {
  3170. result += line.substr(buffer_start, lb_pos - buffer_start) + '\n';
  3171. }
  3172. result += "[" + tag + "]";
  3173. if (from < len) {
  3174. result += '\n';
  3175. }
  3176. r_state = DOC_LINE_IN_CODEBLOCK;
  3177. buffer_start = from;
  3178. } else if (tag == "kbd") {
  3179. r_state = DOC_LINE_IN_KBD;
  3180. }
  3181. } break;
  3182. case DOC_LINE_IN_CODE: {
  3183. int pos = line.find("[/code]", from);
  3184. if (pos < 0) {
  3185. process = false;
  3186. break;
  3187. }
  3188. from = pos + 7; // `len("[/code]")`.
  3189. r_state = DOC_LINE_NORMAL;
  3190. } break;
  3191. case DOC_LINE_IN_CODEBLOCK: {
  3192. int pos = line.find("[/codeblock]", from);
  3193. if (pos < 0) {
  3194. process = false;
  3195. break;
  3196. }
  3197. from = pos + 12; // `len("[/codeblock]")`.
  3198. if (pos == 0) {
  3199. line_join = "\n";
  3200. } else {
  3201. result += line.substr(buffer_start, pos - buffer_start) + '\n';
  3202. }
  3203. result += "[/codeblock]";
  3204. if (from < len) {
  3205. result += '\n';
  3206. }
  3207. r_state = DOC_LINE_NORMAL;
  3208. buffer_start = from;
  3209. } break;
  3210. case DOC_LINE_IN_KBD: {
  3211. int pos = line.find("[/kbd]", from);
  3212. if (pos < 0) {
  3213. process = false;
  3214. break;
  3215. }
  3216. from = pos + 6; // `len("[/kbd]")`.
  3217. r_state = DOC_LINE_NORMAL;
  3218. } break;
  3219. }
  3220. }
  3221. result += line.substr(buffer_start);
  3222. if (r_state == DOC_LINE_NORMAL) {
  3223. result = result.strip_edges(false, true);
  3224. }
  3225. return line_join + result;
  3226. }
  3227. bool GDScriptParser::has_comment(int p_line, bool p_must_be_doc) {
  3228. bool has_comment = tokenizer->get_comments().has(p_line);
  3229. // If there are no comments or if we don't care whether the comment
  3230. // is a docstring, we have our result.
  3231. if (!p_must_be_doc || !has_comment) {
  3232. return has_comment;
  3233. }
  3234. return tokenizer->get_comments()[p_line].comment.begins_with("##");
  3235. }
  3236. GDScriptParser::MemberDocData GDScriptParser::parse_doc_comment(int p_line, bool p_single_line) {
  3237. ERR_FAIL_COND_V(!has_comment(p_line, true), MemberDocData());
  3238. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  3239. int line = p_line;
  3240. if (!p_single_line) {
  3241. while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
  3242. line--;
  3243. }
  3244. }
  3245. max_script_doc_line = MIN(max_script_doc_line, line - 1);
  3246. String space_prefix;
  3247. {
  3248. int i = 2;
  3249. for (; i < comments[line].comment.length(); i++) {
  3250. if (comments[line].comment[i] != ' ') {
  3251. break;
  3252. }
  3253. }
  3254. space_prefix = String(" ").repeat(i - 2);
  3255. }
  3256. DocLineState state = DOC_LINE_NORMAL;
  3257. MemberDocData result;
  3258. while (line <= p_line) {
  3259. String doc_line = comments[line].comment.trim_prefix("##");
  3260. line++;
  3261. if (state == DOC_LINE_NORMAL) {
  3262. String stripped_line = doc_line.strip_edges();
  3263. if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
  3264. result.is_deprecated = true;
  3265. if (stripped_line.begins_with("@deprecated:")) {
  3266. result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
  3267. }
  3268. continue;
  3269. } else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
  3270. result.is_experimental = true;
  3271. if (stripped_line.begins_with("@experimental:")) {
  3272. result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
  3273. }
  3274. continue;
  3275. }
  3276. }
  3277. result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
  3278. }
  3279. return result;
  3280. }
  3281. GDScriptParser::ClassDocData GDScriptParser::parse_class_doc_comment(int p_line, bool p_single_line) {
  3282. ERR_FAIL_COND_V(!has_comment(p_line, true), ClassDocData());
  3283. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
  3284. int line = p_line;
  3285. if (!p_single_line) {
  3286. while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
  3287. line--;
  3288. }
  3289. }
  3290. max_script_doc_line = MIN(max_script_doc_line, line - 1);
  3291. String space_prefix;
  3292. {
  3293. int i = 2;
  3294. for (; i < comments[line].comment.length(); i++) {
  3295. if (comments[line].comment[i] != ' ') {
  3296. break;
  3297. }
  3298. }
  3299. space_prefix = String(" ").repeat(i - 2);
  3300. }
  3301. DocLineState state = DOC_LINE_NORMAL;
  3302. bool is_in_brief = true;
  3303. ClassDocData result;
  3304. while (line <= p_line) {
  3305. String doc_line = comments[line].comment.trim_prefix("##");
  3306. line++;
  3307. if (state == DOC_LINE_NORMAL) {
  3308. String stripped_line = doc_line.strip_edges();
  3309. // A blank line separates the description from the brief.
  3310. if (is_in_brief && !result.brief.is_empty() && stripped_line.is_empty()) {
  3311. is_in_brief = false;
  3312. continue;
  3313. }
  3314. if (stripped_line.begins_with("@tutorial")) {
  3315. String title, link;
  3316. int begin_scan = String("@tutorial").length();
  3317. if (begin_scan >= stripped_line.length()) {
  3318. continue; // Invalid syntax.
  3319. }
  3320. if (stripped_line[begin_scan] == ':') { // No title.
  3321. // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
  3322. title = "";
  3323. link = stripped_line.trim_prefix("@tutorial:").strip_edges();
  3324. } else {
  3325. /* Syntax:
  3326. * @tutorial ( The Title Here ) : https://the.url/
  3327. * ^ open ^ close ^ colon ^ url
  3328. */
  3329. int open_bracket_pos = begin_scan, close_bracket_pos = 0;
  3330. while (open_bracket_pos < stripped_line.length() && (stripped_line[open_bracket_pos] == ' ' || stripped_line[open_bracket_pos] == '\t')) {
  3331. open_bracket_pos++;
  3332. }
  3333. if (open_bracket_pos == stripped_line.length() || stripped_line[open_bracket_pos++] != '(') {
  3334. continue; // Invalid syntax.
  3335. }
  3336. close_bracket_pos = open_bracket_pos;
  3337. while (close_bracket_pos < stripped_line.length() && stripped_line[close_bracket_pos] != ')') {
  3338. close_bracket_pos++;
  3339. }
  3340. if (close_bracket_pos == stripped_line.length()) {
  3341. continue; // Invalid syntax.
  3342. }
  3343. int colon_pos = close_bracket_pos + 1;
  3344. while (colon_pos < stripped_line.length() && (stripped_line[colon_pos] == ' ' || stripped_line[colon_pos] == '\t')) {
  3345. colon_pos++;
  3346. }
  3347. if (colon_pos == stripped_line.length() || stripped_line[colon_pos++] != ':') {
  3348. continue; // Invalid syntax.
  3349. }
  3350. title = stripped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
  3351. link = stripped_line.substr(colon_pos).strip_edges();
  3352. }
  3353. result.tutorials.append(Pair<String, String>(title, link));
  3354. continue;
  3355. } else if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
  3356. result.is_deprecated = true;
  3357. if (stripped_line.begins_with("@deprecated:")) {
  3358. result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
  3359. }
  3360. continue;
  3361. } else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
  3362. result.is_experimental = true;
  3363. if (stripped_line.begins_with("@experimental:")) {
  3364. result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
  3365. }
  3366. continue;
  3367. }
  3368. }
  3369. if (is_in_brief) {
  3370. result.brief += _process_doc_line(doc_line, result.brief, space_prefix, state);
  3371. } else {
  3372. result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
  3373. }
  3374. }
  3375. return result;
  3376. }
  3377. #endif // TOOLS_ENABLED
  3378. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  3379. // Function table for expression parsing.
  3380. // clang-format destroys the alignment here, so turn off for the table.
  3381. /* clang-format off */
  3382. static ParseRule rules[] = {
  3383. // PREFIX INFIX PRECEDENCE (for infix)
  3384. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  3385. // Basic
  3386. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  3387. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  3388. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  3389. // Comparison
  3390. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  3391. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  3392. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  3393. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  3394. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  3395. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  3396. // Logical
  3397. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  3398. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  3399. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
  3400. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  3401. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  3402. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  3403. // Bitwise
  3404. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  3405. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  3406. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  3407. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  3408. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  3409. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  3410. // Math
  3411. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
  3412. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
  3413. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  3414. { nullptr, &GDScriptParser::parse_binary_operator, PREC_POWER }, // STAR_STAR,
  3415. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  3416. { &GDScriptParser::parse_get_node, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  3417. // Assignment
  3418. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  3419. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  3420. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  3421. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  3422. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_STAR_EQUAL,
  3423. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  3424. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  3425. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  3426. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  3427. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  3428. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  3429. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  3430. // Control flow
  3431. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  3432. { nullptr, nullptr, PREC_NONE }, // ELIF,
  3433. { nullptr, nullptr, PREC_NONE }, // ELSE,
  3434. { nullptr, nullptr, PREC_NONE }, // FOR,
  3435. { nullptr, nullptr, PREC_NONE }, // WHILE,
  3436. { nullptr, nullptr, PREC_NONE }, // BREAK,
  3437. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  3438. { nullptr, nullptr, PREC_NONE }, // PASS,
  3439. { nullptr, nullptr, PREC_NONE }, // RETURN,
  3440. { nullptr, nullptr, PREC_NONE }, // MATCH,
  3441. { nullptr, nullptr, PREC_NONE }, // WHEN,
  3442. // Keywords
  3443. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  3444. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  3445. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  3446. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  3447. { nullptr, nullptr, PREC_NONE }, // CLASS,
  3448. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  3449. { nullptr, nullptr, PREC_NONE }, // CONST,
  3450. { nullptr, nullptr, PREC_NONE }, // ENUM,
  3451. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  3452. { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
  3453. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN,
  3454. { nullptr, &GDScriptParser::parse_type_test, PREC_TYPE_TEST }, // IS,
  3455. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  3456. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  3457. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  3458. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  3459. { nullptr, nullptr, PREC_NONE }, // STATIC,
  3460. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  3461. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  3462. { nullptr, nullptr, PREC_NONE }, // VAR,
  3463. { nullptr, nullptr, PREC_NONE }, // VOID,
  3464. { &GDScriptParser::parse_yield, nullptr, PREC_NONE }, // YIELD,
  3465. // Punctuation
  3466. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  3467. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  3468. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  3469. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  3470. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  3471. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  3472. { nullptr, nullptr, PREC_NONE }, // COMMA,
  3473. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  3474. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  3475. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  3476. { nullptr, nullptr, PREC_NONE }, // COLON,
  3477. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  3478. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  3479. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  3480. // Whitespace
  3481. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  3482. { nullptr, nullptr, PREC_NONE }, // INDENT,
  3483. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  3484. // Constants
  3485. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  3486. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  3487. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  3488. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  3489. // Error message improvement
  3490. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  3491. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  3492. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  3493. // Special
  3494. { nullptr, nullptr, PREC_NONE }, // ERROR,
  3495. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  3496. };
  3497. /* clang-format on */
  3498. // Avoid desync.
  3499. static_assert(sizeof(rules) / sizeof(rules[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  3500. // Let's assume this is never invalid, since nothing generates a TK_MAX.
  3501. return &rules[p_token_type];
  3502. }
  3503. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  3504. if (locals_indices.has(p_name)) {
  3505. return true;
  3506. }
  3507. if (parent_block != nullptr) {
  3508. return parent_block->has_local(p_name);
  3509. }
  3510. return false;
  3511. }
  3512. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  3513. if (locals_indices.has(p_name)) {
  3514. return locals[locals_indices[p_name]];
  3515. }
  3516. if (parent_block != nullptr) {
  3517. return parent_block->get_local(p_name);
  3518. }
  3519. return empty;
  3520. }
  3521. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target, ClassNode *p_class) {
  3522. if (is_applied) {
  3523. return true;
  3524. }
  3525. is_applied = true;
  3526. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target, p_class);
  3527. }
  3528. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  3529. return (info->target_kind & p_target_kinds) > 0;
  3530. }
  3531. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  3532. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  3533. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  3534. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  3535. push_error(vformat(R"(Annotation "%s" requires at most %d arguments, but %d were given.)", p_annotation->name, info.arguments.size(), p_annotation->arguments.size()));
  3536. return false;
  3537. }
  3538. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  3539. push_error(vformat(R"(Annotation "%s" requires at least %d arguments, but %d were given.)", p_annotation->name, info.arguments.size() - info.default_arguments.size(), p_annotation->arguments.size()));
  3540. return false;
  3541. }
  3542. // Some annotations need to be resolved in the parser.
  3543. if (p_annotation->name == SNAME("@icon")) {
  3544. ExpressionNode *argument = p_annotation->arguments[0];
  3545. if (argument->type != Node::LITERAL) {
  3546. push_error(R"(Argument 1 of annotation "@icon" must be a string literal.)", argument);
  3547. return false;
  3548. }
  3549. Variant value = static_cast<LiteralNode *>(argument)->value;
  3550. if (value.get_type() != Variant::STRING) {
  3551. push_error(R"(Argument 1 of annotation "@icon" must be a string literal.)", argument);
  3552. return false;
  3553. }
  3554. p_annotation->resolved_arguments.push_back(value);
  3555. }
  3556. // For other annotations, see `GDScriptAnalyzer::resolve_annotation()`.
  3557. return true;
  3558. }
  3559. bool GDScriptParser::tool_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3560. #ifdef DEBUG_ENABLED
  3561. if (_is_tool) {
  3562. push_error(R"("@tool" annotation can only be used once.)", p_annotation);
  3563. return false;
  3564. }
  3565. #endif // DEBUG_ENABLED
  3566. _is_tool = true;
  3567. return true;
  3568. }
  3569. bool GDScriptParser::icon_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3570. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  3571. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  3572. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  3573. String path = p_annotation->resolved_arguments[0];
  3574. #ifdef DEBUG_ENABLED
  3575. if (!class_node->icon_path.is_empty()) {
  3576. push_error(R"("@icon" annotation can only be used once.)", p_annotation);
  3577. return false;
  3578. }
  3579. if (path.is_empty()) {
  3580. push_error(R"("@icon" annotation argument must contain the path to the icon.)", p_annotation->arguments[0]);
  3581. return false;
  3582. }
  3583. #endif // DEBUG_ENABLED
  3584. class_node->icon_path = path;
  3585. if (path.is_empty() || path.is_absolute_path()) {
  3586. class_node->simplified_icon_path = path.simplify_path();
  3587. } else if (path.is_relative_path()) {
  3588. class_node->simplified_icon_path = script_path.get_base_dir().path_join(path).simplify_path();
  3589. } else {
  3590. class_node->simplified_icon_path = path;
  3591. }
  3592. return true;
  3593. }
  3594. bool GDScriptParser::onready_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3595. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  3596. if (current_class && !ClassDB::is_parent_class(current_class->get_datatype().native_type, SNAME("Node"))) {
  3597. push_error(R"("@onready" can only be used in classes that inherit "Node".)", p_annotation);
  3598. return false;
  3599. }
  3600. VariableNode *variable = static_cast<VariableNode *>(p_target);
  3601. if (variable->is_static) {
  3602. push_error(R"("@onready" annotation cannot be applied to a static variable.)", p_annotation);
  3603. return false;
  3604. }
  3605. if (variable->onready) {
  3606. push_error(R"("@onready" annotation can only be used once per variable.)", p_annotation);
  3607. return false;
  3608. }
  3609. variable->onready = true;
  3610. current_class->onready_used = true;
  3611. return true;
  3612. }
  3613. static String _get_annotation_error_string(const StringName &p_annotation_name, const Vector<Variant::Type> &p_expected_types, const GDScriptParser::DataType &p_provided_type) {
  3614. Vector<String> types;
  3615. for (int i = 0; i < p_expected_types.size(); i++) {
  3616. const Variant::Type &type = p_expected_types[i];
  3617. types.push_back(Variant::get_type_name(type));
  3618. types.push_back("Array[" + Variant::get_type_name(type) + "]");
  3619. switch (type) {
  3620. case Variant::INT:
  3621. types.push_back("PackedByteArray");
  3622. types.push_back("PackedInt32Array");
  3623. types.push_back("PackedInt64Array");
  3624. break;
  3625. case Variant::FLOAT:
  3626. types.push_back("PackedFloat32Array");
  3627. types.push_back("PackedFloat64Array");
  3628. break;
  3629. case Variant::STRING:
  3630. types.push_back("PackedStringArray");
  3631. break;
  3632. case Variant::VECTOR2:
  3633. types.push_back("PackedVector2Array");
  3634. break;
  3635. case Variant::VECTOR3:
  3636. types.push_back("PackedVector3Array");
  3637. break;
  3638. case Variant::COLOR:
  3639. types.push_back("PackedColorArray");
  3640. break;
  3641. case Variant::VECTOR4:
  3642. types.push_back("PackedVector4Array");
  3643. break;
  3644. default:
  3645. break;
  3646. }
  3647. }
  3648. String string;
  3649. if (types.size() == 1) {
  3650. string = types[0].quote();
  3651. } else if (types.size() == 2) {
  3652. string = types[0].quote() + " or " + types[1].quote();
  3653. } else if (types.size() >= 3) {
  3654. string = types[0].quote();
  3655. for (int i = 1; i < types.size() - 1; i++) {
  3656. string += ", " + types[i].quote();
  3657. }
  3658. string += ", or " + types[types.size() - 1].quote();
  3659. }
  3660. return vformat(R"("%s" annotation requires a variable of type %s, but type "%s" was given instead.)", p_annotation_name, string, p_provided_type.to_string());
  3661. }
  3662. static StringName _find_narrowest_native_or_global_class(const GDScriptParser::DataType &p_type) {
  3663. switch (p_type.kind) {
  3664. case GDScriptParser::DataType::NATIVE: {
  3665. if (p_type.is_meta_type) {
  3666. return Object::get_class_static(); // `GDScriptNativeClass` is not an exposed class.
  3667. }
  3668. return p_type.native_type;
  3669. } break;
  3670. case GDScriptParser::DataType::SCRIPT: {
  3671. Ref<Script> script;
  3672. if (p_type.script_type.is_valid()) {
  3673. script = p_type.script_type;
  3674. } else {
  3675. script = ResourceLoader::load(p_type.script_path, SNAME("Script"));
  3676. }
  3677. if (p_type.is_meta_type) {
  3678. return script.is_valid() ? script->get_class() : Script::get_class_static();
  3679. }
  3680. if (script.is_null()) {
  3681. return p_type.native_type;
  3682. }
  3683. if (script->get_global_name() != StringName()) {
  3684. return script->get_global_name();
  3685. }
  3686. Ref<Script> base_script = script->get_base_script();
  3687. if (base_script.is_null()) {
  3688. return script->get_instance_base_type();
  3689. }
  3690. GDScriptParser::DataType base_type;
  3691. base_type.kind = GDScriptParser::DataType::SCRIPT;
  3692. base_type.builtin_type = Variant::OBJECT;
  3693. base_type.native_type = base_script->get_instance_base_type();
  3694. base_type.script_type = base_script;
  3695. base_type.script_path = base_script->get_path();
  3696. return _find_narrowest_native_or_global_class(base_type);
  3697. } break;
  3698. case GDScriptParser::DataType::CLASS: {
  3699. if (p_type.is_meta_type) {
  3700. return GDScript::get_class_static();
  3701. }
  3702. if (p_type.class_type == nullptr) {
  3703. return p_type.native_type;
  3704. }
  3705. if (p_type.class_type->get_global_name() != StringName()) {
  3706. return p_type.class_type->get_global_name();
  3707. }
  3708. return _find_narrowest_native_or_global_class(p_type.class_type->base_type);
  3709. } break;
  3710. default: {
  3711. ERR_FAIL_V(StringName());
  3712. } break;
  3713. }
  3714. }
  3715. template <PropertyHint t_hint, Variant::Type t_type>
  3716. bool GDScriptParser::export_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3717. ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3718. ERR_FAIL_NULL_V(p_class, false);
  3719. VariableNode *variable = static_cast<VariableNode *>(p_target);
  3720. if (variable->is_static) {
  3721. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  3722. return false;
  3723. }
  3724. if (variable->exported) {
  3725. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3726. return false;
  3727. }
  3728. variable->exported = true;
  3729. variable->export_info.type = t_type;
  3730. variable->export_info.hint = t_hint;
  3731. String hint_string;
  3732. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  3733. String arg_string = String(p_annotation->resolved_arguments[i]);
  3734. if (p_annotation->name != SNAME("@export_placeholder")) {
  3735. if (arg_string.is_empty()) {
  3736. push_error(vformat(R"(Argument %d of annotation "%s" is empty.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  3737. return false;
  3738. }
  3739. if (arg_string.contains(",")) {
  3740. push_error(vformat(R"(Argument %d of annotation "%s" contains a comma. Use separate arguments instead.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  3741. return false;
  3742. }
  3743. }
  3744. // WARNING: Do not merge with the previous `if` because there `!=`, not `==`!
  3745. if (p_annotation->name == SNAME("@export_flags")) {
  3746. const int64_t max_flags = 32;
  3747. Vector<String> t = arg_string.split(":", true, 1);
  3748. if (t[0].is_empty()) {
  3749. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag name.)", i + 1), p_annotation->arguments[i]);
  3750. return false;
  3751. }
  3752. if (t.size() == 2) {
  3753. if (t[1].is_empty()) {
  3754. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag value.)", i + 1), p_annotation->arguments[i]);
  3755. return false;
  3756. }
  3757. if (!t[1].is_valid_int()) {
  3758. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": The flag value must be a valid integer.)", i + 1), p_annotation->arguments[i]);
  3759. return false;
  3760. }
  3761. int64_t value = t[1].to_int();
  3762. if (value < 1 || value >= (1LL << max_flags)) {
  3763. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": The flag value must be at least 1 and at most 2 ** %d - 1.)", i + 1, max_flags), p_annotation->arguments[i]);
  3764. return false;
  3765. }
  3766. } else if (i >= max_flags) {
  3767. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Starting from argument %d, the flag value must be specified explicitly.)", i + 1, max_flags + 1), p_annotation->arguments[i]);
  3768. return false;
  3769. }
  3770. } else if (p_annotation->name == SNAME("@export_node_path")) {
  3771. String native_class = arg_string;
  3772. if (ScriptServer::is_global_class(arg_string)) {
  3773. native_class = ScriptServer::get_global_class_native_base(arg_string);
  3774. }
  3775. if (!ClassDB::class_exists(native_class)) {
  3776. push_error(vformat(R"(Invalid argument %d of annotation "@export_node_path": The class "%s" was not found in the global scope.)", i + 1, arg_string), p_annotation->arguments[i]);
  3777. return false;
  3778. } else if (!ClassDB::is_parent_class(native_class, SNAME("Node"))) {
  3779. push_error(vformat(R"(Invalid argument %d of annotation "@export_node_path": The class "%s" does not inherit "Node".)", i + 1, arg_string), p_annotation->arguments[i]);
  3780. return false;
  3781. }
  3782. }
  3783. if (i > 0) {
  3784. hint_string += ",";
  3785. }
  3786. hint_string += arg_string;
  3787. }
  3788. variable->export_info.hint_string = hint_string;
  3789. // This is called after the analyzer is done finding the type, so this should be set here.
  3790. DataType export_type = variable->get_datatype();
  3791. // Use initializer type if specified type is `Variant`.
  3792. if (export_type.is_variant() && variable->initializer != nullptr && variable->initializer->datatype.is_set()) {
  3793. export_type = variable->initializer->get_datatype();
  3794. export_type.type_source = DataType::INFERRED;
  3795. }
  3796. const Variant::Type original_export_type_builtin = export_type.builtin_type;
  3797. // Process array and packed array annotations on the element type.
  3798. bool is_array = false;
  3799. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type(0)) {
  3800. is_array = true;
  3801. export_type = export_type.get_container_element_type(0);
  3802. } else if (export_type.is_typed_container_type()) {
  3803. is_array = true;
  3804. export_type = export_type.get_typed_container_type();
  3805. export_type.type_source = variable->datatype.type_source;
  3806. }
  3807. bool use_default_variable_type_check = true;
  3808. if (p_annotation->name == SNAME("@export_range")) {
  3809. if (export_type.builtin_type == Variant::INT) {
  3810. variable->export_info.type = Variant::INT;
  3811. }
  3812. } else if (p_annotation->name == SNAME("@export_multiline")) {
  3813. use_default_variable_type_check = false;
  3814. if (export_type.builtin_type != Variant::STRING && export_type.builtin_type != Variant::DICTIONARY) {
  3815. Vector<Variant::Type> expected_types = { Variant::STRING, Variant::DICTIONARY };
  3816. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  3817. return false;
  3818. }
  3819. if (export_type.builtin_type == Variant::DICTIONARY) {
  3820. variable->export_info.type = Variant::DICTIONARY;
  3821. }
  3822. } else if (p_annotation->name == SNAME("@export")) {
  3823. use_default_variable_type_check = false;
  3824. if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
  3825. push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  3826. return false;
  3827. }
  3828. if (export_type.is_variant() || export_type.has_no_type()) {
  3829. push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
  3830. return false;
  3831. }
  3832. switch (export_type.kind) {
  3833. case GDScriptParser::DataType::BUILTIN:
  3834. variable->export_info.type = export_type.builtin_type;
  3835. variable->export_info.hint = PROPERTY_HINT_NONE;
  3836. variable->export_info.hint_string = String();
  3837. break;
  3838. case GDScriptParser::DataType::NATIVE:
  3839. case GDScriptParser::DataType::SCRIPT:
  3840. case GDScriptParser::DataType::CLASS: {
  3841. const StringName class_name = _find_narrowest_native_or_global_class(export_type);
  3842. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  3843. variable->export_info.type = Variant::OBJECT;
  3844. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  3845. variable->export_info.hint_string = class_name;
  3846. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  3847. variable->export_info.type = Variant::OBJECT;
  3848. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  3849. variable->export_info.hint_string = class_name;
  3850. } else {
  3851. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  3852. return false;
  3853. }
  3854. } break;
  3855. case GDScriptParser::DataType::ENUM: {
  3856. if (export_type.is_meta_type) {
  3857. variable->export_info.type = Variant::DICTIONARY;
  3858. } else {
  3859. variable->export_info.type = Variant::INT;
  3860. variable->export_info.hint = PROPERTY_HINT_ENUM;
  3861. String enum_hint_string;
  3862. bool first = true;
  3863. for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
  3864. if (!first) {
  3865. enum_hint_string += ",";
  3866. } else {
  3867. first = false;
  3868. }
  3869. enum_hint_string += E.key.operator String().capitalize().xml_escape();
  3870. enum_hint_string += ":";
  3871. enum_hint_string += String::num_int64(E.value).xml_escape();
  3872. }
  3873. variable->export_info.hint_string = enum_hint_string;
  3874. variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  3875. variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
  3876. }
  3877. } break;
  3878. default:
  3879. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
  3880. return false;
  3881. }
  3882. if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
  3883. push_error(vformat(R"(Node export is only supported in Node-derived classes, but the current class inherits "%s".)", p_class->base_type.to_string()), p_annotation);
  3884. return false;
  3885. }
  3886. } else if (p_annotation->name == SNAME("@export_enum")) {
  3887. use_default_variable_type_check = false;
  3888. Variant::Type enum_type = Variant::INT;
  3889. if (export_type.kind == DataType::BUILTIN && export_type.builtin_type == Variant::STRING) {
  3890. enum_type = Variant::STRING;
  3891. }
  3892. variable->export_info.type = enum_type;
  3893. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != enum_type)) {
  3894. Vector<Variant::Type> expected_types = { Variant::INT, Variant::STRING };
  3895. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  3896. return false;
  3897. }
  3898. }
  3899. if (use_default_variable_type_check) {
  3900. // Validate variable type with export.
  3901. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
  3902. // Allow float/int conversion.
  3903. if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
  3904. Vector<Variant::Type> expected_types = { t_type };
  3905. push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
  3906. return false;
  3907. }
  3908. }
  3909. }
  3910. if (is_array) {
  3911. String hint_prefix = itos(variable->export_info.type);
  3912. if (variable->export_info.hint) {
  3913. hint_prefix += "/" + itos(variable->export_info.hint);
  3914. }
  3915. variable->export_info.type = original_export_type_builtin;
  3916. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  3917. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  3918. variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
  3919. variable->export_info.class_name = StringName();
  3920. }
  3921. return true;
  3922. }
  3923. // For `@export_storage` and `@export_custom`, there is no need to check the variable type, argument values,
  3924. // or handle array exports in a special way, so they are implemented as separate methods.
  3925. bool GDScriptParser::export_storage_annotation(AnnotationNode *p_annotation, Node *p_node, ClassNode *p_class) {
  3926. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3927. VariableNode *variable = static_cast<VariableNode *>(p_node);
  3928. if (variable->is_static) {
  3929. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  3930. return false;
  3931. }
  3932. if (variable->exported) {
  3933. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3934. return false;
  3935. }
  3936. variable->exported = true;
  3937. // Save the info because the compiler uses export info for overwriting member info.
  3938. variable->export_info = variable->get_datatype().to_property_info(variable->identifier->name);
  3939. variable->export_info.usage |= PROPERTY_USAGE_STORAGE;
  3940. return true;
  3941. }
  3942. bool GDScriptParser::export_custom_annotation(AnnotationNode *p_annotation, Node *p_node, ClassNode *p_class) {
  3943. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3944. ERR_FAIL_COND_V_MSG(p_annotation->resolved_arguments.size() < 2, false, R"(Annotation "@export_custom" requires 2 arguments.)");
  3945. VariableNode *variable = static_cast<VariableNode *>(p_node);
  3946. if (variable->is_static) {
  3947. push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
  3948. return false;
  3949. }
  3950. if (variable->exported) {
  3951. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3952. return false;
  3953. }
  3954. variable->exported = true;
  3955. DataType export_type = variable->get_datatype();
  3956. variable->export_info.type = export_type.builtin_type;
  3957. variable->export_info.hint = static_cast<PropertyHint>(p_annotation->resolved_arguments[0].operator int64_t());
  3958. variable->export_info.hint_string = p_annotation->resolved_arguments[1];
  3959. if (p_annotation->resolved_arguments.size() >= 3) {
  3960. variable->export_info.usage = p_annotation->resolved_arguments[2].operator int64_t();
  3961. }
  3962. return true;
  3963. }
  3964. template <PropertyUsageFlags t_usage>
  3965. bool GDScriptParser::export_group_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3966. if (p_annotation->resolved_arguments.is_empty()) {
  3967. return false;
  3968. }
  3969. p_annotation->export_info.name = p_annotation->resolved_arguments[0];
  3970. switch (t_usage) {
  3971. case PROPERTY_USAGE_CATEGORY: {
  3972. p_annotation->export_info.usage = t_usage;
  3973. } break;
  3974. case PROPERTY_USAGE_GROUP: {
  3975. p_annotation->export_info.usage = t_usage;
  3976. if (p_annotation->resolved_arguments.size() == 2) {
  3977. p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
  3978. }
  3979. } break;
  3980. case PROPERTY_USAGE_SUBGROUP: {
  3981. p_annotation->export_info.usage = t_usage;
  3982. if (p_annotation->resolved_arguments.size() == 2) {
  3983. p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
  3984. }
  3985. } break;
  3986. }
  3987. return true;
  3988. }
  3989. bool GDScriptParser::warning_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  3990. #ifndef DEBUG_ENABLED
  3991. // Only available in debug builds.
  3992. return true;
  3993. #else // DEBUG_ENABLED
  3994. if (is_ignoring_warnings) {
  3995. return true; // We already ignore all warnings, let's optimize it.
  3996. }
  3997. bool has_error = false;
  3998. for (const Variant &warning_name : p_annotation->resolved_arguments) {
  3999. GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
  4000. if (warning_code == GDScriptWarning::WARNING_MAX) {
  4001. push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
  4002. has_error = true;
  4003. } else {
  4004. int start_line = p_annotation->start_line;
  4005. int end_line = p_target->end_line;
  4006. switch (p_target->type) {
  4007. #define SIMPLE_CASE(m_type, m_class, m_property) \
  4008. case m_type: { \
  4009. m_class *node = static_cast<m_class *>(p_target); \
  4010. if (node->m_property == nullptr) { \
  4011. end_line = node->start_line; \
  4012. } else { \
  4013. end_line = node->m_property->end_line; \
  4014. } \
  4015. } break;
  4016. // Can contain properties (set/get).
  4017. SIMPLE_CASE(Node::VARIABLE, VariableNode, initializer)
  4018. // Contain bodies.
  4019. SIMPLE_CASE(Node::FOR, ForNode, list)
  4020. SIMPLE_CASE(Node::IF, IfNode, condition)
  4021. SIMPLE_CASE(Node::MATCH, MatchNode, test)
  4022. SIMPLE_CASE(Node::WHILE, WhileNode, condition)
  4023. #undef SIMPLE_CASE
  4024. case Node::CLASS: {
  4025. end_line = p_target->start_line;
  4026. for (const AnnotationNode *annotation : p_target->annotations) {
  4027. start_line = MIN(start_line, annotation->start_line);
  4028. end_line = MAX(end_line, annotation->end_line);
  4029. }
  4030. } break;
  4031. case Node::FUNCTION: {
  4032. // `@warning_ignore` on function has a controversial feature that is used in tests.
  4033. // It's better not to remove it for now, while there is no way to mass-ignore warnings.
  4034. } break;
  4035. case Node::MATCH_BRANCH: {
  4036. MatchBranchNode *branch = static_cast<MatchBranchNode *>(p_target);
  4037. end_line = branch->start_line;
  4038. for (int i = 0; i < branch->patterns.size(); i++) {
  4039. end_line = MAX(end_line, branch->patterns[i]->end_line);
  4040. }
  4041. } break;
  4042. default: {
  4043. } break;
  4044. }
  4045. end_line = MAX(start_line, end_line); // Prevent infinite loop.
  4046. for (int line = start_line; line <= end_line; line++) {
  4047. warning_ignored_lines[warning_code].insert(line);
  4048. }
  4049. }
  4050. }
  4051. return !has_error;
  4052. #endif // DEBUG_ENABLED
  4053. }
  4054. bool GDScriptParser::rpc_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4055. ERR_FAIL_COND_V_MSG(p_target->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name));
  4056. FunctionNode *function = static_cast<FunctionNode *>(p_target);
  4057. if (function->rpc_config.get_type() != Variant::NIL) {
  4058. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  4059. return false;
  4060. }
  4061. Dictionary rpc_config;
  4062. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  4063. if (!p_annotation->resolved_arguments.is_empty()) {
  4064. unsigned char locality_args = 0;
  4065. unsigned char permission_args = 0;
  4066. unsigned char transfer_mode_args = 0;
  4067. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  4068. if (i == 3) {
  4069. rpc_config["channel"] = p_annotation->resolved_arguments[i].operator int();
  4070. continue;
  4071. }
  4072. String arg = p_annotation->resolved_arguments[i].operator String();
  4073. if (arg == "call_local") {
  4074. locality_args++;
  4075. rpc_config["call_local"] = true;
  4076. } else if (arg == "call_remote") {
  4077. locality_args++;
  4078. rpc_config["call_local"] = false;
  4079. } else if (arg == "any_peer") {
  4080. permission_args++;
  4081. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_ANY_PEER;
  4082. } else if (arg == "authority") {
  4083. permission_args++;
  4084. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  4085. } else if (arg == "reliable") {
  4086. transfer_mode_args++;
  4087. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE;
  4088. } else if (arg == "unreliable") {
  4089. transfer_mode_args++;
  4090. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE;
  4091. } else if (arg == "unreliable_ordered") {
  4092. transfer_mode_args++;
  4093. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED;
  4094. } else {
  4095. push_error(R"(Invalid RPC argument. Must be one of: "call_local"/"call_remote" (local calls), "any_peer"/"authority" (permission), "reliable"/"unreliable"/"unreliable_ordered" (transfer mode).)", p_annotation);
  4096. }
  4097. }
  4098. if (locality_args > 1) {
  4099. push_error(R"(Invalid RPC config. The locality ("call_local"/"call_remote") must be specified no more than once.)", p_annotation);
  4100. } else if (permission_args > 1) {
  4101. push_error(R"(Invalid RPC config. The permission ("any_peer"/"authority") must be specified no more than once.)", p_annotation);
  4102. } else if (transfer_mode_args > 1) {
  4103. push_error(R"(Invalid RPC config. The transfer mode ("reliable"/"unreliable"/"unreliable_ordered") must be specified no more than once.)", p_annotation);
  4104. }
  4105. }
  4106. function->rpc_config = rpc_config;
  4107. return true;
  4108. }
  4109. bool GDScriptParser::static_unload_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
  4110. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, vformat(R"("%s" annotation can only be applied to classes.)", p_annotation->name));
  4111. ClassNode *class_node = static_cast<ClassNode *>(p_target);
  4112. if (class_node->annotated_static_unload) {
  4113. push_error(vformat(R"("%s" annotation can only be used once per script.)", p_annotation->name), p_annotation);
  4114. return false;
  4115. }
  4116. class_node->annotated_static_unload = true;
  4117. return true;
  4118. }
  4119. GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
  4120. switch (type) {
  4121. case CONSTANT:
  4122. return constant->get_datatype();
  4123. case VARIABLE:
  4124. return variable->get_datatype();
  4125. case PARAMETER:
  4126. return parameter->get_datatype();
  4127. case FOR_VARIABLE:
  4128. case PATTERN_BIND:
  4129. return bind->get_datatype();
  4130. case UNDEFINED:
  4131. return DataType();
  4132. }
  4133. return DataType();
  4134. }
  4135. String GDScriptParser::SuiteNode::Local::get_name() const {
  4136. switch (type) {
  4137. case SuiteNode::Local::PARAMETER:
  4138. return "parameter";
  4139. case SuiteNode::Local::CONSTANT:
  4140. return "constant";
  4141. case SuiteNode::Local::VARIABLE:
  4142. return "variable";
  4143. case SuiteNode::Local::FOR_VARIABLE:
  4144. return "for loop iterator";
  4145. case SuiteNode::Local::PATTERN_BIND:
  4146. return "pattern bind";
  4147. case SuiteNode::Local::UNDEFINED:
  4148. return "<undefined>";
  4149. default:
  4150. return String();
  4151. }
  4152. }
  4153. String GDScriptParser::DataType::to_string() const {
  4154. switch (kind) {
  4155. case VARIANT:
  4156. return "Variant";
  4157. case BUILTIN:
  4158. if (builtin_type == Variant::NIL) {
  4159. return "null";
  4160. }
  4161. if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
  4162. return vformat("Array[%s]", container_element_types[0].to_string());
  4163. }
  4164. return Variant::get_type_name(builtin_type);
  4165. case NATIVE:
  4166. if (is_meta_type) {
  4167. return GDScriptNativeClass::get_class_static();
  4168. }
  4169. return native_type.operator String();
  4170. case CLASS:
  4171. if (class_type->identifier != nullptr) {
  4172. return class_type->identifier->name.operator String();
  4173. }
  4174. return class_type->fqcn;
  4175. case SCRIPT: {
  4176. if (is_meta_type) {
  4177. return script_type.is_valid() ? script_type->get_class_name().operator String() : "";
  4178. }
  4179. String name = script_type.is_valid() ? script_type->get_name() : "";
  4180. if (!name.is_empty()) {
  4181. return name;
  4182. }
  4183. name = script_path;
  4184. if (!name.is_empty()) {
  4185. return name;
  4186. }
  4187. return native_type.operator String();
  4188. }
  4189. case ENUM: {
  4190. // native_type contains either the native class defining the enum
  4191. // or the fully qualified class name of the script defining the enum
  4192. return String(native_type).get_file(); // Remove path, keep filename
  4193. }
  4194. case RESOLVING:
  4195. case UNRESOLVED:
  4196. return "<unresolved type>";
  4197. }
  4198. ERR_FAIL_V_MSG("<unresolved type>", "Kind set outside the enum range.");
  4199. }
  4200. PropertyInfo GDScriptParser::DataType::to_property_info(const String &p_name) const {
  4201. PropertyInfo result;
  4202. result.name = p_name;
  4203. result.usage = PROPERTY_USAGE_NONE;
  4204. if (!is_hard_type()) {
  4205. result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4206. return result;
  4207. }
  4208. switch (kind) {
  4209. case BUILTIN:
  4210. result.type = builtin_type;
  4211. if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
  4212. const DataType elem_type = get_container_element_type(0);
  4213. switch (elem_type.kind) {
  4214. case BUILTIN:
  4215. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4216. result.hint_string = Variant::get_type_name(elem_type.builtin_type);
  4217. break;
  4218. case NATIVE:
  4219. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4220. result.hint_string = elem_type.native_type;
  4221. break;
  4222. case SCRIPT:
  4223. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4224. if (elem_type.script_type.is_valid() && elem_type.script_type->get_global_name() != StringName()) {
  4225. result.hint_string = elem_type.script_type->get_global_name();
  4226. } else {
  4227. result.hint_string = elem_type.native_type;
  4228. }
  4229. break;
  4230. case CLASS:
  4231. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4232. if (elem_type.class_type != nullptr && elem_type.class_type->get_global_name() != StringName()) {
  4233. result.hint_string = elem_type.class_type->get_global_name();
  4234. } else {
  4235. result.hint_string = elem_type.native_type;
  4236. }
  4237. break;
  4238. case ENUM:
  4239. result.hint = PROPERTY_HINT_ARRAY_TYPE;
  4240. result.hint_string = String(elem_type.native_type).replace("::", ".");
  4241. break;
  4242. case VARIANT:
  4243. case RESOLVING:
  4244. case UNRESOLVED:
  4245. break;
  4246. }
  4247. }
  4248. break;
  4249. case NATIVE:
  4250. result.type = Variant::OBJECT;
  4251. if (is_meta_type) {
  4252. result.class_name = GDScriptNativeClass::get_class_static();
  4253. } else {
  4254. result.class_name = native_type;
  4255. }
  4256. break;
  4257. case SCRIPT:
  4258. result.type = Variant::OBJECT;
  4259. if (is_meta_type) {
  4260. result.class_name = script_type.is_valid() ? script_type->get_class() : Script::get_class_static();
  4261. } else if (script_type.is_valid() && script_type->get_global_name() != StringName()) {
  4262. result.class_name = script_type->get_global_name();
  4263. } else {
  4264. result.class_name = native_type;
  4265. }
  4266. break;
  4267. case CLASS:
  4268. result.type = Variant::OBJECT;
  4269. if (is_meta_type) {
  4270. result.class_name = GDScript::get_class_static();
  4271. } else if (class_type != nullptr && class_type->get_global_name() != StringName()) {
  4272. result.class_name = class_type->get_global_name();
  4273. } else {
  4274. result.class_name = native_type;
  4275. }
  4276. break;
  4277. case ENUM:
  4278. if (is_meta_type) {
  4279. result.type = Variant::DICTIONARY;
  4280. } else {
  4281. result.type = Variant::INT;
  4282. result.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
  4283. result.class_name = String(native_type).replace("::", ".");
  4284. }
  4285. break;
  4286. case VARIANT:
  4287. case RESOLVING:
  4288. case UNRESOLVED:
  4289. result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  4290. break;
  4291. }
  4292. return result;
  4293. }
  4294. static Variant::Type _variant_type_to_typed_array_element_type(Variant::Type p_type) {
  4295. switch (p_type) {
  4296. case Variant::PACKED_BYTE_ARRAY:
  4297. case Variant::PACKED_INT32_ARRAY:
  4298. case Variant::PACKED_INT64_ARRAY:
  4299. return Variant::INT;
  4300. case Variant::PACKED_FLOAT32_ARRAY:
  4301. case Variant::PACKED_FLOAT64_ARRAY:
  4302. return Variant::FLOAT;
  4303. case Variant::PACKED_STRING_ARRAY:
  4304. return Variant::STRING;
  4305. case Variant::PACKED_VECTOR2_ARRAY:
  4306. return Variant::VECTOR2;
  4307. case Variant::PACKED_VECTOR3_ARRAY:
  4308. return Variant::VECTOR3;
  4309. case Variant::PACKED_COLOR_ARRAY:
  4310. return Variant::COLOR;
  4311. case Variant::PACKED_VECTOR4_ARRAY:
  4312. return Variant::VECTOR4;
  4313. default:
  4314. return Variant::NIL;
  4315. }
  4316. }
  4317. bool GDScriptParser::DataType::is_typed_container_type() const {
  4318. return kind == GDScriptParser::DataType::BUILTIN && _variant_type_to_typed_array_element_type(builtin_type) != Variant::NIL;
  4319. }
  4320. GDScriptParser::DataType GDScriptParser::DataType::get_typed_container_type() const {
  4321. GDScriptParser::DataType type;
  4322. type.kind = GDScriptParser::DataType::BUILTIN;
  4323. type.builtin_type = _variant_type_to_typed_array_element_type(builtin_type);
  4324. return type;
  4325. }
  4326. void GDScriptParser::complete_extents(Node *p_node) {
  4327. while (!nodes_in_progress.is_empty() && nodes_in_progress.back()->get() != p_node) {
  4328. ERR_PRINT("Parser bug: Mismatch in extents tracking stack.");
  4329. nodes_in_progress.pop_back();
  4330. }
  4331. if (nodes_in_progress.is_empty()) {
  4332. ERR_PRINT("Parser bug: Extents tracking stack is empty.");
  4333. } else {
  4334. nodes_in_progress.pop_back();
  4335. }
  4336. }
  4337. void GDScriptParser::update_extents(Node *p_node) {
  4338. p_node->end_line = previous.end_line;
  4339. p_node->end_column = previous.end_column;
  4340. p_node->leftmost_column = MIN(p_node->leftmost_column, previous.leftmost_column);
  4341. p_node->rightmost_column = MAX(p_node->rightmost_column, previous.rightmost_column);
  4342. }
  4343. void GDScriptParser::reset_extents(Node *p_node, GDScriptTokenizer::Token p_token) {
  4344. p_node->start_line = p_token.start_line;
  4345. p_node->end_line = p_token.end_line;
  4346. p_node->start_column = p_token.start_column;
  4347. p_node->end_column = p_token.end_column;
  4348. p_node->leftmost_column = p_token.leftmost_column;
  4349. p_node->rightmost_column = p_token.rightmost_column;
  4350. }
  4351. void GDScriptParser::reset_extents(Node *p_node, Node *p_from) {
  4352. if (p_from == nullptr) {
  4353. return;
  4354. }
  4355. p_node->start_line = p_from->start_line;
  4356. p_node->end_line = p_from->end_line;
  4357. p_node->start_column = p_from->start_column;
  4358. p_node->end_column = p_from->end_column;
  4359. p_node->leftmost_column = p_from->leftmost_column;
  4360. p_node->rightmost_column = p_from->rightmost_column;
  4361. }
  4362. /*---------- PRETTY PRINT FOR DEBUG ----------*/
  4363. #ifdef DEBUG_ENABLED
  4364. void GDScriptParser::TreePrinter::increase_indent() {
  4365. indent_level++;
  4366. indent = "";
  4367. for (int i = 0; i < indent_level * 4; i++) {
  4368. if (i % 4 == 0) {
  4369. indent += "|";
  4370. } else {
  4371. indent += " ";
  4372. }
  4373. }
  4374. }
  4375. void GDScriptParser::TreePrinter::decrease_indent() {
  4376. indent_level--;
  4377. indent = "";
  4378. for (int i = 0; i < indent_level * 4; i++) {
  4379. if (i % 4 == 0) {
  4380. indent += "|";
  4381. } else {
  4382. indent += " ";
  4383. }
  4384. }
  4385. }
  4386. void GDScriptParser::TreePrinter::push_line(const String &p_line) {
  4387. if (!p_line.is_empty()) {
  4388. push_text(p_line);
  4389. }
  4390. printed += "\n";
  4391. pending_indent = true;
  4392. }
  4393. void GDScriptParser::TreePrinter::push_text(const String &p_text) {
  4394. if (pending_indent) {
  4395. printed += indent;
  4396. pending_indent = false;
  4397. }
  4398. printed += p_text;
  4399. }
  4400. void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
  4401. push_text(p_annotation->name);
  4402. push_text(" (");
  4403. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  4404. if (i > 0) {
  4405. push_text(" , ");
  4406. }
  4407. print_expression(p_annotation->arguments[i]);
  4408. }
  4409. push_line(")");
  4410. }
  4411. void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
  4412. push_text("[ ");
  4413. for (int i = 0; i < p_array->elements.size(); i++) {
  4414. if (i > 0) {
  4415. push_text(" , ");
  4416. }
  4417. print_expression(p_array->elements[i]);
  4418. }
  4419. push_text(" ]");
  4420. }
  4421. void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
  4422. push_text("Assert ( ");
  4423. print_expression(p_assert->condition);
  4424. push_line(" )");
  4425. }
  4426. void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
  4427. switch (p_assignment->assignee->type) {
  4428. case Node::IDENTIFIER:
  4429. print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
  4430. break;
  4431. case Node::SUBSCRIPT:
  4432. print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
  4433. break;
  4434. default:
  4435. break; // Unreachable.
  4436. }
  4437. push_text(" ");
  4438. switch (p_assignment->operation) {
  4439. case AssignmentNode::OP_ADDITION:
  4440. push_text("+");
  4441. break;
  4442. case AssignmentNode::OP_SUBTRACTION:
  4443. push_text("-");
  4444. break;
  4445. case AssignmentNode::OP_MULTIPLICATION:
  4446. push_text("*");
  4447. break;
  4448. case AssignmentNode::OP_DIVISION:
  4449. push_text("/");
  4450. break;
  4451. case AssignmentNode::OP_MODULO:
  4452. push_text("%");
  4453. break;
  4454. case AssignmentNode::OP_POWER:
  4455. push_text("**");
  4456. break;
  4457. case AssignmentNode::OP_BIT_SHIFT_LEFT:
  4458. push_text("<<");
  4459. break;
  4460. case AssignmentNode::OP_BIT_SHIFT_RIGHT:
  4461. push_text(">>");
  4462. break;
  4463. case AssignmentNode::OP_BIT_AND:
  4464. push_text("&");
  4465. break;
  4466. case AssignmentNode::OP_BIT_OR:
  4467. push_text("|");
  4468. break;
  4469. case AssignmentNode::OP_BIT_XOR:
  4470. push_text("^");
  4471. break;
  4472. case AssignmentNode::OP_NONE:
  4473. break;
  4474. }
  4475. push_text("= ");
  4476. print_expression(p_assignment->assigned_value);
  4477. push_line();
  4478. }
  4479. void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
  4480. push_text("Await ");
  4481. print_expression(p_await->to_await);
  4482. }
  4483. void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
  4484. // Surround in parenthesis for disambiguation.
  4485. push_text("(");
  4486. print_expression(p_binary_op->left_operand);
  4487. switch (p_binary_op->operation) {
  4488. case BinaryOpNode::OP_ADDITION:
  4489. push_text(" + ");
  4490. break;
  4491. case BinaryOpNode::OP_SUBTRACTION:
  4492. push_text(" - ");
  4493. break;
  4494. case BinaryOpNode::OP_MULTIPLICATION:
  4495. push_text(" * ");
  4496. break;
  4497. case BinaryOpNode::OP_DIVISION:
  4498. push_text(" / ");
  4499. break;
  4500. case BinaryOpNode::OP_MODULO:
  4501. push_text(" % ");
  4502. break;
  4503. case BinaryOpNode::OP_POWER:
  4504. push_text(" ** ");
  4505. break;
  4506. case BinaryOpNode::OP_BIT_LEFT_SHIFT:
  4507. push_text(" << ");
  4508. break;
  4509. case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
  4510. push_text(" >> ");
  4511. break;
  4512. case BinaryOpNode::OP_BIT_AND:
  4513. push_text(" & ");
  4514. break;
  4515. case BinaryOpNode::OP_BIT_OR:
  4516. push_text(" | ");
  4517. break;
  4518. case BinaryOpNode::OP_BIT_XOR:
  4519. push_text(" ^ ");
  4520. break;
  4521. case BinaryOpNode::OP_LOGIC_AND:
  4522. push_text(" AND ");
  4523. break;
  4524. case BinaryOpNode::OP_LOGIC_OR:
  4525. push_text(" OR ");
  4526. break;
  4527. case BinaryOpNode::OP_CONTENT_TEST:
  4528. push_text(" IN ");
  4529. break;
  4530. case BinaryOpNode::OP_COMP_EQUAL:
  4531. push_text(" == ");
  4532. break;
  4533. case BinaryOpNode::OP_COMP_NOT_EQUAL:
  4534. push_text(" != ");
  4535. break;
  4536. case BinaryOpNode::OP_COMP_LESS:
  4537. push_text(" < ");
  4538. break;
  4539. case BinaryOpNode::OP_COMP_LESS_EQUAL:
  4540. push_text(" <= ");
  4541. break;
  4542. case BinaryOpNode::OP_COMP_GREATER:
  4543. push_text(" > ");
  4544. break;
  4545. case BinaryOpNode::OP_COMP_GREATER_EQUAL:
  4546. push_text(" >= ");
  4547. break;
  4548. }
  4549. print_expression(p_binary_op->right_operand);
  4550. // Surround in parenthesis for disambiguation.
  4551. push_text(")");
  4552. }
  4553. void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
  4554. if (p_call->is_super) {
  4555. push_text("super");
  4556. if (p_call->callee != nullptr) {
  4557. push_text(".");
  4558. print_expression(p_call->callee);
  4559. }
  4560. } else {
  4561. print_expression(p_call->callee);
  4562. }
  4563. push_text("( ");
  4564. for (int i = 0; i < p_call->arguments.size(); i++) {
  4565. if (i > 0) {
  4566. push_text(" , ");
  4567. }
  4568. print_expression(p_call->arguments[i]);
  4569. }
  4570. push_text(" )");
  4571. }
  4572. void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
  4573. print_expression(p_cast->operand);
  4574. push_text(" AS ");
  4575. print_type(p_cast->cast_type);
  4576. }
  4577. void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
  4578. push_text("Class ");
  4579. if (p_class->identifier == nullptr) {
  4580. push_text("<unnamed>");
  4581. } else {
  4582. print_identifier(p_class->identifier);
  4583. }
  4584. if (p_class->extends_used) {
  4585. bool first = true;
  4586. push_text(" Extends ");
  4587. if (!p_class->extends_path.is_empty()) {
  4588. push_text(vformat(R"("%s")", p_class->extends_path));
  4589. first = false;
  4590. }
  4591. for (int i = 0; i < p_class->extends.size(); i++) {
  4592. if (!first) {
  4593. push_text(".");
  4594. } else {
  4595. first = false;
  4596. }
  4597. push_text(p_class->extends[i]->name);
  4598. }
  4599. }
  4600. push_line(" :");
  4601. increase_indent();
  4602. for (int i = 0; i < p_class->members.size(); i++) {
  4603. const ClassNode::Member &m = p_class->members[i];
  4604. switch (m.type) {
  4605. case ClassNode::Member::CLASS:
  4606. print_class(m.m_class);
  4607. break;
  4608. case ClassNode::Member::VARIABLE:
  4609. print_variable(m.variable);
  4610. break;
  4611. case ClassNode::Member::CONSTANT:
  4612. print_constant(m.constant);
  4613. break;
  4614. case ClassNode::Member::SIGNAL:
  4615. print_signal(m.signal);
  4616. break;
  4617. case ClassNode::Member::FUNCTION:
  4618. print_function(m.function);
  4619. break;
  4620. case ClassNode::Member::ENUM:
  4621. print_enum(m.m_enum);
  4622. break;
  4623. case ClassNode::Member::ENUM_VALUE:
  4624. break; // Nothing. Will be printed by enum.
  4625. case ClassNode::Member::GROUP:
  4626. break; // Nothing. Groups are only used by inspector.
  4627. case ClassNode::Member::UNDEFINED:
  4628. push_line("<unknown member>");
  4629. break;
  4630. }
  4631. }
  4632. decrease_indent();
  4633. }
  4634. void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
  4635. push_text("Constant ");
  4636. print_identifier(p_constant->identifier);
  4637. increase_indent();
  4638. push_line();
  4639. push_text("= ");
  4640. if (p_constant->initializer == nullptr) {
  4641. push_text("<missing value>");
  4642. } else {
  4643. print_expression(p_constant->initializer);
  4644. }
  4645. decrease_indent();
  4646. push_line();
  4647. }
  4648. void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
  4649. push_line("{");
  4650. increase_indent();
  4651. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  4652. print_expression(p_dictionary->elements[i].key);
  4653. if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
  4654. push_text(" : ");
  4655. } else {
  4656. push_text(" = ");
  4657. }
  4658. print_expression(p_dictionary->elements[i].value);
  4659. push_line(" ,");
  4660. }
  4661. decrease_indent();
  4662. push_text("}");
  4663. }
  4664. void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
  4665. if (p_expression == nullptr) {
  4666. push_text("<invalid expression>");
  4667. return;
  4668. }
  4669. switch (p_expression->type) {
  4670. case Node::ARRAY:
  4671. print_array(static_cast<ArrayNode *>(p_expression));
  4672. break;
  4673. case Node::ASSIGNMENT:
  4674. print_assignment(static_cast<AssignmentNode *>(p_expression));
  4675. break;
  4676. case Node::AWAIT:
  4677. print_await(static_cast<AwaitNode *>(p_expression));
  4678. break;
  4679. case Node::BINARY_OPERATOR:
  4680. print_binary_op(static_cast<BinaryOpNode *>(p_expression));
  4681. break;
  4682. case Node::CALL:
  4683. print_call(static_cast<CallNode *>(p_expression));
  4684. break;
  4685. case Node::CAST:
  4686. print_cast(static_cast<CastNode *>(p_expression));
  4687. break;
  4688. case Node::DICTIONARY:
  4689. print_dictionary(static_cast<DictionaryNode *>(p_expression));
  4690. break;
  4691. case Node::GET_NODE:
  4692. print_get_node(static_cast<GetNodeNode *>(p_expression));
  4693. break;
  4694. case Node::IDENTIFIER:
  4695. print_identifier(static_cast<IdentifierNode *>(p_expression));
  4696. break;
  4697. case Node::LAMBDA:
  4698. print_lambda(static_cast<LambdaNode *>(p_expression));
  4699. break;
  4700. case Node::LITERAL:
  4701. print_literal(static_cast<LiteralNode *>(p_expression));
  4702. break;
  4703. case Node::PRELOAD:
  4704. print_preload(static_cast<PreloadNode *>(p_expression));
  4705. break;
  4706. case Node::SELF:
  4707. print_self(static_cast<SelfNode *>(p_expression));
  4708. break;
  4709. case Node::SUBSCRIPT:
  4710. print_subscript(static_cast<SubscriptNode *>(p_expression));
  4711. break;
  4712. case Node::TERNARY_OPERATOR:
  4713. print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
  4714. break;
  4715. case Node::TYPE_TEST:
  4716. print_type_test(static_cast<TypeTestNode *>(p_expression));
  4717. break;
  4718. case Node::UNARY_OPERATOR:
  4719. print_unary_op(static_cast<UnaryOpNode *>(p_expression));
  4720. break;
  4721. default:
  4722. push_text(vformat("<unknown expression %d>", p_expression->type));
  4723. break;
  4724. }
  4725. }
  4726. void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
  4727. push_text("Enum ");
  4728. if (p_enum->identifier != nullptr) {
  4729. print_identifier(p_enum->identifier);
  4730. } else {
  4731. push_text("<unnamed>");
  4732. }
  4733. push_line(" {");
  4734. increase_indent();
  4735. for (int i = 0; i < p_enum->values.size(); i++) {
  4736. const EnumNode::Value &item = p_enum->values[i];
  4737. print_identifier(item.identifier);
  4738. push_text(" = ");
  4739. push_text(itos(item.value));
  4740. push_line(" ,");
  4741. }
  4742. decrease_indent();
  4743. push_line("}");
  4744. }
  4745. void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
  4746. push_text("For ");
  4747. print_identifier(p_for->variable);
  4748. push_text(" IN ");
  4749. print_expression(p_for->list);
  4750. push_line(" :");
  4751. increase_indent();
  4752. print_suite(p_for->loop);
  4753. decrease_indent();
  4754. }
  4755. void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
  4756. for (const AnnotationNode *E : p_function->annotations) {
  4757. print_annotation(E);
  4758. }
  4759. if (p_function->is_static) {
  4760. push_text("Static ");
  4761. }
  4762. push_text(p_context);
  4763. push_text(" ");
  4764. if (p_function->identifier) {
  4765. print_identifier(p_function->identifier);
  4766. } else {
  4767. push_text("<anonymous>");
  4768. }
  4769. push_text("( ");
  4770. for (int i = 0; i < p_function->parameters.size(); i++) {
  4771. if (i > 0) {
  4772. push_text(" , ");
  4773. }
  4774. print_parameter(p_function->parameters[i]);
  4775. }
  4776. push_line(" ) :");
  4777. increase_indent();
  4778. print_suite(p_function->body);
  4779. decrease_indent();
  4780. }
  4781. void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
  4782. if (p_get_node->use_dollar) {
  4783. push_text("$");
  4784. }
  4785. push_text(p_get_node->full_path);
  4786. }
  4787. void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
  4788. if (p_identifier != nullptr) {
  4789. push_text(p_identifier->name);
  4790. } else {
  4791. push_text("<invalid identifier>");
  4792. }
  4793. }
  4794. void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
  4795. if (p_is_elif) {
  4796. push_text("Elif ");
  4797. } else {
  4798. push_text("If ");
  4799. }
  4800. print_expression(p_if->condition);
  4801. push_line(" :");
  4802. increase_indent();
  4803. print_suite(p_if->true_block);
  4804. decrease_indent();
  4805. // FIXME: Properly detect "elif" blocks.
  4806. if (p_if->false_block != nullptr) {
  4807. push_line("Else :");
  4808. increase_indent();
  4809. print_suite(p_if->false_block);
  4810. decrease_indent();
  4811. }
  4812. }
  4813. void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
  4814. print_function(p_lambda->function, "Lambda");
  4815. push_text("| captures [ ");
  4816. for (int i = 0; i < p_lambda->captures.size(); i++) {
  4817. if (i > 0) {
  4818. push_text(" , ");
  4819. }
  4820. push_text(p_lambda->captures[i]->name.operator String());
  4821. }
  4822. push_line(" ]");
  4823. }
  4824. void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
  4825. // Prefix for string types.
  4826. switch (p_literal->value.get_type()) {
  4827. case Variant::NODE_PATH:
  4828. push_text("^\"");
  4829. break;
  4830. case Variant::STRING:
  4831. push_text("\"");
  4832. break;
  4833. case Variant::STRING_NAME:
  4834. push_text("&\"");
  4835. break;
  4836. default:
  4837. break;
  4838. }
  4839. push_text(p_literal->value);
  4840. // Suffix for string types.
  4841. switch (p_literal->value.get_type()) {
  4842. case Variant::NODE_PATH:
  4843. case Variant::STRING:
  4844. case Variant::STRING_NAME:
  4845. push_text("\"");
  4846. break;
  4847. default:
  4848. break;
  4849. }
  4850. }
  4851. void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
  4852. push_text("Match ");
  4853. print_expression(p_match->test);
  4854. push_line(" :");
  4855. increase_indent();
  4856. for (int i = 0; i < p_match->branches.size(); i++) {
  4857. print_match_branch(p_match->branches[i]);
  4858. }
  4859. decrease_indent();
  4860. }
  4861. void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
  4862. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  4863. if (i > 0) {
  4864. push_text(" , ");
  4865. }
  4866. print_match_pattern(p_match_branch->patterns[i]);
  4867. }
  4868. push_line(" :");
  4869. increase_indent();
  4870. print_suite(p_match_branch->block);
  4871. decrease_indent();
  4872. }
  4873. void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
  4874. switch (p_match_pattern->pattern_type) {
  4875. case PatternNode::PT_LITERAL:
  4876. print_literal(p_match_pattern->literal);
  4877. break;
  4878. case PatternNode::PT_WILDCARD:
  4879. push_text("_");
  4880. break;
  4881. case PatternNode::PT_REST:
  4882. push_text("..");
  4883. break;
  4884. case PatternNode::PT_BIND:
  4885. push_text("Var ");
  4886. print_identifier(p_match_pattern->bind);
  4887. break;
  4888. case PatternNode::PT_EXPRESSION:
  4889. print_expression(p_match_pattern->expression);
  4890. break;
  4891. case PatternNode::PT_ARRAY:
  4892. push_text("[ ");
  4893. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  4894. if (i > 0) {
  4895. push_text(" , ");
  4896. }
  4897. print_match_pattern(p_match_pattern->array[i]);
  4898. }
  4899. push_text(" ]");
  4900. break;
  4901. case PatternNode::PT_DICTIONARY:
  4902. push_text("{ ");
  4903. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  4904. if (i > 0) {
  4905. push_text(" , ");
  4906. }
  4907. if (p_match_pattern->dictionary[i].key != nullptr) {
  4908. // Key can be null for rest pattern.
  4909. print_expression(p_match_pattern->dictionary[i].key);
  4910. push_text(" : ");
  4911. }
  4912. print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
  4913. }
  4914. push_text(" }");
  4915. break;
  4916. }
  4917. }
  4918. void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
  4919. print_identifier(p_parameter->identifier);
  4920. if (p_parameter->datatype_specifier != nullptr) {
  4921. push_text(" : ");
  4922. print_type(p_parameter->datatype_specifier);
  4923. }
  4924. if (p_parameter->initializer != nullptr) {
  4925. push_text(" = ");
  4926. print_expression(p_parameter->initializer);
  4927. }
  4928. }
  4929. void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
  4930. push_text(R"(Preload ( ")");
  4931. push_text(p_preload->resolved_path);
  4932. push_text(R"(" )");
  4933. }
  4934. void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
  4935. push_text("Return");
  4936. if (p_return->return_value != nullptr) {
  4937. push_text(" ");
  4938. print_expression(p_return->return_value);
  4939. }
  4940. push_line();
  4941. }
  4942. void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
  4943. push_text("Self(");
  4944. if (p_self->current_class->identifier != nullptr) {
  4945. print_identifier(p_self->current_class->identifier);
  4946. } else {
  4947. push_text("<main class>");
  4948. }
  4949. push_text(")");
  4950. }
  4951. void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
  4952. push_text("Signal ");
  4953. print_identifier(p_signal->identifier);
  4954. push_text("( ");
  4955. for (int i = 0; i < p_signal->parameters.size(); i++) {
  4956. print_parameter(p_signal->parameters[i]);
  4957. }
  4958. push_line(" )");
  4959. }
  4960. void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
  4961. print_expression(p_subscript->base);
  4962. if (p_subscript->is_attribute) {
  4963. push_text(".");
  4964. print_identifier(p_subscript->attribute);
  4965. } else {
  4966. push_text("[ ");
  4967. print_expression(p_subscript->index);
  4968. push_text(" ]");
  4969. }
  4970. }
  4971. void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
  4972. switch (p_statement->type) {
  4973. case Node::ASSERT:
  4974. print_assert(static_cast<AssertNode *>(p_statement));
  4975. break;
  4976. case Node::VARIABLE:
  4977. print_variable(static_cast<VariableNode *>(p_statement));
  4978. break;
  4979. case Node::CONSTANT:
  4980. print_constant(static_cast<ConstantNode *>(p_statement));
  4981. break;
  4982. case Node::IF:
  4983. print_if(static_cast<IfNode *>(p_statement));
  4984. break;
  4985. case Node::FOR:
  4986. print_for(static_cast<ForNode *>(p_statement));
  4987. break;
  4988. case Node::WHILE:
  4989. print_while(static_cast<WhileNode *>(p_statement));
  4990. break;
  4991. case Node::MATCH:
  4992. print_match(static_cast<MatchNode *>(p_statement));
  4993. break;
  4994. case Node::RETURN:
  4995. print_return(static_cast<ReturnNode *>(p_statement));
  4996. break;
  4997. case Node::BREAK:
  4998. push_line("Break");
  4999. break;
  5000. case Node::CONTINUE:
  5001. push_line("Continue");
  5002. break;
  5003. case Node::PASS:
  5004. push_line("Pass");
  5005. break;
  5006. case Node::BREAKPOINT:
  5007. push_line("Breakpoint");
  5008. break;
  5009. case Node::ASSIGNMENT:
  5010. print_assignment(static_cast<AssignmentNode *>(p_statement));
  5011. break;
  5012. default:
  5013. if (p_statement->is_expression()) {
  5014. print_expression(static_cast<ExpressionNode *>(p_statement));
  5015. push_line();
  5016. } else {
  5017. push_line(vformat("<unknown statement %d>", p_statement->type));
  5018. }
  5019. break;
  5020. }
  5021. }
  5022. void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
  5023. for (int i = 0; i < p_suite->statements.size(); i++) {
  5024. print_statement(p_suite->statements[i]);
  5025. }
  5026. }
  5027. void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
  5028. // Surround in parenthesis for disambiguation.
  5029. push_text("(");
  5030. print_expression(p_ternary_op->true_expr);
  5031. push_text(") IF (");
  5032. print_expression(p_ternary_op->condition);
  5033. push_text(") ELSE (");
  5034. print_expression(p_ternary_op->false_expr);
  5035. push_text(")");
  5036. }
  5037. void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
  5038. if (p_type->type_chain.is_empty()) {
  5039. push_text("Void");
  5040. } else {
  5041. for (int i = 0; i < p_type->type_chain.size(); i++) {
  5042. if (i > 0) {
  5043. push_text(".");
  5044. }
  5045. print_identifier(p_type->type_chain[i]);
  5046. }
  5047. }
  5048. }
  5049. void GDScriptParser::TreePrinter::print_type_test(TypeTestNode *p_test) {
  5050. print_expression(p_test->operand);
  5051. push_text(" IS ");
  5052. print_type(p_test->test_type);
  5053. }
  5054. void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
  5055. // Surround in parenthesis for disambiguation.
  5056. push_text("(");
  5057. switch (p_unary_op->operation) {
  5058. case UnaryOpNode::OP_POSITIVE:
  5059. push_text("+");
  5060. break;
  5061. case UnaryOpNode::OP_NEGATIVE:
  5062. push_text("-");
  5063. break;
  5064. case UnaryOpNode::OP_LOGIC_NOT:
  5065. push_text("NOT");
  5066. break;
  5067. case UnaryOpNode::OP_COMPLEMENT:
  5068. push_text("~");
  5069. break;
  5070. }
  5071. print_expression(p_unary_op->operand);
  5072. // Surround in parenthesis for disambiguation.
  5073. push_text(")");
  5074. }
  5075. void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
  5076. for (const AnnotationNode *E : p_variable->annotations) {
  5077. print_annotation(E);
  5078. }
  5079. if (p_variable->is_static) {
  5080. push_text("Static ");
  5081. }
  5082. push_text("Variable ");
  5083. print_identifier(p_variable->identifier);
  5084. push_text(" : ");
  5085. if (p_variable->datatype_specifier != nullptr) {
  5086. print_type(p_variable->datatype_specifier);
  5087. } else if (p_variable->infer_datatype) {
  5088. push_text("<inferred type>");
  5089. } else {
  5090. push_text("Variant");
  5091. }
  5092. increase_indent();
  5093. push_line();
  5094. push_text("= ");
  5095. if (p_variable->initializer == nullptr) {
  5096. push_text("<default value>");
  5097. } else {
  5098. print_expression(p_variable->initializer);
  5099. }
  5100. push_line();
  5101. if (p_variable->property != VariableNode::PROP_NONE) {
  5102. if (p_variable->getter != nullptr) {
  5103. push_text("Get");
  5104. if (p_variable->property == VariableNode::PROP_INLINE) {
  5105. push_line(":");
  5106. increase_indent();
  5107. print_suite(p_variable->getter->body);
  5108. decrease_indent();
  5109. } else {
  5110. push_line(" =");
  5111. increase_indent();
  5112. print_identifier(p_variable->getter_pointer);
  5113. push_line();
  5114. decrease_indent();
  5115. }
  5116. }
  5117. if (p_variable->setter != nullptr) {
  5118. push_text("Set (");
  5119. if (p_variable->property == VariableNode::PROP_INLINE) {
  5120. if (p_variable->setter_parameter != nullptr) {
  5121. print_identifier(p_variable->setter_parameter);
  5122. } else {
  5123. push_text("<missing>");
  5124. }
  5125. push_line("):");
  5126. increase_indent();
  5127. print_suite(p_variable->setter->body);
  5128. decrease_indent();
  5129. } else {
  5130. push_line(" =");
  5131. increase_indent();
  5132. print_identifier(p_variable->setter_pointer);
  5133. push_line();
  5134. decrease_indent();
  5135. }
  5136. }
  5137. }
  5138. decrease_indent();
  5139. push_line();
  5140. }
  5141. void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
  5142. push_text("While ");
  5143. print_expression(p_while->condition);
  5144. push_line(" :");
  5145. increase_indent();
  5146. print_suite(p_while->loop);
  5147. decrease_indent();
  5148. }
  5149. void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
  5150. ERR_FAIL_NULL_MSG(p_parser.get_tree(), "Parse the code before printing the parse tree.");
  5151. if (p_parser.is_tool()) {
  5152. push_line("@tool");
  5153. }
  5154. if (!p_parser.get_tree()->icon_path.is_empty()) {
  5155. push_text(R"(@icon (")");
  5156. push_text(p_parser.get_tree()->icon_path);
  5157. push_line("\")");
  5158. }
  5159. print_class(p_parser.get_tree());
  5160. print_line(String(printed));
  5161. }
  5162. #endif // DEBUG_ENABLED