gdscript_parser.cpp 138 KB

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