gdscript_parser.cpp 183 KB

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