gdscript_parser.cpp 168 KB

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