gdscript_parser.cpp 168 KB

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