gdscript_parser.cpp 170 KB

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