gdscript_parser.cpp 151 KB

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