gdscript_parser.cpp 168 KB

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