gdscript_parser.cpp 148 KB

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