gdscript_parser.cpp 147 KB

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