gdscript_parser.cpp 185 KB

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