2
0

gdscript_parser.cpp 169 KB

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