gdscript_parser.cpp 147 KB

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