gdscript_parser.cpp 143 KB

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