gdscript_parser.cpp 198 KB

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