gdscript_parser.cpp 167 KB

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